Android中Twitter/Facebook SDK登录登出时清除Cookie缓存及授权异常处理
Hey there, let's tackle your Twitter SDK login issues step by step—first fixing that occasional authorization error, then addressing your cookie/cache control needs.
1. Fixing the "Authorize already in progress" Error
That log message tells me you're accidentally triggering the Twitter authorization flow multiple times (e.g., user taps the login button quickly, or your code calls the auth method twice in the lifecycle). Here's a simple fix with a flag to prevent duplicate requests:
// Add a class-level flag to track authorization state private boolean isTwitterAuthorizing = false; private void initiateTwitterLogin() { // Block duplicate requests if (isTwitterAuthorizing) { return; } isTwitterAuthorizing = true; TwitterAuthClient authClient = new TwitterAuthClient(); authClient.authorize(this, new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { isTwitterAuthorizing = false; // Handle successful login here } @Override public void failure(TwitterException exception) { isTwitterAuthorizing = false; Log.e("Twitter", "Authorization failed", exception); // Handle failure (e.g., show error message to user) } }); }
This should eliminate the Authorize already in progress error entirely, since we're blocking any new auth attempts until the current one finishes.
2. Controlling Cookie/Cache to Force Fresh Login
If you want users to enter their credentials every time (instead of relying on browser cache), you have a few options:
Option 1: Guide Users to Clear System Browser Cache
Starting from Android 10, third-party apps can't directly clear another app's cache or cookies. So you'll need to redirect users to the browser's app settings to let them clear data manually:
// For Chrome (most common default browser) Intent clearCacheIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", "com.android.chrome", null); clearCacheIntent.setData(uri); startActivity(clearCacheIntent);
Note: This is a clunky user experience, so it's better to use the options below instead.
Option 2: Use a Custom WebView for Twitter Authorization
By replacing the default browser with a WebView in your app, you get full control over cache and cookies. Here's how to implement it:
// 1. Create a WebView and configure it to disable cache WebView twitterAuthWebView = new WebView(this); WebSettings webSettings = twitterAuthWebView.getSettings(); webSettings.setJavaScriptEnabled(true); // Disable all caching webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // Clear existing cookies for the WebView CookieManager.getInstance().removeAllCookies(null); CookieManager.getInstance().flush(); // 2. Handle the OAuth flow manually (you'll need to fetch a request token first) // Replace with your actual Twitter API keys and callback URL TwitterAuthConfig authConfig = new TwitterAuthConfig(YOUR_TWITTER_API_KEY, YOUR_TWITTER_API_SECRET); String requestToken = fetchTwitterRequestToken(); // Implement this to get a request token via OAuth 1.0a String authUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + requestToken; // 3. Load the authorization URL and listen for the callback twitterAuthWebView.loadUrl(authUrl); twitterAuthWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { String url = request.getUrl().toString(); // Check if we're redirected to your callback URL if (url.startsWith(YOUR_TWITTER_CALLBACK_URL)) { // Extract the oauth_verifier from the URL String verifier = Uri.parse(url).getQueryParameter("oauth_verifier"); // Use the verifier and request token to fetch the access token exchangeVerifierForAccessToken(requestToken, verifier); return true; } return super.shouldOverrideUrlLoading(view, request); } }); // 4. Add the WebView to your layout to display the login page setContentView(twitterAuthWebView);
This approach ensures every login attempt uses a clean state—no cached credentials, so users have to enter their username and password each time.
Option 3: Customize Chrome Custom Tabs (Advanced)
If you prefer using the official SDK's Chrome Custom Tabs, you can try disabling cache via intent extras, but this is more complex (and relies on undocumented behavior). The WebView method is more reliable for this use case.
Final Recommendations
- Start with fixing the duplicate authorization requests first—that's the root cause of your occasional
TwitterAuthException. - For forcing fresh logins, use the custom WebView approach for full control over the login state. Avoid asking users to clear browser cache unless it's a last resort.
内容的提问来源于stack exchange,提问作者Manikandan1987

