Some ADB utility functions

Filed Under (android, bash) by Nathan Schwermann on 16-03-2013

Tagged Under : , ,

It is always such a pain debugging when you have multiple devices and emulators connected at the same time. I hate the dreaded “error: more than once device and emulator” message or “-waiting for device” when trying to view logcat.


So today I wrote some helper functions for my bash profile that will offer a menu to select what device to use when more than one is available. It is assumed that both adb and Jeff Sharkey’s coloredlogcat script are in your $PATH variable. If not, it shouldn’t be hard to modify the code to use direct paths.

adbd () {
	adb -s $(get_device) "$@"
}
 
function get_device() {
	local devices=$(adb devices | grep device$)
	if [ $(wc -l <<< "$devices") -eq 1 ]; then
		awk {'print $1'} <<< "$devices" 
	else
		IFS=$'\n' devices=($devices)
		unset IFS
		local device
		PS3="Select a device # "
		select device in "${devices[@]}"; do
			if [ -n "$device" ]; then
				awk {'print $1'} <<< "$device"
			fi
			break
		done
	fi
}
 
function logcat(){
	local device
	device=$(get_device)
	if [ -z "$1" ]
	then
		adb -s $device logcat | coloredlogcat.py
   	else
      		local filters=""
      		for f in $@
      		do
			export filters="$filters $f:*"
      		done
      		echo "filters $filters"
		adb -s $device logcat $filters *:S | coloredlogcat.py    
  	 fi
}

The usage goes as follow, after adding to your bash profile (add to ~./bash_profile on OSX or ~/.bashrc on linux) you can use the follow commands:

deviceid=$(get_device)


Full Source Here

Using Scribe with Android

Filed Under (android, java, programming) by Nathan Schwermann on 13-04-2011

Tagged Under : , , , , ,

Recently I have been working on signing in with social networks with Android applications. I found a great article using Twitter4J to log in with twitter but I would like to expand on that article and rather than relying on an intent-filter and the default android browser I am adding a WebViewClient to handle the callback url.

Using an intent-filter and the default browser has two problems. ¬†One, depending on what browser the user has set as their default browser there is a chance that the browser won’t initiate an ACTION_VIEW intent but rather just attempt to load the callback url. Secondly, when your app goes into the background and the default browser opens there is a chance that onDestory would be called on the Activity and then onNewIntent wouldn’t be called. Although that could be handled in a number of different ways. Finally, instead of using Twitter4J I opted for Scribe instead. Mainly because it is designed to work with and already has support for many other social networks besides Twitter.

It just about 80 lines of code we can have the user sign in and verify their account. Of course we have no error handling yet, and the next step would be to move this to the new Fragment API to so you can easily attach it to any Activity to sign in with Twitter.

 

package net.schwiz.oauth;

import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

/**
 *Demonstrates how to use the scribe library to login with twitter.
 *
 */
public class Main extends Activity {
	
	final static String APIKEY = null;
	final static String APISECRET = null;
	final static String CALLBACK = "oauth://twitter";
		
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final TextView textView = (TextView)findViewById(R.id.textview);
        final  WebView webview = (WebView) findViewById(R.id.webview);
        
        if(APIKEY == null || APISECRET == null){
        	textView.setText("You must enter your own APIKEY and SECRET to use this demo.  dev.twitter.com");
        	webview.setVisibility(View.GONE);
        	return;
        }
        
        //set up service and get request token as seen on scribe website 
        //https://github.com/fernandezpablo85/scribe-java/wiki/Getting-Started
        final OAuthService s = new ServiceBuilder()
        .provider(TwitterApi.class)
		.apiKey(APIKEY)
		.apiSecret(APISECRET)
		.callback(CALLBACK)
		.build();

		final Token requestToken = s.getRequestToken();
		final String authURL = s.getAuthorizationUrl(requestToken);
        
        //attach WebViewClient to intercept the callback url
        webview.setWebViewClient(new WebViewClient(){
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url) {
        		
        		//check for our custom callback protocol otherwise use default behavior
        		if(url.startsWith("oauth")){
        			//authorization complete hide webview for now.
        			webview.setVisibility(View.GONE);
        			
        			Uri uri = Uri.parse(url);
        			String verifier = uri.getQueryParameter("oauth_verifier");
        			Verifier v = new Verifier(verifier);
        			
        			//save this token for practical use.
        			Token accessToken = s.getAccessToken(requestToken, v);
        			
        			//host twitter detected from callback oauth://twitter
        			if(uri.getHost().equals("twitter")){
	        			OAuthRequest req = new OAuthRequest(Verb.GET, "http://api.twitter.com/1/account/verify_credentials.json");
	        			s.signRequest(accessToken, req);
	        			Response response = req.send();
	        			try {
							JSONObject json = new JSONObject(response.getBody());
							textView.setText(json.toString(3));
						} catch (JSONException e) {
							e.printStackTrace();
						}
        			}
        			
        			return true;
        		}
        		
        		
        		return super.shouldOverrideUrlLoading(view, url);
        	}
        });
        

        //send user to authorization page
        webview.loadUrl(authURL);
    }
}

 
Don’t forget to add the internet permission to your manifest! Also please note you will get a forceclose if you don’t add your own twitter API key. If you would like the full source code you can find it here.

