简体   繁体   中英

How to use default google account to register GCM without account picker option or any user interaction android

Android device needs a google account when registering GCM for the first time. Currently, I am using account picker intent to select google account from users when registering GCM. If users have multiple accounts then it will ask users to select the account for successfully complete the GCM registration.

So, Is there any option to automatically choose the default account without showing any account picker intent or any select options from user side manually?

After spending some time, I have found a solution to do this in an efficient way just use below code to get default google account ID:

 private String getPrimaryEmailID(Context context) {
        AccountManager accountManager = AccountManager.get(context); 
        Account account = getAccount(accountManager);

        if (account == null) {
            return null;
        } else {
            return account.name;
        }
    }

       private Account getAccount(AccountManager accountManager) {
            Account[] accounts = accountManager.getAccountsByType("com.google");
            Account account;
            if (accounts.length > 0) {
                account = accounts[0];
            } else {
                account = null;
            }
            return account;
        }

It will give the user default google account ID without any Account Picker intent popup or any other user interaction/selection.

Also, you need to add this in your manifest file:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM