|
Page 5 of 5
Twitter4j
To send the tweets, we use the excellent Twitter4j library available here. The twitter-4j-core-android... jar is added to our projects /lib folder. Using this library vastly simplifies the code needed to connect to the Twitter service - heres our TwitterWidgetActivity in full:
/*
* Copyright (c) 2011 OTAMate Technology Ltd. All Rights Reserved.
* http://www.androidacademy.com
*/
package com.androidacademy.tutorials.twitterwidget;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
public class TwitterWidgetActivity extends Activity {
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
private EditText mTwitterEditText;
private TextView mTwitterDialogMessage;
private Button mSendButton;
private Button mCancelButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If the user backs out of the widget placement, tell the widget host
setResult(RESULT_CANCELED);
LayoutInflater factory = LayoutInflater.from( this );
View mainView = factory.inflate( R.layout.send_tweet, null );
mTwitterEditText = (EditText) mainView.findViewById (R.id.twitterText );
mTwitterDialogMessage = (TextView) mainView.findViewById (R.id.twitterDialogMessage );
mSendButton = (Button) mainView.findViewById( R.id.button_send);
mCancelButton = (Button) mainView.findViewById( R.id.button_cancel);
setContentView(mainView);
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!"".equals(mTwitterEditText.getText().toString())) {
final SharedPreferences settings =
getSharedPreferences(Constants.SHARED_PREF_CONFIG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(Constants.KEY_LAST_TWEET_TEXT,
mTwitterEditText.getText().toString());
editor.commit();
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
// If we've got here with no Twitter auth token we need to get one
if ("".equals(settings.getString(Constants.KEY_ACCESS_TOKEN, ""))) {
TwitterWidgetActivity.this.startActivity(
new Intent(TwitterWidgetActivity.this, AuthoriseTwitterActivity.class));
} else {
new Thread(
new Runnable() {
public void run() {
AccessToken accessToken = new AccessToken(
settings.getString(Constants.KEY_ACCESS_TOKEN, ""),
settings.getString(Constants.KEY_ACCESS_TOKEN_SECRET, ""));
twitter.setOAuthAccessToken(accessToken);
try {
Intent update = new Intent(TwitterWidgetActivity.this,
TwitterWidgetProvider.class);
update.setAction(Constants.UPDATE);
sendBroadcast(update);
twitter.updateStatus(settings.getString(
Constants.KEY_LAST_TWEET_TEXT, ""));
finish();
} catch (Exception e) {}
}
}
).start();
}
} else {
Toast.makeText(getApplicationContext(),
getString(R.string.toast_no_text_entered), Toast.LENGTH_SHORT).show();
}
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences settings =
getSharedPreferences(Constants.SHARED_PREF_CONFIG, Context.MODE_PRIVATE);
// If we've been added as a widget we don't need to explain how to do it
if (!"".equals(settings.getString(Constants.KEY_ACCESS_TOKEN, ""))) {
mTwitterDialogMessage.setVisibility(View.GONE);
}
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.widget);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
}
}
}
Notice how we retrieve the consumer key and secret we stored earlier and use it to set authorisation on the Twitter object we ultimately call updateStatus() on - that's the call that actually sends the tweet. Notice also this is done in its own thread to keep the UI snappy.
That's about it for this one - I'd suggest you download the source and run it in Eclipse, setting breakpoints at the various points in the code I highlighted. As usual, this tutorial is intended just to get the basics across. If you were to implement a fuller Twitter client you'd have to deal with the history, the timeline, following and retweeting etc - all of which are available using appropriate API calls.
The app is available in the market here.
|