Tuesday, February 19, 2013

Posting message on Twitter

I have used twitter4j-core-3.0.3.jar and twitter4j-media-support-3.0.3.jar for posting.

1. Create an instance of TwitterApp class by passing context, consumerKey and secretKey.
2. For handling twitter login callbacks we need to create a class which implements TwDialogListener interface.
3. Before sharing on Twitter, we needs to check user twitter authentication using hasAccessToken(). If the token available means valid user otherwise we needs to show login page using authorize().
4. First time hasAccessToken() value will be null. So, authorize() will be called and internally(in TwitterApp class) it will get the authorization url by using consumerKey, secretKey and callbackUrl.
5. After retrieving authorization url, it will be loaded in Twitter dialog using webview.
6. By using custom webview client, shouldOverrideUrlLoading() - checks each url whether it is starting with callbackUrl. If we get url starts with callbackUrl means authorization process completed. At this time we need to store accessToken and necessary information in shared preferences for future use.
7. After storing all the necessary details, mTwLoginDialogListener's onComplete() will be called. Here we need to post message on Twitter.
8. Using updateStatus() of StatusUpdate class, we can post message on Twitter.

package com.android.sot;

import twitter4j.StatusUpdate;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.android.sot.twitter.TwitterApp;
import com.android.sot.twitter.TwitterApp.TwDialogListener;

public class TwitterShare extends Activity
{
private static final String TWITTER_CONSUMER_KEY = "Your twitter consumer key";
private static final String TWITTER_SECRET_KEY = "Your twitter secret key";

private Handler mHandler;
private TwitterApp mTwitter;
private ProgressDialog progressdialog;

@Override
protected void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_twitter_share);

  mHandler = new Handler();
    mTwitter = new TwitterApp(this, TWITTER_CONSUMER_KEY,TWITTER_SECRET_KEY);
  mTwitter.setListener(mTwLoginDialogListener);

  Button btnShare = (Button) findViewById(R.id.btnShare);
  btnShare.setOnClickListener(new OnClickListener()
  {
    @Override
      public void onClick(View v)
      {
        if (mTwitter.hasAccessToken())
        postMsgOnTwitter("Hi, This is from Android App");
        else
        mTwitter.authorize();
    }
  });
}

private TwDialogListener mTwLoginDialogListener = new TwDialogListener()
{
  @Override
             public void onComplete(String value)
             {
      postMsgOnTwitter("Hi, This is from Android App");
             }

  @Override
             public void onError(String value)
             {
            showToast("Twitter login failed");
                    mTwitter.resetAccessToken();
              }
      };
 
      private void postMsgOnTwitter(final String msg)
      {
    showProgressDialog("sending tweet..");

  new Thread(new Runnable()
  {
    @Override
      public void run()
      {
        StatusUpdate status = new StatusUpdate(msg);

        try
        {
          mTwitter.updateStatus(status);

          hideProgressDialog();

          showToast("Posted successfully.");
        }
        catch (Exception e)
        {
          hideProgressDialog();

          showToast("Failed to Tweet");
          e.printStackTrace();
        }
    }
  }).start();
}
 
  public void showToast(final String msg)
{
  mHandler.post(new Runnable()
  {
    @Override
    public void run()
    {
      Toast.makeText(TwitterShare.this, msg, Toast.LENGTH_SHORT).show();
    }
  });
}

     /** This will shows a progress dialog with loading text, this is useful to call when some other                          *functionality is taking place.
  */
  public void showProgressDialog(String msg)
  {
    runOnUiThread(new RunShowLoader(msg, false));
  }

  /**
  * Implementing Runnable for runOnUiThread(), This will show a progress dialog
  */
class RunShowLoader implements Runnable
{
  private String strMsg;
  private boolean isCancalable;

  public RunShowLoader(String strMsg, boolean isCancalable)
  {
    this.strMsg = strMsg;
    this.isCancalable = isCancalable;
  }

  @Override
  public void run()
  {
    try
    {
      if(progressdialog == null ||(progressdialog != null && !progressdialog.isShowing()))
      {
        progressdialog = ProgressDialog.show(TwitterShare.this, "", strMsg);
        progressdialog.setCancelable(isCancalable);
      }
    }
    catch(Exception e)
    {
      progressdialog = null;
      e.printStackTrace();
    }
  }
}

  /** For hiding progress dialog **/
public void hideProgressDialog()
{
  runOnUiThread(new Runnable()
  {
    @Override
    public void run()
    {
      try
      {
        if(progressdialog != null && progressdialog.isShowing())
        {
          progressdialog.dismiss();
        }
        progressdialog = null;
      }
      catch(Exception e)
      {
        e.printStackTrace();
      }
    }
  });
}
}

You can download the full source from here

No comments:

Post a Comment