我正在Android应用中实现Twitter推文消息。我能够实现Twitter登录,但我想我无法在登录后保存访问令牌,因为当我发推文时,它不会出现在我的推特墙上。我还试图干杯访问令牌并访问toke秘密,但它都是空白的。
这是我的代码:
public class MainActivity extends Activity {
Intent intent;
static String TWITTER_CONSUMER_KEY = "hide key";
static String TWITTER_CONSUMER_SECRET = "hide key";
// Preference Constants
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";
// Twitter oauth urls
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";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
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;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
sendToTwitter(status);
}
});
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
twitter4j.conf.Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
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);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
public static void sendToTwitter(String tweet) {
String access_token1 = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret1 = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("8yTg3E1eHq6YF6l6stS4tQ")
.setOAuthConsumerSecret("6spBb7gxsuUMfv50CWSjMZLVhHUEoLXxg97txoon45w")
.setOAuthAccessToken(access_token1)
.setOAuthAccessTokenSecret(access_token_secret1);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter t = tf.getInstance();
try {
t.updateStatus(tweet);
} catch (TwitterException te) {
te.printStackTrace();
}
}
有人能指出我的代码有什么不对或缺失吗?它没有抛出任何错误。
答案 0 :(得分:1)
试试这个......
private TwitterSession mSession;
private AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Activity context;
public static final String CALLBACK_URL = "twitterapp://connect";
private static final String TWITTER_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
private static final String TWITTER_AUTHORZE_URL = "https://api.twitter.com/oauth/authorize";
private static final String TWITTER_REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String MESSAGE = "There is lot more to come, Subscribe to http://....";
public TwitterApp(Activity context, String consumerKey, String secretKey) {
Log.d("tag", consumerKey + ";" + secretKey);
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey,
mSecretKey);
String request_url = TWITTER_REQUEST_URL;
String access_token_url = TWITTER_ACCESS_TOKEN_URL;
String authorize_url = TWITTER_AUTHORZE_URL;
mHttpOauthprovider = new DefaultOAuthProvider(request_url,
access_token_url, authorize_url);
mAccessToken = mSession.getAccessToken();
Log.d("tag", "Access_Token: " + mAccessToken);
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
@SuppressWarnings("deprecation")
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
Log.d("Twitter Exception * Update Status * tag", e.getMessage());
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing...");
mProgressDlg.show();
new Thread() {
@Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(
mHttpOauthConsumer, CALLBACK_URL);
what = 0;
} catch (Exception e) {
Log.d("Twitter Exception * Authorize * tag", e.getMessage());
}
mHandler.sendMessage(mHandler
.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
@Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
verifier);
mAccessToken = new AccessToken(
mHttpOauthConsumer.getToken(),
mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
what = 0;
} catch (Exception e) {
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(
oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
public void onComplete(String value) {
processToken(value);
}
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
public void onComplete(String value);
public void onError(String value);
}
}
public class TwitterSession {
private SharedPreferences sharedPref;
private static Editor editor;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
String token = sharedPref.getString(TWEET_AUTH_KEY, null);
String tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}