Use twitter4j oauth to post status in Android app

我们这里使用twitter4j来实现这个功能. http://twitter4j.org/

  • 新建一个android项目
  • 下载twitter4j-core-2.1.8.jar, 放到${base.dir}/libs, 并加到项目的classpath中
  • MyActivity

  • package com.example;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    import twitter4j.Twitter;
    import twitter4j.TwitterException;
    import twitter4j.TwitterFactory;
    import twitter4j.conf.ConfigurationBuilder;
    import twitter4j.http.AccessToken;
    import twitter4j.http.RequestToken;
    
    import java.util.Date;
    
    public class MyActivity extends Activity {
    
    
    
        private final String CALLBACKURL = "myapp://mainactivity";
        private static Twitter twitter;
    
        private TextView tweetTextView;
        private Button buttonLogin;
    
    
        public static final String consumerKey = "XXXXXXXXX";
        public static final String consumerSecret = "XXXXXXXXXXXXXXXX";
    
        private void doOauth() {
    
    
            try {
    
                twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(consumerKey, consumerSecret);
                RequestToken requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
                System.out.println("Got request token.");
                System.out.println("Request token: "+ requestToken.getToken());
                System.out.println("Request token secret: "+ requestToken.getTokenSecret());
                this.startActivity(new Intent(Intent.ACTION_VIEW,
                Uri.parse(requestToken.getAuthenticationURL())));
            } catch (TwitterException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            Uri uri = intent.getData();
            if (uri != null && uri.toString().startsWith(CALLBACKURL)) {
                String verifier =
                        uri.getQueryParameter("oauth_verifier");
                try {
                    AccessToken oAuthAccessToken = twitter.getOAuthAccessToken(verifier);
                    // TODO: store the oauthaccess token
    // create a tweet
                    Date d =
                            new Date(System.currentTimeMillis());
                    String tweet = "#OAuth working! " + d.toLocaleString();
    // send the tweet
                    twitter.updateStatus(tweet);
    // feedback for the user...
                    Toast.makeText(this, tweet, Toast.LENGTH_LONG).show();
                    buttonLogin.setVisibility(Button.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            tweetTextView = (TextView) findViewById(R.id.tweet);
            buttonLogin = (Button) findViewById(R.id.ButtonLogin);
            setContentView(R.layout.main);
            doOauth();
    
        }
    }
  • consumerKey, consumerSecret需要换成你们自己的, 在twitter中创建app后可以得到. 这里要注意的是CALLBACKURL变量, 这里是用户verfiy之后browser回调的url. 这个我们需要在AndroidManifest.xml定义. 这样就能使browser带回到MyActivity中.
  • AndroidManifest.xml

  • <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="com.example"
              android:versionCode="1"
              android:versionName="1.0">
        <application android:label="twittertest" android:icon="@drawable/icon" android:debuggable="true">
            <activity android:name="MyActivity"
                      android:label="@string/app_name" android:launchMode="singleInstance" >
                <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:scheme="myapp" android:host="mainactivity"/>
                </intent-filter>
            </activity>
        </application>
        <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    </manifest> 
  • 在国内twitter被墙, 所以需要代理. 用这个命令可以起一个链接到代理的模拟器

  • 引用
    ./emulator -avd adv8 -http-proxy 192.168.1.13:8118 -debug-proxy


    附件是源码.

    参考:

    http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e4fc18c1398895c4/9d4a29f66f930a3e?lnk=gst&q=OAuth

    http://abhinavasblog.blogspot.com/2010/09/using-twitter-with-oauth-on-andorid.html

    你可能感兴趣的:(android,xml,OS,Google,twitter)