Skip to content

Instantly share code, notes, and snippets.

@takuo
Created October 20, 2011 09:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuo/1300725 to your computer and use it in GitHub Desktop.
Save takuo/1300725 to your computer and use it in GitHub Desktop.
Android code snippet - OAuth verifier process (with Twitter4J)
public class OAuthVerify extends Activity {
private static final String CONSUMER_KEY = "";
private static final String CONSUMER_SECRET = "";
private static final String CALLBACK_URL = "myoauthapp://oauthcallback/";
private Context mContext;
private WebView mWebView;
private Twitter mTwitter;
private RequestToken mRequestToken;
private AccessToken mAccessToken;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
// Add here initialize mTwitter object with Twitter4J
mTwitter = new TwitterFactory().getInstance();
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
mRequestToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
mContext = getApplicationContext();
mIntent = getIntent();
mWebView = (WebView)findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (url.startsWith(CALLBACK_URL)) {
Uri uri = Uri.parse(url);
completeVerify(uri);
return true;
}
return false;
}
});
mWebView.getSettings().setAppCacheEnabled(false);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.clearCache(true);
mWebView.clearFormData();
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
final Activity activity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView w, int p) {
activity.setProgress(p * 100);
}
});
// AsyncTask to load mRequestToken.getAuthorizationURL() into mWebView
OAuthTask oauthTask = new OAuthTask();
oauthTask.execute();
}
private void completeVerify(Uri uri) {
if (uri != null) {
String verifier = uri.getQueryParameter("oauth_verifier");
try {
mAccessToken = mTwitter.getOAuthAccessToken(mRequestToken, verifier);
mTwitter.setOAuthAccessToken(mAccessToken);
// Add code here to save the OAuth AccessToken and AccessTokenSecret into SharedPreferences
} catch (Exception e) {
Log.d(LOG_TAG, "Cannot get AccessToken: " + e.getMessage());
}
setResult(Activity.RESULT_OK, mIntent);
finish();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment