Saturday 11 October 2014

Android Twitter Integration with Twitter4j

1. Refer twitter development site before continuing: https://dev.twitter.com/
2. Create your Twitter application on Twitter.
3. Save Access token and Access token secret in your application(Save in your constant file).
4. Download twitter4j jar file from http://twitter4j.org/en/index.html.
5. Create OAuthWebViewActivity.java with WebView.
6. Make a manifest entry for this:

<activity  
 android:name="com.android.sample.OAuthWebViewActivity"  
 android:launchMode="singleInstance"  
 android:theme="@android:style/Theme.Black.NoTitleBar" >  
 <intent-filter>  
 <action android:name="android.intent.action.VIEW" />  
 <category android:name=”android.intent.category.DEFAULT” />  
 <category android:name=”android.intent.category.BROWSABLE” />  
 <data  
 android:host=”callback”  
 android:scheme=”sample” />  
 </intent-filter>  
 </activity> 

7. Build your authentication process in OAuthWebViewActivity.java:
public class OAuthWebViewActivity extends Activity{  
 final String TAG = getClass().getName();  
 private WebView mWebview;  
 private Twitter mTwitter;  
 private RequestToken mTwitterRequestToken;  
 private SharedPreferences mPref = null;  
 private int mResult = -1;  
 @Override  
 public void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 setContentView(R.layout.auth_layout);  
 mPref = getSharedPreferences(APP_PREFERENCE_NAME, MODE_PRIVATE);  
 mWebview = (WebView)findViewById(R.id.web);  
 mWebview.getSettings().setJavaScriptEnabled(true);  
 mWebview.getSettings().setBuiltInZoomControls(true);  
 mWebview.getSettings().setRenderPriority(RenderPriority.HIGH);  
 mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  
 class MyWebViewClient extends WebViewClient {  
 @Override  
 public boolean shouldOverrideUrlLoading(WebView view, String url) {  
 if (Uri.parse(url).getHost().equals("callback")) {  
 // This is your web site, so do not override; let the WebView to load the page  
 Uri uri = Uri.parse(url);  
 new RetrieveAccessToken(uri.getQueryParameter("oauth_verifier")).execute();  
 return true;  
 }  
 // Otherwise, the link is not for a page on my site,  
 //so launch another Activity that handles URLs  
 return false;  
 }  
 }  
 mWebview.setWebViewClient(new MyWebViewClient());  
 new OAuthTokenTask().execute();  
 }  
 private void redirect(){  
 setResult(mResult);  
 finish();  
 }  
 class RetrieveAccessToken extends AsyncTask<Void, Void, Void> {  
 private String oAuthVerifier;  
 public RetrieveAccessToken(String oAuthVerifier) {  
 this.oAuthVerifier = oAuthVerifier;  
 }  
 @Override  
 protected void onPreExecute() {  
 super.onPreExecute();  
 }  
 /**  
 * Store the oauth_token and oauth_token_secret  
 * for future API calls.  
 */  
 @Override  
 protected Void doInBackground(Void... params) {  
 // TODO Auto-generated method stub  
 try {  
 AccessToken accessToken = mTwitter.getOAuthAccessToken(mTwitterRequestToken, oAuthVerifier);  
 DebugUtil.printLog(TAG, "Access Token Retrieved.", Log.INFO);  
 Editor edit = mPref.edit();  
 edit.putString(APIConstant.TWITTER_TOKEN, accessToken.getToken());  
 edit.putString(APIConstant.TWITTER_TOKEN_SECRET, accessToken.getTokenSecret());  
 edit.commit();  
 mResult = RESULT_OK;  
 redirect();  
 } catch (Exception e) {  
 // TODO Auto-generated catch block  
 mResult = RESULT_CANCELED;  
 Log.e(TAG, "Access token failed: ", e);  
 redirect();  
 }  
 return null;  
 }  
 @Override  
 protected void onPostExecute(Void result) {  
 // TODO Auto-generated method stub  
 super.onPostExecute(result);  
 }  
 }  
 class OAuthTokenTask extends AsyncTask<Void, Void, Void> {  
 @Override  
 protected Void doInBackground(Void... params) {  
 try {  
 ConfigurationBuilder builder = new ConfigurationBuilder();  
 builder.setOAuthConsumerKey(APIConstant.TWITTER_API_KEY);  
 builder.setOAuthConsumerSecret(APIConstant.TWITTER_SECRET_KEY);  
 TwitterFactory factory = new TwitterFactory(builder.build());  
 mTwitter = factory.getInstance();  
 mTwitterRequestToken = mTwitter.getOAuthRequestToken(APIConstant.TWITTER_CALLBACK_URL);  
 String authUrl = mTwitterRequestToken.getAuthorizationURL();  
 mWebview.loadUrl(authUrl);  
 } catch (Exception e) {  
 mResult = RESULT_CANCELED;  
 Log.e(TAG, "Error during OAUth retrieve request token: ", e);  
 redirect();  
 }  
 return null;  
 }  
 }  
 }  

No comments:

Post a Comment