本文介绍了使用 oauth 和 twitter4j 的 Android Twitter 集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 twitter 集成到一个 android 应用程序中,并找到了很多教程.实施了其中的2个.但是在实施之后,当运行应用程序时,我开始知道他们使用旧版本的 twitter4J 库.>

虽然有很多其他教程可用,但没有一个是最新的.仅大 2-3 个月.我需要一个使用最新 twitter4J 库版本的教程或示例,它是 twitter4j-core-3.0.3.

我的主要目标是允许用户在他/她的帐户上发布推文.但同样,如果用户当时没有登录,我首先需要要求提供凭据.此外,如果用户点击 logout 按钮,那么我需要某种方式来注销用户.

解决方案

我解决了这个问题.我对在教程中找到的代码进行了更改以使其工作.在这里复制整个代码.只需替换为您的 ConsumerKeyConsumerSecret.

您需要将 twitter4j 库添加到您项目的 libs 文件夹中.

AndroidManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"包=com.androidhive.twitterconnect"机器人:版本代码=1"android:versionName="1.0" ><使用-sdkandroid:minSdkVersion="14"android:targetSdkVersion="17"/><!-- 权限- Internet 连接--><uses-permission android:name="android.permission.INTERNET"/><!-- 网络状态权限--><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><申请机器人:allowBackup =真"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><活动android:name=".MainActivity"android:label="@string/title_activity_main" ><意图过滤器><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></意图过滤器><意图过滤器><action android:name="android.intent.action.VIEW"/><category android:name="android.intent.category.DEFAULT"/><category android:name="android.intent.category.BROWSABLE"/><数据机器人:主机=t4jsample"机器人:方案=oauth"/></意图过滤器></活动></应用程序></清单>

MainActivity.java :

