前面申请CONSUMER_KEY和CONSUMER_SECRET的过程就忽略了,这里直接上代码。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.twitter_demo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />    <uses-permission android:name="android.permission.INTERNET" />    <!-- Network State Permissions -->    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.twitter_demo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <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="t4jsample" android:scheme="oauth" />            </intent-filter>        </activity>    </application></manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".TwitterHomeActivity" ><TextView    android:id="@+id/textView1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignParentLeft="true"    android:layout_alignParentTop="true"    android:layout_marginLeft="106dp"    android:layout_marginTop="21dp"    android:text="@string/hello_world"    android:textColor="#A52A2A"    android:textStyle="bold"    android:typeface="serif" /><Button    android:id="@+id/button1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignLeft="@+id/textView1"    android:layout_below="@+id/textView1"    android:layout_marginTop="80dp"    android:text="Login to twitter" /><EditText    android:id="@+id/editText1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerHorizontal="true"    android:layout_centerVertical="true"    android:visibility="gone"    android:ems="10" /><Button    android:id="@+id/button2"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_below="@+id/editText1"    android:layout_centerHorizontal="true"    android:layout_marginTop="34dp"    android:visibility="gone"    android:text="Tweets" /></RelativeLayout>

AlertDialogManager.java

package com.example.twitter_demo;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;public class AlertDialogManager {public void showAlertDialog(Context context, String title, String message,Boolean status) {AlertDialog alertDialog = new AlertDialog.Builder(context).create();// Setting Dialog TitlealertDialog.setTitle(title);// Setting Dialog MessagealertDialog.setMessage(message);if (status != null)// Setting alert dialog icon// alertDialog.setIcon((status) ? R.drawable.success :// R.drawable.fail);// Setting OK ButtonalertDialog.setButton("OK", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});// Showing Alert MessagealertDialog.show();}}

ConnectionDetector.java

package com.example.twitter_demo;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.util.Log;public class ConnectionDetector {private Context _context;public ConnectionDetector(Context context) {this._context = context;}public boolean isConnectingToInternet() {ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);if (connectivity != null) {NetworkInfo[] info = connectivity.getAllNetworkInfo();if (info != null)for (int i = 0; i < info.length; i++)if (info[i].getState() == NetworkInfo.State.CONNECTED) {Log.d("Network","NETWORKnAME: " + info[i].getTypeName());return true;}}return false;}}

MainActivity.java

package com.example.twitter_demo;import twitter4j.Twitter;import twitter4j.TwitterException;import twitter4j.TwitterFactory;import twitter4j.User;import twitter4j.auth.AccessToken;import twitter4j.auth.RequestToken;import twitter4j.conf.Configuration;import twitter4j.conf.ConfigurationBuilder;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.app.ProgressDialog;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.content.pm.ActivityInfo;import android.text.Html;import android.util.Log;import android.view.Menu;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {static String TWITTER_CONSUMER_KEY = "gWuDKEHVD4Ito3TKNaexmg";static String TWITTER_CONSUMER_SECRET = "0DYm4kSSOnZ0iYmUojJPZOs0KppYivN9jiVnkba574";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";ProgressDialog pDialog;private static Twitter twitter;private static RequestToken requestToken;private static SharedPreferences mSharedPreferences;private ConnectionDetector cd;AlertDialogManager alert = new AlertDialogManager();EditText sts;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);cd = new ConnectionDetector(getApplicationContext());if (!cd.isConnectingToInternet()) {alert.showAlertDialog(MainActivity.this,"Internet Connection Error","Please connect to working Internet connection", false);return;}// Check if twitter keys are setif (TWITTER_CONSUMER_KEY.trim().length() == 0|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens","Please set your twitter oauth tokens first!", false);return;}mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {loginToTwitter();}});findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {sts = (EditText) findViewById(R.id.editText1);String status = sts.getText().toString();if (status.trim().length() > 0) {new updateTwitterStatus().execute(status);} else {Toast.makeText(getApplicationContext(),"Please enter status message",Toast.LENGTH_SHORT).show();}}});if (!isTwitterLoggedInAlready()) {Uri uri = getIntent().getData();if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {if (pDialog == null) {pDialog = new ProgressDialog(MainActivity.this);}pDialog.setMessage("Access Tiwtter...");pDialog.show();new AccessTwitter().execute(uri);}} else {findViewById(R.id.button1).setVisibility(View.GONE);findViewById(R.id.editText1).setVisibility(View.VISIBLE);findViewById(R.id.button2).setVisibility(View.VISIBLE);}}private ProgressDialog getProgressDialog() {ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);progressDialog.setTitle("login...");progressDialog.setMessage("please wait...");return progressDialog;}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.return true;}private void loginToTwitter() {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 RequestTwitter().execute();} else {Toast.makeText(getApplicationContext(),"Already Logged into twitter", Toast.LENGTH_LONG).show();}}private class RequestTwitter extends AsyncTask<String, String, String> {@Overrideprotected String doInBackground(String... params) {try {requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);} catch (TwitterException e) {e.printStackTrace();}return null;}@Overrideprotected void onPostExecute(String result) {if (requestToken != null) {Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(requestToken.getAuthenticationURL()));intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);MainActivity.this.startActivity(intent);} else {Log.e("TAG", "requstToken error");}super.onPostExecute(result);}}private class AccessTwitter extends AsyncTask<Uri, String, Boolean> {@Overrideprotected Boolean doInBackground(Uri... params) {Uri uri = params[0];if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);try {AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);// Shared PreferencesEditor 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();Log.e("Twitter OAuth Token", "> " + accessToken.getToken());long userID = accessToken.getUserId();User user = twitter.showUser(userID);String username = user.getName();Log.e("UserID: ", "userID: " + userID + "" + username);Log.v("Welcome:","Thanks:"+ Html.fromHtml("<b>Welcome " + username+ "</b>"));return true;} catch (Exception e) {Log.e("Twitter Login Error", "> " + e.getMessage(), e);}}return false;}@Overrideprotected void onPostExecute(Boolean result) {pDialog.dismiss();if (result) {findViewById(R.id.button1).setVisibility(View.GONE);findViewById(R.id.editText1).setVisibility(View.VISIBLE);findViewById(R.id.button2).setVisibility(View.VISIBLE);} else {Log.e("TAG", "accessToken error");}super.onPostExecute(result);}}private boolean isTwitterLoggedInAlready() {return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);}class updateTwitterStatus extends AsyncTask<String, String, String> {@Overrideprotected void onPreExecute() {super.onPreExecute();if (pDialog == null) {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);// Access TokenString access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");// Access Token SecretString 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 statustwitter4j.Status response = twitter.updateStatus(status);Log.d("Status", "> " + response.getText());} catch (TwitterException e) {// Error in updating statusLog.d("Twitter Update Error", e.getMessage());}return null;}protected void onPostExecute(String file_url) {// dismiss the dialog after getting all productspDialog.dismiss();// updating UI from Background ThreadrunOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplicationContext(),"Status tweeted successfully", Toast.LENGTH_SHORT).show();// Clearing EditText fieldsts.setText("");}});}}}

更多相关文章

  1. Android(安卓)PinnedSectionListView 收缩
  2. Android中imageView图片放大缩小及旋转功能示例代码
  3. Android(安卓)启动过程
  4. Twitter V1.1在Android中的应用
  5. Android(安卓)开发环境 adt-bundle android-studio sdk adt 下载
  6. Android(安卓)4.0 Launcher2源码分析——启动过程分析
  7. Android(安卓)Unable to resolve target "Android-14"
  8. Android之——判断当前应用程序是否是用户程序
  9. Android地图添加标记和文字【代码片段】

随机推荐

  1. android,NDK, write logs to a file
  2. Android遍历某个文件夹的图片并实现滑动
  3. [android]为程序创建快捷方式
  4. 卡联系人IccProvider
  5. android apk 破解
  6. android 弹出框(输入框和选择框)
  7. Android 结合WindowManager和WindowManag
  8. Android 调用系统相机拍照的返回结果
  9. Android中Matrix的pre post set方法理解
  10. Android关闭开机弹出SIM卡变动提示对话框