首先,我已经完成了所有配置(twitter 键、清单中的回调等),然后我调用 twitter 并打开浏览器,然后我在 twitter 中登录并接受应用程序,然后浏览器返回到应用程序并尝试从 twitter 获得响应,但我得到 NULL 作为答案。
package com.example.fragmenttwitter;
import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity {
private final int LOGIN = 1;
private final int TweetMenu = 2;
private final int Retweet = 3;
private final int FOWLOIING = 5;
private final int SETTING = 6;
private final int LOGOUT = 7;
static String TWITTER_CONSUMER_KEY = "xxx";
static String TWITTER_CONSUMER_SECRET = "yyy";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static boolean isLogin;
private WebView wv;
private String Url = null;
Uri u;
ImageButton close;
Button cancel;
Button btnUpdateStatus;
EditText txtUpdate;
TextView lblUpdate;
TextView lblUserName;
ProgressDialog pDialog;
private PopupWindow Popup;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
/// option menu
@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
menu.add(Menu.NONE, LOGIN, Menu.NONE, "Login").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS);
SubMenu submenu = menu.addSubMenu("Option");
submenu.add(Menu.NONE, TweetMenu, Menu.NONE, "Tweet").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, FOWLOIING, Menu.NONE, "Following")
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, SETTING, Menu.NONE, "Setting").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
submenu.add(Menu.NONE, LOGOUT, Menu.NONE, "Logout").setShowAsAction(
MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case LOGIN:
if (item.getTitle().equals(("Login"))) {
loginToTwitter();
//new Login().execute();
item.setTitle("Logout");
} else {
logoutFromTwitter();
item.setTitle("Login");
}
break;
case TweetMenu:
ImageButton bt1 = (ImageButton) findViewById(R.id.imageButton1);
bt1.setVisibility(View.VISIBLE);
setContentView(R.layout.activity_main1);
Button bt_status = (Button) findViewById(R.id.btnUpdateStatus);
bt_status.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final EditText etStaus = (EditText) findViewById(R.id.txtUpdateStatus);
String status = etStaus.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
break;
case Retweet:
String retweet = txtUpdate.getText().toString();
if (retweet.trim().length() > 0) {
Twitter twitter = new TwitterFactory().getInstance();
try {
twitter.retweetStatus(Long.parseLong(retweet));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Please enter Tweet message", Toast.LENGTH_SHORT)
.show();
}
break;
case FOWLOIING:
Toast.makeText(getApplicationContext(), "Fowllowing called",
Toast.LENGTH_SHORT).show();
followingList();
break;
case SETTING:
Toast.makeText(getApplicationContext(), "setting called",
Toast.LENGTH_SHORT).show();
break;
case LOGOUT:
Toast.makeText(getApplicationContext(), "Logout called",
Toast.LENGTH_SHORT).show();
logoutFromTwitter();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
FragmentManager f = getSupportFragmentManager();
TweetList tl = new TweetList();
FragmentTransaction ft = f.beginTransaction().add(R.id.Lineary2, tl);
ft.commit();
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// check for already login in or not
if (!isTwitterLoggedInAlready()) {
Uri uri=getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
///AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
} catch (Exception e) {
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
else
Toast.makeText(getBaseContext(), "not Login",Toast.LENGTH_LONG).show();
}
}
// code to login twitter
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
new Thread(new Runnable() {
public void run() {
try {
//requestToken = twitter
//.getOAuthRequestToken(TWITTER_CALLBACK_URL);
// twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY,TWITTER_CONSUMER_SECRET);
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(requestToken
.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
}).start();
}
}
//update the stastus from twiiter app
class updateTwitterStatus extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "");
Log.i("Access Token", access_token);
Log.i("Access Token secrate", access_token_secret);
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Log.i("Access Token", accessToken.toString());
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
txtUpdate.setText("");
}
});
}
}
//Logout from twitter app
public void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
}
private boolean isTwitterLoggedInAlready() {
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
public void onResume() {
super.onResume();
}
}