package com.androidhive.twitterconnect;导入 twitter4j.Twitter;导入 twitter4j.TwitterException;导入 twitter4j.TwitterFactory;导入 twitter4j.User;导入 twitter4j.auth.AccessToken;导入 twitter4j.auth.RequestToken;导入 twitter4j.conf.Configuration;导入 twitter4j.conf.ConfigurationBuilder;导入 com.androidhive.twitterconnect.R;导入 android.app.Activity;导入 android.app.ProgressDialog;导入 android.content.Intent;导入 android.content.SharedPreferences;导入 android.content.SharedPreferences.Editor;导入 android.content.pm.ActivityInfo;导入android.net.Uri;导入 android.os.AsyncTask;导入 android.os.Bundle;导入 android.text.Html;导入 android.util.Log;导入 android.view.View;导入 android.widget.Button;导入 android.widget.EditText;导入 android.widget.TextView;导入 android.widget.Toast;公共类 MainActivity 扩展 Activity {//常量/*** 在此处注册您的应用程序 https://dev.twitter.com/apps/new 并获取您的* 消费者密钥和秘密* */static String TWITTER_CONSUMER_KEY = "PutYourConsumerKeyHere";//将您的用户密钥放在这里static String TWITTER_CONSUMER_SECRET = "PutYourConsumerSecretHere";//把你的消费者秘密放在这里//偏好常量静态字符串 PREFERENCE_NAME = "twitter_oauth";静态最终字符串 PREF_KEY_OAUTH_TOKEN = "oauth_token";static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";静态最终字符串 TWITTER_CALLBACK_URL = "oauth://t4jsample";//Twitter oauth url静态最终字符串 URL_TWITTER_AUTH = "auth_url";静态最终字符串 URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";静态最终字符串 URL_TWITTER_OAUTH_TOKEN = "oauth_token";//登录按钮按钮 btnLoginTwitter;//更新状态按钮按钮 btnUpdateStatus;//退出按钮按钮 btnLogoutTwitter;//用于更新的 EditTextEditText txtUpdate;//lbl 更新TextView lblUpdate;TextView lblUserName;//进度对话框ProgressDialog pDialog;//推特私人静态 Twitter 推特;私有静态 RequestToken requestToken;私有访问令牌访问令牌;//共享首选项私有静态 SharedPreferences mSharedPreferences;//Internet 连接检测器私人 ConnectionDetector 光盘;//警报对话框管理器AlertDialogManager alert = new AlertDialogManager();@覆盖public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);cd = new ConnectionDetector(getApplicationContext());//检查 Internet 是否存在如果 (!cd.isConnectingToInternet()) {//Internet 连接不存在alert.showAlertDialog(MainActivity.this, "Internet 连接错误","请连接到工作的 Internet 连接", false);//通过返回停止执行代码返回;}//检查推特键是否设置if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){//Internet 连接不存在alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "请先设置你的 twitter oauth 令牌!", false);//通过返回停止执行代码返回;}//所有界面元素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);//共享首选项mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);/*** Twitter 登录按钮点击事件会调用 loginToTwitter() 函数* */btnLoginTwitter.setOnClickListener(new View.OnClickListener() {@覆盖公共无效 onClick(查看 arg0){//调用登录twitter函数登录推特();}});/*** 按钮点击事件更新状态,会调用updateTwitterStatus()* 功能* */btnUpdateStatus.setOnClickListener(new View.OnClickListener() {@覆盖public void onClick(View v) {//调用更新状态函数//从 EditText 获取状态字符串状态 = txtUpdate.getText().toString();//检查空白文本如果 (status.trim().length() > 0) {//更新状态新的 updateTwitterStatus().execute(status);} 别的 {//编辑文本为空Toast.makeText(getApplicationContext(),请输入状态信息",Toast.LENGTH_SHORT).展示();}}});/*** 用于从 twitter 注销的按钮单击事件* */btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {@覆盖公共无效 onClick(查看 arg0){//调用注销推特函数logoutFromTwitter();}});/** 如果条件被测试一次是* 从推特页面重定向.解析 uri 以获取 oAuth* 验证器* */如果 (!isTwitterLoggedInAlready()) {uri uri = getIntent().getData();if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {//oAuth 验证器最终字符串验证器 = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);尝试 {线程线程=新线程(新的Runnable(){@覆盖公共无效运行(){尝试 {//获取访问令牌MainActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken,验证者);} 捕获(异常 e){e.printStackTrace();}}});线程开始();//共享首选项编辑器 e = mSharedPreferences.edit();//获得访问令牌后,访问令牌秘密//将它们存储在应用程序首选项中e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());//存储登录状态 - truee.putBoolean(PREF_KEY_TWITTER_LOGIN, true);e.commit();//保存更改Log.e("Twitter OAuth Token", ">" + accessToken.getToken());//隐藏登录按钮btnLoginTwitter.setVisibility(View.GONE);//显示更新推特lblUpdate.setVisibility(View.VISIBLE);txtUpdate.setVisibility(View.VISIBLE);btnUpdateStatus.setVisibility(View.VISIBLE);btnLogoutTwitter.setVisibility(View.VISIBLE);//从推特获取用户详细信息//现在我只知道他的名字long userID = accessToken.getUserId();用户用户 = twitter.showUser(userID);字符串用户名 = user.getName();//在 xml ui 中显示lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));} 捕获(异常 e){//检查登录错误日志Log.e("Twitter 登录错误", "> " + e.getMessage());e.printStackTrace();}}}}/*** 登录推特的功能* */私人无效 loginToTwitter() {//检查是否已经登录如果 (!isTwitterLoggedInAlready()) {ConfigurationBuilder builder = new ConfigurationBuilder();builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);配置配置= builder.build();TwitterFactory factory = new TwitterFactory(configuration);推特 = factory.getInstance();线程线程=新线程(新的Runnable(){@覆盖公共无效运行(){尝试 {请求令牌 = 推特.getOAuthRequestToken(TWITTER_CALLBACK_URL);MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));} 捕获(异常 e){e.printStackTrace();}}});线程开始();} 别的 {//用户已经登录推特Toast.makeText(getApplicationContext(),已经登录推特", Toast.LENGTH_LONG).show();}}/*** 功能更新状态* */类 updateTwitterStatus 扩展了 AsyncTask{/*** 在启动后台线程之前显示进度对话框* */@覆盖受保护的无效 onPreExecute() {super.onPreExecute();pDialog = new ProgressDialog(MainActivity.this);pDialog.setMessage("正在更新推特...");pDialog.setIndeterminate(false);pDialog.setCancelable(false);pDialog.show();}/*** 获取地点 JSON* */受保护的字符串 doInBackground(String... args) {Log.d("Tweet Text", "> " + args[0]);字符串状态 = args[0];尝试 {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, "");AccessToken accessToken = new AccessToken(access_token, access_token_secret);Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);//更新状态twitter4j.Status 响应 = twitter.updateStatus(status);Log.d("状态", "> " + response.getText());} catch (TwitterException e) {//更新状态出错Log.d("Twitter 更新错误", e.getMessage());e.printStackTrace();}返回空;}/*** 完成后台任务后关闭进度对话框并显示* UI 中的数据总是使用 runOnUiThread(new Runnable()) 来更新 UI* 来自后台线程,否则会报错* **/protected void onPostExecute(String file_url) {//获取所有产品后关闭对话框pDialog.dismiss();//从后台线程更新 UIrunOnUiThread(new Runnable() {@覆盖公共无效运行(){Toast.makeText(getApplicationContext(),状态推文成功",Toast.LENGTH_SHORT).展示();//清除 EditText 字段txtUpdate.setText("");}});}}/*** 退出推特功能* 它只会清除应用程序共享首选项* */私人无效 logoutFromTwitter() {//清除共享首选项编辑器 e = mSharedPreferences.edit();e.remove(PREF_KEY_OAUTH_TOKEN);e.remove(PREF_KEY_OAUTH_SECRET);e.remove(PREF_KEY_TWITTER_LOGIN);e.commit();//在此之后采取适当的行动//我再次显示隐藏/显示按钮//您可能不需要此代码btnLogoutTwitter.setVisibility(View.GONE);btnUpdateStatus.setVisibility(View.GONE);txtUpdate.setVisibility(View.GONE);lblUpdate.setVisibility(View.GONE);lblUserName.setText("");lblUserName.setVisibility(View.GONE);btnLoginTwitter.setVisibility(View.VISIBLE);}/*** 检查用户已经使用 twitter 登录标志登录您的应用程序是* 从共享首选项中获取* */私有布尔值 isTwitterLoggedInAlready() {//从共享首选项返回推特登录状态返回 mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);}受保护的无效 onResume() {super.onResume();}}

AlertDialogManager.java :

package com.androidhive.twitterconnect;导入 android.app.AlertDialog;导入 android.content.Context;导入 android.content.DialogInterface;公共类 AlertDialogManager {/*** 显示简单警报对话框的功能* @param context - 应用程序上下文* @param title - 警告对话框标题* @param message - 警报消息* @param status - 成功/失败(用于设置图标)* - 如果您不想要图标,则传递 null* */public void showAlertDialog(Context context, String title, String message,布尔状态) {AlertDialog alertDialog = new AlertDialog.Builder(context).create();//设置对话框标题alertDialog.setTitle(title);//设置对话框消息alertDialog.setMessage(message);如果(状态!= null)//设置警告对话框图标alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);//设置确定按钮alertDialog.setButton("OK", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});//显示警报信息alertDialog.show();}}

ConnectionDetector.java :

package com.androidhive.twitterconnect;导入 android.content.Context;导入 android.net.ConnectivityManager;导入 android.net.NetworkInfo;公共类连接检测器{私有上下文_context;公共连接检测器(上下文上下文){this._context = 上下文;}/*** 检查所有可能的互联网提供商* **/公共布尔 isConnectingToInternet(){ConnectivityManager 连接 = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);如果(连接!= null){NetworkInfo[] info = connected.getAllNetworkInfo();如果(信息!= null)for (int i = 0; i < info.length; i++)if (info[i].getState() == NetworkInfo.State.CONNECTED){返回真;}}返回假;}}

这是 Ravi Tamada 的原始代码.我所做的更改仅在 MainActivity.javaAndroidManifest.xml 文件中.

I want to integrate twitter in an android application and found many tutorials. Implemented 2 of them. But after implementing, when ran the application, I came to know that they use older version of twitter4J library.

Although plenty other tutorials are available but none of them is latest one.i.e. just 2-3 months older. I need a tutorial or example which uses latest twitter4J library version which is twitter4j-core-3.0.3.

My main aim is to allow user to post tweets on his/her account. But again, if user is not logged in then, I first need to ask for credentials. Also, if user clicks on logout button then I need some way to log the user out.

解决方案

I solved the problem. I made changes to the code I found in a tutorial to make it work. Copying the whole code here. Just replace with your ConsumerKey and ConsumerSecret.

You need to add twitter4j library to your project's libs folder.

AndroidManifest.xml :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.twitterconnect"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <!-- Permission - Internet Connect -->
    <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=".MainActivity"
            android:label="@string/title_activity_main" >
            <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>

MainActivity.java :

package com.androidhive.twitterconnect;

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 com.androidhive.twitterconnect.R;
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.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    // Constants
    /**
     * Register your here app https://dev.twitter.com/apps/new and get your
     * consumer key and secret
     * */
    static String TWITTER_CONSUMER_KEY = "PutYourConsumerKeyHere"; // place your cosumer key here
    static String TWITTER_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here

    // 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;
    private AccessToken accessToken;

    // Shared Preferences
    private static SharedPreferences mSharedPreferences;

    // Internet Connection detector
    private ConnectionDetector cd;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        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);

        /**
         * Twitter login button click event will call loginToTwitter() function
         * */
        btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Call login twitter function
                loginToTwitter();
            }
        });

        /**
         * Button click event to Update Status, will call updateTwitterStatus()
         * function
         * */
        btnUpdateStatus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Call update status function
                // Get the status from EditText
                String status = txtUpdate.getText().toString();

                // Check for blank text
                if (status.trim().length() > 0) {
                    // update status
                    new updateTwitterStatus().execute(status);
                } else {
                    // EditText is empty
                    Toast.makeText(getApplicationContext(),
                            "Please enter status message", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        /**
         * Button click event for logout from twitter
         * */
        btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Call logout twitter function
                logoutFromTwitter();
            }
        });

        /** This if conditions is tested once is
         * redirected from twitter page. Parse the uri to get oAuth
         * Verifier
         * */
        if (!isTwitterLoggedInAlready()) {
            Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                // oAuth verifier
                final String verifier = uri
                        .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

                try {

                    Thread thread = new Thread(new Runnable(){
                        @Override
                        public void run() {
                            try {

                                // Get the access token
                                MainActivity.this.accessToken = twitter.getOAuthAccessToken(
                                        requestToken, verifier);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                    // 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());
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * Function 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();


                Thread thread = new Thread(new Runnable(){
                    @Override
                    public void run() {
                        try {

                            requestToken = twitter
                                    .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                            MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                    .parse(requestToken.getAuthenticationURL())));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();
        } else {
            // user already logged into twitter
            Toast.makeText(getApplicationContext(),
                    "Already Logged into twitter", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Function to update status
     * */
    class updateTwitterStatus extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        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());
                e.printStackTrace();
            }
            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() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Status tweeted successfully", Toast.LENGTH_SHORT)
                            .show();
                    // Clearing EditText field
                    txtUpdate.setText("");
                }
            });
        }

    }

    /**
     * Function to logout from twitter
     * It will just clear the application shared preferences
     * */
    private 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();

        // After this take the appropriate action
        // I am showing the hiding/showing buttons again
        // You might not needed this code
        btnLogoutTwitter.setVisibility(View.GONE);
        btnUpdateStatus.setVisibility(View.GONE);
        txtUpdate.setVisibility(View.GONE);
        lblUpdate.setVisibility(View.GONE);
        lblUserName.setText("");
        lblUserName.setVisibility(View.GONE);

        btnLoginTwitter.setVisibility(View.VISIBLE);
    }

    /**
     * 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);
    }

    protected void onResume() {
        super.onResume();
    }

}

AlertDialogManager.java :

package com.androidhive.twitterconnect;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
    public void showAlertDialog(Context context, String title, String message,
        Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
            alertDialog.setMessage(message);

        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}

ConnectionDetector.java :

package com.androidhive.twitterconnect;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    /**
     * Checking for all possible internet providers
     * **/
    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)
                      {
                          return true;
                      }

          }
          return false;
    }
}

This is original code by Ravi Tamada. The changes I made are in MainActivity.java and AndroidManifest.xml files only.

这篇关于使用 oauth 和 twitter4j 的 Android Twitter 集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-22 15:55