Asking user to add google account to android device if none exists.
I'm writing an application in which we are asking the u开发者_开发问答sers to associate a google account with so that we can auto sync server side data between installations of the app on different devices.
I'm already using
AccountManager accountManager = AccountManager.get(mContext);
Account[] accounts = accountManager.getAccountsByType("com.google");
to pull the list of available user accounts. In the case there is just one we use that, and in the case of more than one account we ask the users to select an account to associate with the application. What I'm having issue with now is a scenario where there are no google accounts on the device. I'm currently using this
context.startActivity(new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT));
to force an add account dialog; but the issue is it gives the user an option of what account type to add, and we would like to avoid confusing them by just forcing them right in to the add Google account option. Is there a way to do this?
I know this is an old question now, but Android has provided an alternative solution.
Using AccountManager.addAccount()
requires the MANAGE_ACCOUNTS
permission. I've found that users balk at your app when they see that permission. You can avoid requiring MANAGE_ACCOUNTS
if you use the Settings.EXTRA_ACCOUNT_TYPES
extra added in API 18:
http://developer.android.com/reference/android/provider/Settings.html#EXTRA_ACCOUNT_TYPES
This launches the add Google account flow:
Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT);
intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, new String[] {"com.google"});
startActivity(intent);
I've discovered that even though Settings.EXTRA_ACCOUNT_TYPES
was added it API 18, it seems to work on all my devices running ICS or later. Sadly, it did not work on Gingerbread. I'm not sure if it can be trusted to work before API 18, but I've found success so far.
Something like this should do it:
AccountManager accountMgr = AccountManager.get(mContext);
accountMgr.addAccount("com.google", "ah", null, new Bundle(), (Activity) mContext, null, null);
"ah" is the authorization token type.
I'm not entirely sure but: http://www.thialfihar.org/projects/android_add_account/
at the bottom there's a code snippet that adds a google account, tho I'm not very sure if this is what you're looking for.
精彩评论