After very hard work, I can now log in to Google using Oauth 2. Now I shared here because many questions remained unanswered. Below are the steps to sign in to Google.
1 - Select an account on your device using
public static AccountManager accountManager; accountManager = AccountManager.get(this); Account[] accounts = accountManager.getAccountsByType("com.google");
2 - Get the token from the selected account using
private void onAccountSelected(final Account account) { accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN); useToken(account, token); } catch (OperationCanceledException e) { onAccessDenied(); } catch (Exception e) { handleException(e); } } }, null);
}
3 - . Now authenticate the token using the user account and token. You can log in to Google.
Note. . After the token becomes unauthorized to enter the system, you need to revoke the token.
4 - to re-enter the system, you must revoke the token using
accountManager.invalidateAuthToken("com.google", token);
5 - after invalidation you should receive a new token using
String newToken = AccountManager.get(this).getAuthToken(new Account(account, "com.google"), AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);
6 - in your AndroidManifest.xml add below uses permissions
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.GET_ACCOUNTS"/> <uses-permission android:name="android.permission.USE_CREDENTIALS"/>
That's all you need now enjoy