如何在Twitter上从我的Android应用程序发推文

时间:2014-02-15 08:57:30

标签: android twitter

我创建了一个应用程序,因为我想放置一个Twitter按钮,当用户点击Twitter按钮时,我想要Twitter的登录屏幕,然后用户可以在他的Twitter帐户上发推文。

如何才能实现?

我在StackOverflow中看到一些示例,并且在Twitter中创建App也有消费者密钥和消费者密钥,但我不明白。

所以,请给我解决方案。

我的代码:

public class MainActivity extends Activity 
{
    static String TWITTER_CONSUMER_KEY = "2wLf5du5SHcnYr5OIQ"; 
    static String TWITTER_CONSUMER_SECRET = "BsiY4LH5Y4naSmbmNbcxG7gZwG9NSBAkA4EE3Zt8o"; 

    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 = "http://www.soul-spotter.com/";

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

    Button btnLoginTwitter;
    Button btnUpdateStatus;
    Button btnLogoutTwitter;
    EditText txtUpdate;
    TextView lblUpdate;
    TextView lblUserName;
    ProgressDialog pDialog;

    private static Twitter twitter;
    private static RequestToken requestToken;

    private static SharedPreferences mSharedPreferences;

    private ConnectionDetector cd;

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

        if (!cd.isConnectingToInternet()) 
        {           
            alert.showAlertDialog(MainActivity.this, "Internet Connection Error","Please connect to working Internet connection", false);
            return;
        }       

        if(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;
        }

        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);
        btnLoginTwitter.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View arg0) 
            {
                Thread thread = new Thread()
                {
                    @Override
                    public void run() 
                    {
                        try 
                        {
                            loginToTwitter();                       
                        }
                        catch (Exception e)
                        {
                            Log.d("Check","C2"+e.toString());
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();             
            }
        });

        btnUpdateStatus.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {
                String status = txtUpdate.getText().toString();
                if (status.trim().length() > 0) 
                {
                    new updateTwitterStatus().execute(status);
                }
                else 
                {
                    Toast.makeText(getApplicationContext(),"Please enter status message", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnLogoutTwitter.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View arg0) 
            {
                logoutFromTwitter();
            }
        });

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

                    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();
                    User user = twitter.showUser(userID);
                    String username = user.getName();

                    lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
                } 
                catch (Exception e) 
                {
                    Log.e("Twitter Login Error", "> " + e.getMessage());
                }
            }
        }
    }

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

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

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

                AccessToken accessToken = new AccessToken(access_token, access_token_secret);
                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("");
                }
            });
        }
    }
    private void logoutFromTwitter() 
    {
        Editor 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);
    }

    private boolean isTwitterLoggedInAlready() 
    {
        return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
    }

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

3 个答案:

答案 0 :(得分:3)

检查第一个链接。您也可以使用Twitter开发者控制台

Twitter Integration

Twitter Developer Link

Twitter,Facebook,MySpace,LinkedIn Integration

答案 1 :(得分:1)

答案 2 :(得分:0)