Twitter - 从webview中检索PIN码。 Android的

时间:2012-02-22 09:51:34

标签: android twitter webview

是否有可能在授权Twitter时以某种方式从Android中的WebView检索PIN码?

我有教程示例,但要登录用户需要将密码从WebView重写为app。我只想通过这个并直接从网上获取密码。

这与它在iPhone上的表现非常相似。

现在我使用这样的东西:

public void getTwitter() 
{
      handleEvent.post(new Runnable() 
      {

       @Override
       public void run() 
       {               
            if (oHelper.hasAccessToken()) 
            {

                oHelper.configureOAuth(twitterConnection);
                try 
                {
                     twitterConnection.updateStatus("Hii!!!!");
                } 
                catch (TwitterException e) 
                {
                     Log.d("TWEET", "Error Updating status " + e.getMessage());
                     e.printStackTrace();
                }
            } 
            else 
            {
                 try 
                 {
                      twitterConnection.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
                      requestToken = twitterConnection.getOAuthRequestToken("");
                      webViewDialog(requestToken.getAuthorizationURL(), 0);
                 } 
                 catch (TwitterException e) 
                 {
                     e.printStackTrace();
                 }
            }
       }

      });
}

然后在对话框弹出窗口中显示webview:

private void webViewDialog(final String authorizationURL, final int type) 
{
      LinearLayout container = new LinearLayout(this);
      container.setMinimumWidth(200);
      container.setMinimumHeight(320);
      webView = new WebView(this);

      webView.setMinimumWidth(200);
      webView.setMinimumHeight(380);
      webView.getSettings().setJavaScriptEnabled(true);
      webView.setWebViewClient(new WebViewClient());
      webView.loadUrl(authorizationURL);

      container.addView(webView);
      webDialog = new AlertDialog.Builder(this);
      webDialog.setView(container).setPositiveButton("Ok", new DialogInterface.OnClickListener() 
      {

         @Override
         public void onClick(DialogInterface dialog, int which) 
         {
             dia = dialog;
              if (type == 0) 
              {
                   twitterPinCodeDialog();
              }

         }
      }).show();
}

并在最后提示用户输入密码:

public void twitterPinCodeDialog() 
{
      LinearLayout pinHolder = new LinearLayout(this);
      pinHolder.setGravity(Gravity.CENTER);
      final EditText editPinCode = new EditText(this);
      editPinCode.setGravity(Gravity.CENTER);
      editPinCode.setHint("Pin Code");
      editPinCode.setWidth(200);
      pinHolder.addView(editPinCode);

      Builder pinBuilder = new AlertDialog.Builder(this);
      pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry")
        .setMessage("Please enter displayed twitter code into the field")
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() 
        {

         @Override
         public void onClick(DialogInterface dialog, int which) 
         {
              if (editPinCode.getText().toString() != null && !editPinCode.getText().toString().equals("")) 
              {
                   try 
                   {
                        accessToken = twitterConnection.getOAuthAccessToken(requestToken,editPinCode.getText().toString());
                        oHelper.storeAccessToken(accessToken);
                        Log.i("Access Token:", accessToken.getToken());
                        Log.i("Access Secret:", accessToken.getTokenSecret());
                        twitterConnection.updateStatus("Tweeted Successfully");
                   } 
                   catch (TwitterException te) 
                   {
                        if (401 == te.getStatusCode()) 
                        {
                            System.out.println("Unable to get the access token.");
                        } 
                        else 
                        {
                            te.printStackTrace();
                        }
                   }
              } 
              else 
              {
               Toast.makeText(context, "Pin code is required",
                 Toast.LENGTH_SHORT).show();
               dialog.dismiss();    
               dia.dismiss();
               twitterPinCodeDialog();
               }
         }

        }).setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
        {

           @Override
           public void onClick(DialogInterface dialog,int which) 
           {
                Toast.makeText(context,"To share your news please complete login next time",Toast.LENGTH_LONG).show();
                dialog.dismiss();
           }
          }).show();
     }

我甚至不记得从哪里拿过这个例子。 但是摆脱最后一次对话会很好。

2 个答案:

答案 0 :(得分:2)

是的,很有可能 - 我的代码没有在我面前,但过程如下:

  • 当你发出推特授权请求时,你会给它提供一个回调网址,让我们称之为回调://myapp.twitter.pin
  • 在此网址的清单中注册网址处理程序
  • 授权成功后,Twitter网页会将用户重定向到您的回调网址
  • Android将拦截回调网址并恢复您的登录活动
  • 您可以使用onResume访问uri中的PIN码,我在问题here
  • 中进行了演示

答案 1 :(得分:1)

按如下方式调用webview活动进行授权。

final String url = provider.retrieveRequestToken(consumer,
                "callback://x-oauthflow-twitter");
        Log.i(TAG, "Popping a browser with the authorize URL : " + url);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
                .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                        | Intent.FLAG_ACTIVITY_NO_HISTORY
                        | Intent.FLAG_FROM_BACKGROUND);
        context.startActivity(intent);

然后按如下方式检索活动中的访问令牌。

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    final Uri uri = intent.getData();
    if (uri != null
            && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
        Log.i(TAG, "Callback received : " + uri);
        Log.i(TAG, "Retrieving Access Token");
        new RetrieveAccessTokenTask(this, consumer, provider, prefs)
                .execute(uri);
        finish();
    }
}

public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {

    private OAuthProvider provider;
    private OAuthConsumer consumer;
    private SharedPreferences prefs;

    public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
            OAuthProvider provider, SharedPreferences prefs) {
        this.consumer = consumer;
        this.provider = provider;
        this.prefs = prefs;
    }

    /**
     * Retrieve the oauth_verifier, and store the oauth and
     * oauth_token_secret for future API calls.
     */
    @Override
    protected Void doInBackground(Uri... params) {
        final Uri uri = params[0];
        final String oauth_verifier = uri
                .getQueryParameter(OAuth.OAUTH_VERIFIER);

        try {
            provider.retrieveAccessToken(consumer, oauth_verifier);

            final Editor edit = prefs.edit();
            edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
            edit.putString(OAuth.OAUTH_TOKEN_SECRET,
                    consumer.getTokenSecret());
            edit.commit();

            String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
            String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

            consumer.setTokenWithSecret(token, secret);
            // context.startActivity(new Intent(context,
            // MerionActivity.class));

            executeAfterAccessTokenRetrieval();

            Log.i(TAG, "OAuth - Access Token Retrieved");

        } catch (Exception e) {
            Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
        }

        return null;
    }

活动应在清单文件中声明如下。

 <activity
        android:name="com.nppa.twitter.PrepareRequestTokenActivity"
        android:launchMode="singleTask" >
        <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="callback"
                android:scheme="x-oauthflow-twitter" />
        </intent-filter>
    </activity>