Android – new line, shmew line

Filed Under (android, java, programming) by Nathan Schwermann on 26-01-2010

Tagged Under : , ,

In a previous blog post I talked about how to avoid having your users make a new line when the press enter on an EditText view in your Android applications. It was a hack way where you had to make your own EditText class and override onKeyDown. It works just fine but since then I have found a much easier way to achieve the same goal.

First your activity or dialog needs to implement OnEditorActionListener, set the onEditorActionListener in onCreate and…. thats it!!!! Right out of the box the implemented method automatically cancels sends a null character instead of a new line character when you press enter.

public class AdjustStringDialog extends Dialog  implements android.view.View.OnClickListener, OnEditorActionListener{

	private EditText editTextView;
	
	public AdjustStringDialog(Context context, UnderlinedView mV) {
		super(context);
		setTitle("My Dialog Box");
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adjuststring);
		retisterViews();
		editTextView.setOnEditorActionListener(this);
	}
	private void retisterViews() {
		editTextView = (EditText)findViewById(R.id.editString);
		findViewById(R.id.finishedAdjustString).setOnClickListener(this);		
	}
	@Override
	public void onClick(View v) {
		closeDialog();	
		
	}
	private void closeDialog() {
		//do what you want with the entered text
		dismiss();
		//update UI with new text if needed
	}
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		closeDialog();
		return false;
	}

}

Of course you can detect any key that is being pressed aside from the enter key with the event argument, and you can handle cases like the ‘Next’ button with actionId as well. Know any other ways to accomplish this, or care to share something you implemented with onEditorAction feel free to comment!
Cheers and happy 2010!

Android WolframAlpha Launcher

Filed Under (android, java, math, programming) by Nathan Schwermann on 16-09-2009

Tagged Under : , , , ,

Ahoy Ahoy it has been way to long I need to write you more often, but I have been busy with school, and before that I had video games to play. Being busy with school is what ultimately let to the project I want to talk about today. Recently, while studying for my Calculus 2 class I found this amazing website WolframAlpha which is what they call a computational engine. It can do all kinds of awesome stuff I have barely scratched the surface on playing with its different capabilities. I mainly use it to quickly look up integrals and sums while doing Calc homework.

Long story short, I ended up using my G1 daily to look up integrals on my phone and I wanted a faster way to do it. After applying for a code to access their online API and never hearing back I decided the next best thing was to just make a quick launcher similar to the one Wolfram released for Vista.

It came together pretty quickly I think its the first program I was able to finish in one day, and bug free to boot (it seems).
WolframAlpha Quicklaunch

It was pretty hassle free but I did run into a little snag I want to talk about. By default when pressing the enter key in the edit text box Android will make a new line, I wanted to launch the website. Getting this behavior was by far the most challenging thing to do in this project.

In order to pull this off you need to make your own EditText class that inherits from Android’s EditText class. Then, you have to override the onKeyDown function for the EditText class.

	public static class MyEditView extends EditText {
		//ref to the nesting the view
		walauncher launcher;
		
		public MyEditView(Context context, AttributeSet attrs) {
			super(context,attrs);
			this.launcher = (walauncher)context;
		}
		
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {	
			switch(keyCode){
			case KeyEvent.KEYCODE_ENTER:
				launcher.launchWebsite();
				break;
			}
			return super.onKeyDown(keyCode, event);
		}
		
		@Override
		public Editable getText() {
			// TODO Auto-generated method stub
			return super.getText();
		}		
	}

Thats the easy part, what is tricky is how do you actually use it in your XML layout for the app? For starters notice how the class is static in the code above, also it has to be nested inside the Activity class that will be using it. Then in the XML file you need to add a View tag with an attribute called class which equals yourpackage.activityname$nameOfTheCustomClass

<view
	class = "net.schwiz.wolfram.walauncher$MyEditView"
	android:id="@+id/inputID" 
	android:text="" 
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	android:layout_weight="4"
	android:maxLines="1" android:inputType="text|textImeMultiLine">
</view>

Well ok I guess that wasn’t so tuff but it took me a while to find out how to do this on the developers website, they do this in the notepad tutorial though if you want another example. If you want to install my app search for schwiz on the Android Market. I went ahead and released the source, it can be found here.

UPDATE: After over a year in the market WolframAlpha contacted me to let me know my app is in violation of their website’s TOS and forced me to remove it from the market. I updated the source to remove the WolframAlpha feature but keep the math keyboard for the system. I moved the source over to github with the updated codebase. It can be found here.