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.

Share

Comments:

Make a comment

You must be logged in to post a comment.