1

首先,我已下载twitter4j-3.0.3并将其.jar文件放入libs我的 eclipse 应用程序的文件夹中。之后,我创建了一个应用程序https://dev.twitter.com/并获取所需的所有凭据,并将回调 url 指定为https://google.co.in

现在我的代码如下

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.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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 TwitterSampleActivity extends Activity  {

    private static final String CONSUMER_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxx";
    private static final String CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxx";
    private static final String CALLBACK = "https://google.co.in";
    private  String OAuthToken;
    private  String OAuthSecret;
    private boolean isLogged;
    private static Twitter twitter;
    private static RequestToken requestToken;

    private Button loginButton;
    private Button logoutButton;
    private Button sendStatus;
    private EditText status;
    private TextView userName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_twitter);

        loginButton = (Button) findViewById(R.id.twitter_log_in);
        logoutButton = (Button) findViewById(R.id.twitter_log_out);
        sendStatus = (Button) findViewById(R.id.twitter_send);
        status = (EditText) findViewById(R.id.twitter_text);
        userName = (TextView) findViewById(R.id.twitter_username);

        loginButton.setVisibility(View.VISIBLE);
        userName.setVisibility(View.GONE);
        sendStatus.setVisibility(View.GONE);
        status.setVisibility(View.GONE);
        logoutButton.setVisibility(View.GONE);

        Uri uri = getIntent().getData();
        if(uri!=null && uri.toString().startsWith(CALLBACK)) {
            String verifier = uri.getQueryParameter("oauth_verifier");

            try {
                AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);

                OAuthToken = token.getToken();
                OAuthSecret = token.getTokenSecret();
                isLogged = true;

                loginButton.setVisibility(View.GONE);
                userName.setVisibility(View.VISIBLE);
                sendStatus.setVisibility(View.VISIBLE);
                status.setVisibility(View.VISIBLE);
                logoutButton.setVisibility(View.VISIBLE);

                User user = twitter.showUser(token.getUserId());
                String username = user.getName();

                userName.setText("Logged as: " + username);
            } catch (Exception e) {
                Log.e("Login error: ", e.getMessage());
            }
        }
    }

    public void onLogInClicked(View v) {
        if(!isLogged) {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(CONSUMER_KEY);
            builder.setOAuthConsumerSecret(CONSUMER_SECRET);
            Configuration config = builder.build();
            TwitterFactory factory = new TwitterFactory(config); 
            twitter = factory.getInstance();

            try {
                requestToken = twitter.getOAuthRequestToken(CALLBACK);
                this.startActivity(new Intent(Intent.ACTION_VIEW, 
                        Uri.parse(requestToken.getAuthenticationURL())));
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "Already logged", Toast.LENGTH_LONG).show();
        }
    }

    public void onLogOutclicked(View v) {
        OAuthToken = "";
        OAuthSecret = "";
        isLogged = false;

        loginButton.setVisibility(View.VISIBLE);
        userName.setVisibility(View.GONE);
        userName.setText("");
        sendStatus.setVisibility(View.GONE);
        status.setVisibility(View.GONE);
        logoutButton.setVisibility(View.GONE);
    }   


    public void onSendClicked(View v) {
        String text = status.getText().toString();
        if(text.length()>0) {
           new SendTwitterStatusUpdate(this, CONSUMER_KEY, CONSUMER_SECRET,
               OAuthToken, OAuthSecret).execute(text);
        } else {
            Toast.makeText(this, "Enter some text" , Toast.LENGTH_SHORT).show();
        }
    }

}

我的activity_twitter.xml文件是

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/twitter_log_in"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="twitter log in"
        android:onClick="onLogInClicked" />

    <TextView
        android:id="@+id/twitter_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText 
        android:id="@+id/twitter_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <Button
        android:id="@+id/twitter_send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="twitter send"
        android:onClick="onSendClicked" />

    <Button
        android:id="@+id/twitter_log_out"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="twitter log_out"
        android:onClick="onLogOutClicked" />

</LinearLayout>

文件SendTwitterStatusUpdate.java

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

public class SendTwitterStatusUpdate extends AsyncTask<String, Void, Boolean>{

    private Context context;
    private String consumerKey;
    private String consumerSecret;
    private String accessToken;
    private String accessTokenSecret;

    public SendTwitterStatusUpdate(Context context, String consumerKey, String consumerSecret, String accessToken,String accessTokenSecret) {
        this.context=context;
        this.consumerKey=consumerKey;
        this.consumerSecret=consumerSecret;
        this.accessToken=accessToken;
        this.accessTokenSecret=accessTokenSecret;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        String status = params[0];

        if(status!=null) {
            try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(consumerKey);
                builder.setOAuthConsumerSecret(consumerSecret);

                AccessToken token = new AccessToken(accessToken, accessTokenSecret);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(token);

                twitter.updateStatus(status);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public void onPostExecute(Boolean result) {
        if(result) {
            Toast.makeText(context, "Status successfully updated", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Status not updated", Toast.LENGTH_LONG).show();
        }
    }

现在当我运行我的应用程序时,我得到了这个窗口 查看没有显示完整 <code>twitter_activity.xml</code> 的模拟器

除此之外,当我单击该按钮时twitter log in...该按钮不起作用..需要帮助

}

谁能告诉我为什么我在Uri uri = getIntent().getData();...uri对象值为null..因此这部分没有执行

if(uri!=null && uri.toString().startsWith(CALLBACK)) {
            String verifier = uri.getQueryParameter("oauth_verifier");

            try {
                AccessToken token = twitter.getOAuthAccessToken(requestToken, verifier);

                OAuthToken = token.getToken();
                OAuthSecret = token.getTokenSecret();
                isLogged = true;

                loginButton.setVisibility(View.GONE);
                userName.setVisibility(View.VISIBLE);
                sendStatus.setVisibility(View.VISIBLE);
                status.setVisibility(View.VISIBLE);
                logoutButton.setVisibility(View.VISIBLE);

                User user = twitter.showUser(token.getUserId());
                String username = user.getName();

                userName.setText("Logged as: " + username);
            } catch (Exception e) {
                Log.e("Login error: ", e.getMessage());
            }
        }
4

1 回答 1

0

查看此演示链接,您将了解它是如何工作的,然后尝试实现自己的

你可以下载你只需要创建你的 Twitter 应用程序。这也是博主解释的。按照他们你会得到两个密钥。

TWITTER_CONSUMER_KEY="**********************";

TWITTER_CONSUMER_SECRET="********************";

替换您的活动并运行您的项目。

第一个例子

第二个例子

享受。!!!

于 2013-05-22T10:52:13.073 回答