Android M - GoogleAccountCredential setSelectedAcc

2020-07-14 06:09发布

问题:

On the Android M-Preview GoogleAccountCredential.setSelectedAccount doesn't seem to work.

When debugging, I noticed that after calling that method, the selectedAccount and accountName fields of the object are still null.

While debugging you can see that my variable accountName is not empty or null, I call the .setSelectedAccountName(), but as you can see in the debug window, the field in the GoogleAccountCredential is still null.

I think this can be related to some permissions? On my Manifest, I have the following permissions declared:

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

I know that the GET_ACCOUNTS permission you get for free on M (According to https://developer.android.com/preview/features/runtime-permissions.html#normal ), but the other two permissions are "unknown" to the M-Preview. So maybe, it's that?

回答1:

android.permission.GET_ACCOUNTS has protectionLevel:dangerous and is now part of the Contacts permission group, which means you should request it at runtime using the new Activity.requestPermissions()

Only then can you interact with accounts created by other apps on your device.



回答2:

I had the same issue.

Use setSelectedAccount() instead of setSelectedAccountName()

 mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());

        // to set accountName manually instead of prompting user to select it
        mCredential.setSelectedAccount(new Account("xyz@gmail.com", "com.android.example"));

set the account that you want to set as the email and you can give your package name as the second parameter.