mardi 1 décembre 2015

Android Studio, Obtenir un token Xoauth2 Gmail par programmation

AccountManager accountManager = AccountManager.get(this.getApplicationContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
    for (int i = 0; i < accounts.length; i++) {
        account = accounts[i];
        Log.d(TAG, (account.name));
        AccountManagerFuture<Bundle> amf = accountManager.getAuthToken(account, "oauth2:" + "https://mail.google.com", null, this, null, null);
        try {
            Bundle bundle = amf.getResult();
            String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
            Log.d(TAG, "token=" + token);
            if (account.name.equals("remplaccezparvotreemail@gmail.com"))
            {
                tokenToUse = token;
            }
        }catch(Exception ex){
            Log.d(TAG,"ExceptionGMT:" + ex.toString());
        }
    }
} else {
    account = null;
}

Log.d(TAG, "Will use token " + tokenToUse);