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!
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.