Java – AccountManager: invalideauthttoken does not invalidate the token
I tried to get a brand new token from the Google account stored in the Android device, but all the tokens I got were old tokens I had been caching in the past few days It seems that it is cached somewhere on the phone, and even the Internet request is not sent (I tested it in the application without an Internet connection and returned the same token)
Before using getResult in accountmanagerfuture to get the new method, I used the invalideauttoken method Please take a look:
public String updateToken(Activity activity) throws Exception { AccountManager am = AccountManager.get(activity); Account[] accounts = am.getAccountsByType("com.google"); if (accounts == null || accounts.length == 0 || "".equals(accounts[0].name.trim())) { throw new Exception("Não há contas Google configuradas no smartphone."); } else if (!"crsilva@gmail.com".equals(accounts[0].name.trim()) && !"cristiano.bezerra@sulamerica.com.br".equals(accounts[0].name.trim()) && !"tholiver@gmail.com".equals(accounts[0].name.trim())) { Log.w("Util.updateToken","conta obtida: " + accounts[0].name); throw new Exception("Conta Google não autorizada."); } Log.w("Util.updateToken","conta obtida: " + accounts[0].name); am.invalidateAuthToken("com.google",null); Log.w("Util.updateToken","Passou do invalidateAuthToken"); AccountManagerFuture<Bundle> future = am.getAuthToken(accounts[0],"ah",null,activity,"Passou do getAuthToken"); Bundle bundle = future.getResult(); Log.w("Util.updateToken","Passou do getResult"); future = null; am = null; accounts = null; String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN); Log.w("Util.updateToken","Token: " + authToken); return authToken; }
The thread that invokes this method from the util class by a singleton instance The manifest has all required permissions Does anyone know why the token is not refreshed?
Solution
To invalidate the auth token, you need to pass the token to be invalid as the second parameter of invalideauthtoken to invalideauthtoken Please refer to "4.4.3 invalidating authentication token" section of this blog post The video on this page is also very helpful
The document of invalideauthtoken mentions that the second parameter may be null, but this only means that null is allowed to call this method, not that if NULL is passed, each cached tag is invalid
If you do this, your code should work:
// Get token AccountManagerFuture<Bundle> future = am.getAuthToken(accounts[0],null); Bundle bundle = future.getResult(); String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN); // invalidate the token since it may have expired. am.invalidateAuthToken("com.google",authToken); // Get token again future = am.getAuthToken(accounts[0],null); bundle = future.getResult(); authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);