在"取消"点击Twitter,页面请求令牌无效(Twitter4j)

时间:2014-07-31 16:34:22

标签: java android twitter

我正在使用Twitter4j让我的用户登录他们的Twitter帐户。他们能够成功登录和退出,但是如果他们在Twitter弹出对话框中点击“取消”并返回应用程序然后重新打开登录就会出现问题,登录会发出错误,说明页面的请求令牌是无效。我知道我有正确的消费者/密钥,因为如果我没有点击取消并正常登录,登录就有效。有什么想法吗?

image

MainActivity

public class MainActivity extends Activity {

SharedPreferences pref;

private static String CONSUMER_KEY = "mykey";
private static String CONSUMER_SECRET = "mykey";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pref = getPreferences(0);
    SharedPreferences.Editor edit = pref.edit();
    edit.putString("CONSUMER_KEY", CONSUMER_KEY);
    edit.putString("CONSUMER_SECRET", CONSUMER_SECRET);
    edit.commit();

    Fragment login = new LoginFragment();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, login);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(null);
    ft.commit();
}

}

LoginFragment

public class LoginFragment extends Fragment {
ImageView login;
Twitter twitter;
RequestToken requestToken = null;
AccessToken accessToken;
String oauth_url, oauth_verifier, profile_url;
Dialog auth_dialog;
WebView web;
SharedPreferences pref;
ProgressDialog progress;
Bitmap bitmap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.login_fragment, container, false);
    login = (ImageView) view.findViewById(R.id.login);
    pref = getActivity().getPreferences(0);
    twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""),
            pref.getString("CONSUMER_SECRET", ""));

    login.setOnClickListener(new LoginProcess());
    return view;
}

private class LoginProcess implements OnClickListener {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        new TokenGet().execute();

    }
}

private class TokenGet extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... args) {

        try {
            requestToken = twitter.getOAuthRequestToken();
            oauth_url = requestToken.getAuthorizationURL()
                    + "&force_login=true";
            Log.d("URL", oauth_url);
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return oauth_url;
    }

    @Override
    protected void onPostExecute(String oauth_url) {
        if (oauth_url != null) {
            Log.e("URL", oauth_url);
            auth_dialog = new Dialog(getActivity());
            auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            auth_dialog.setContentView(R.layout.auth_dialog);
            web = (WebView) auth_dialog.findViewById(R.id.webv);
            web.getSettings().setJavaScriptEnabled(true);
            web.loadUrl(oauth_url);
            web.setWebViewClient(new WebViewClient() {
                boolean authComplete = false;

                @Override
                public void onPageStarted(WebView view, String url,
                        Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    if (url.contains("oauth_verifier")
                            && authComplete == false) {
                        authComplete = true;
                        Log.e("Url", url);
                        Uri uri = Uri.parse(url);
                        oauth_verifier = uri
                                .getQueryParameter("oauth_verifier");

                        auth_dialog.dismiss();
                        new AccessTokenGet().execute();
                    } else if (url.contains("denied")) {
                        auth_dialog.dismiss();
                        Toast.makeText(getActivity(),
                                "Sorry !, Permission Denied",
                                Toast.LENGTH_SHORT).show();

                    }
                }
            });
            auth_dialog.show();
            auth_dialog.setCancelable(true);

        } else {

            Toast.makeText(getActivity(),
                    "Sorry !, Network Error or Invalid Credentials",
                    Toast.LENGTH_SHORT).show();

        }
    }
}

private class AccessTokenGet extends AsyncTask<String, String, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progress = new ProgressDialog(getActivity());
        progress.setMessage("Fetching Data ...");
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);
        progress.show();

    }

    @Override
    protected Boolean doInBackground(String... args) {

        try {

            accessToken = twitter.getOAuthAccessToken(requestToken,
                    oauth_verifier);
            SharedPreferences.Editor edit = pref.edit();
            edit.putString("ACCESS_TOKEN", accessToken.getToken());
            edit.putString("ACCESS_TOKEN_SECRET",
                    accessToken.getTokenSecret());
            User user = twitter.showUser(accessToken.getUserId());
            profile_url = user.getOriginalProfileImageURL();
            edit.putString("NAME", user.getName());
            edit.putString("IMAGE_URL", user.getOriginalProfileImageURL());

            edit.commit();

        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        return true;
    }

    @Override
    protected void onPostExecute(Boolean response) {
        if (response) {
            progress.hide();
            Fragment profile = new ProfileFragment();
            FragmentTransaction ft = getActivity().getFragmentManager()
                    .beginTransaction();
            ft.replace(R.id.content_frame, profile);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.addToBackStack(null);
            ft.commit();

        }
    }

}
}

1 个答案:

答案 0 :(得分:0)

尝试为对话框添加onCancelListener,并在其中将OAuthAccessToken设置为null。

mAuth_dialog.setOnCancelListener(new OnCancelListener() {       
    @Override
    public void onCancel(DialogInterface dialog) {
        sTwitter.setOAuthAccessToken(null);
    }
});