3

How I can add a google account by code?

I just need to add an existing account, not to create a new one. The interactive process would be similar to Setting> Accounts> Add account

Thanks!

Ricmcm
  • 123
  • 1
  • 1
  • 10

1 Answers1

1

You'll have to work out your user interface, but the simplest code to add an existing account would be something like this:

AccountMager mgr = (AccountManager)getSystemService(ACCOUNT_SERVICE);
Account acc = new Account("user@domain.com", "com.google"));
if(mgr.addAccountExplicitly(acc, "password", new Bundle())) {
    //account added successfully
    //do whatever is needed;
}
else {
    //something did not work
}

You will need AUTHENTICATE_ACCOUNTS permission. If you pass null in place of the password, then the account will be added without the password and the user will be prompted for password on the next re-sync.

If you need more control over the process, then you can use method

public AccountManagerFuture<Bundle> addAccount (String accountType,
                                                String authTokenType,
                                                String[] requiredFeatures,
                                                Bundle addAccountOptions,
                                                Activity activity,
                                                AccountManagerCallback<Bundle> callback,
                                                Handler handler)

in class AccountManager. Have a look at the AccountManager class documentation for more details.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • Thanks for your answer. I get the following exception: E/AndroidRuntime(1583): java.lang.SecurityException: caller uid 10009 is different than the authenticator's uid – Ricmcm Jul 13 '12 at 08:30
  • Have a look at [this question](http://stackoverflow.com/questions/3774282/securityexception-caller-uid-xxxx-is-different-than-the-authenticators-uid) - it may be something to do with "com.google" string. The best thing would be to use the constant one from one of the android classes, but I can't remember where it is. – Aleks G Jul 13 '12 at 08:38
  • 1
    I think the "different than the authenticator's uid" exception is saying that you can't make "com.google" accounts because you aren't Google. In other words, the original question is impossible. Please correct me if I am wrong! – mike jones Jan 28 '14 at 00:09