0

我想在我的应用程序中集成一个 twitter,这是我的代码:

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.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 = "<my key>";
    static String TWITTER_CONSUMER_SECRET = "<my secure key>";

    // 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 = "https://api.twitter.com/oauth/authenticate";
    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;

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

        /**
         * 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
                String verifier = uri
                        .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

                try {
                    Log.e("Twitter Login ... >", 0+"");

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

                    Log.e("Twitter Login ... >", 1+"");

                    // Shared Preferences
                    Editor e = mSharedPreferences.edit();

                    Log.e("Twitter Login ... >", 2+"");

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

                    Log.e("Twitter Login ... >", 3+"");

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

                    Log.e("Twitter Login ... >", 4+"");

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

    }

    /**
     * Function to login twitter
     * */
    private void loginToTwitter() {
        new myConnection().execute(1);
    }

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

    class myConnection extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected Integer doInBackground(Integer... params) {
            // 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();

                try {
                    requestToken = twitter
                            .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse(requestToken.getAuthenticationURL())));
                } catch (TwitterException e) {
                    e.printStackTrace();
                }
            } else {
                // user already logged into twitter

            }
            return 1;
        }

    }
}

Log打印然后Twitter Login ... > 0发生异常,我捕获并打印此语句

Log.e("Twitter Login Error", "> " + e.getMessage());

e.getMessage()是_null

任何帮助,将不胜感激

4

1 回答 1

0

这都是关于 CallbackURL 的。您需要编写一些代码来处理 WebView。所以从推特重定向后。!检查我在下面给出的代码。!!

我在上面的教程中设置了 Twitter 用户身份验证,以便执行 Twitter 身份验证的 Activity 将其内容视图更改为 WebView,在包含意图过滤器的清单文件中声明 Activity 以捕获 Twitter 回调,并在回调时,响应被处理,Activity 的内容视图变回原来的样子。

我让它工作了,但这样做我发现(我认为是)一种更简单的方法,这样 WebView 就不会启动手机的网络浏览器应用程序(从而离开你的应用程序,你并不真正想要),如下:

(1) 删除您添加到清单文件中的 Activity singleInstance 和 intent-filter 声明(按照上面的教程进行操作)。不再需要那个了!

(2) 将 WebView 添加到您的 Activity 布局文件中,并将其初始可见性设置为“已消失”以及您想要的位置、高度、宽度等。我设置了它的属性,使其在可见时覆盖整个屏幕,如下所示:

<WebView
  android:id="@+id/myWebView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:visibility="gone" />

(3)在你的Activity中获取你的WebView的句柄,并设置它的WebViewClient来接收Twitter回调(而不是在任何时候启动Web浏览器应用程序),如下...

    myWebView = (WebView)findViewById(R.id.myWebView);
    myWebView.setWebViewClient(new WebViewClient()
    {
      @Override
      public boolean shouldOverrideUrlLoading(WebView webView, String url)
      {
        if (url != null
            && url.startsWith("myapptwittercallback:///myapp"))
          handleTwitterCallback(url);
        else
          webView.loadUrl(url);
        return true;
      }

});

...在这里,您可能还希望启用 WebView 的其他设置,例如保存表单数据和 javascript 执行(例如 myWebView.getSettings().setJavaScriptEnabled(true);)

(4) 让你的 WebView 可见并聚焦在你需要做 Twitter 认证的地方,如下:

try
{
  twitter = new TwitterFactory().getInstance();
  twitter.setOAuthConsumer(
      myTwitterConsumerKey,
      myTwitterConsumerSecret);
  twitterRequestToken = twitter.getOAuthRequestToken(
      "myapptwittercallback:///myapp");
  myWebView.loadUrl(
      twitterRequestToken.getAuthenticationURL());
  myWebView.setVisibility(View.VISIBLE);
  myWebView.requestFocus(View.FOCUS_DOWN);
}
catch (TwitterException ex)
{
  Toast.makeText(
      this,
      "Login failed. Please try again.",
      Toast.LENGTH_SHORT).show();
}

...请记住清除您的 WebView 的历史记录(即 myWebView.clearHistory() 并在您的 handleTwitterCallback(String) 方法中将其可见性设置为“已消失”。

(5) 最后,覆盖 Activity 的 onBackPressed() 方法,以便 WebView 处理后退按钮的按下(如果可见),如下所示...

@Override
public void onBackPressed()
{
  if (myWebView.getVisibility() == View.VISIBLE)
  {
    if (myWebView.canGoBack())
    {
      myWebView.goBack();
      return;
    }
    else
    {
      myWebView.setVisibility(View.GONE);
      return;
    }
  }
  super.onBackPressed();
}

而已!您现在应该在您的应用程序中集成 Twitter,并且用户不应该离开您的应用程序进行 Twitter 身份验证。

于 2014-01-14T09:32:06.553 回答