2 * Copyright (C) 2009 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package android.accounts;
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.content.Context;
22 import android.content.IntentFilter;
23 import android.content.BroadcastReceiver;
24 import android.database.SQLException;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.os.Looper;
28 import android.os.RemoteException;
29 import android.os.Parcelable;
30 import android.os.Build;
31 import android.util.Log;
32 import android.text.TextUtils;
34 import java.io.IOException;
35 import java.util.concurrent.Callable;
36 import java.util.concurrent.CancellationException;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.FutureTask;
39 import java.util.concurrent.TimeoutException;
40 import java.util.concurrent.TimeUnit;
41 import java.util.HashMap;
44 import com.google.android.collect.Maps;
47 * This class provides access to a centralized registry of the user's
48 * online accounts. The user enters credentials (username and password) once
49 * per account, granting applications access to online resources with
50 * "one-click" approval.
52 * <p>Different online services have different ways of handling accounts and
53 * authentication, so the account manager uses pluggable <em>authenticator</em>
54 * modules for different <em>account types</em>. Authenticators (which may be
55 * written by third parties) handle the actual details of validating account
56 * credentials and storing account information. For example, Google, Facebook,
57 * and Microsoft Exchange each have their own authenticator.
59 * <p>Many servers support some notion of an <em>authentication token</em>,
60 * which can be used to authenticate a request to the server without sending
61 * the user's actual password. (Auth tokens are normally created with a
62 * separate request which does include the user's credentials.) AccountManager
63 * can generate auth tokens for applications, so the application doesn't need to
64 * handle passwords directly. Auth tokens are normally reusable and cached by
65 * AccountManager, but must be refreshed periodically. It's the responsibility
66 * of applications to <em>invalidate</em> auth tokens when they stop working so
67 * the AccountManager knows it needs to regenerate them.
69 * <p>Applications accessing a server normally go through these steps:
72 * <li>Get an instance of AccountManager using {@link #get(Context)}.
74 * <li>List the available accounts using {@link #getAccountsByType} or
75 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
76 * be interested in accounts with one particular <em>type</em>, which
77 * identifies the authenticator. Account <em>features</em> are used to
78 * identify particular account subtypes and capabilities. Both the account
79 * type and features are authenticator-specific strings, and must be known by
80 * the application in coordination with its preferred authenticators.
82 * <li>Select one or more of the available accounts, possibly by asking the
83 * user for their preference. If no suitable accounts are available,
84 * {@link #addAccount} may be called to prompt the user to create an
85 * account of the appropriate type.
87 * <li><b>Important:</b> If the application is using a previously remembered
88 * account selection, it must make sure the account is still in the list
89 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
90 * for an account no longer on the device results in an undefined failure.
92 * <li>Request an auth token for the selected account(s) using one of the
93 * {@link #getAuthToken} methods or related helpers. Refer to the description
94 * of each method for exact usage and error handling details.
96 * <li>Make the request using the auth token. The form of the auth token,
97 * the format of the request, and the protocol used are all specific to the
98 * service you are accessing. The application may use whatever network and
99 * protocol libraries are useful.
101 * <li><b>Important:</b> If the request fails with an authentication error,
102 * it could be that a cached auth token is stale and no longer honored by
103 * the server. The application must call {@link #invalidateAuthToken} to remove
104 * the token from the cache, otherwise requests will continue failing! After
105 * invalidating the auth token, immediately go back to the "Request an auth
106 * token" step above. If the process fails the second time, then it can be
107 * treated as a "genuine" authentication failure and the user notified or other
108 * appropriate actions taken.
111 * <p>Some AccountManager methods may need to interact with the user to
112 * prompt for credentials, present options, or ask the user to add an account.
113 * The caller may choose whether to allow AccountManager to directly launch the
114 * necessary user interface and wait for the user, or to return an Intent which
115 * the caller may use to launch the interface, or (in some cases) to install a
116 * notification which the user can select at any time to launch the interface.
117 * To have AccountManager launch the interface directly, the caller must supply
118 * the current foreground {@link Activity} context.
120 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
121 * {@link Handler} as parameters. These methods return immediately and
122 * run asynchronously. If a callback is provided then
123 * {@link AccountManagerCallback#run} will be invoked on the Handler's
124 * thread when the request completes, successfully or not.
125 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
126 * on the {@link AccountManagerFuture} returned by the method (and also passed
127 * to the callback). This method waits for the operation to complete (if
128 * necessary) and either returns the result or throws an exception if an error
129 * occurred during the operation. To make the request synchronously, call
130 * {@link AccountManagerFuture#getResult()} immediately on receiving the
131 * future from the method; no callback need be supplied.
133 * <p>Requests which may block, including
134 * {@link AccountManagerFuture#getResult()}, must never be called on
135 * the application's main event thread. These operations throw
136 * {@link IllegalStateException} if they are used on the main thread.
138 public class AccountManager {
139 private static final String TAG = "AccountManager";
141 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
142 public static final int ERROR_CODE_NETWORK_ERROR = 3;
143 public static final int ERROR_CODE_CANCELED = 4;
144 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
145 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
146 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
147 public static final int ERROR_CODE_BAD_REQUEST = 8;
150 * Bundle key used for the {@link String} account name in results
151 * from methods which return information about a particular account.
153 public static final String KEY_ACCOUNT_NAME = "authAccount";
156 * Bundle key used for the {@link String} account type in results
157 * from methods which return information about a particular account.
159 public static final String KEY_ACCOUNT_TYPE = "accountType";
162 * Bundle key used for the auth token value in results
163 * from {@link #getAuthToken} and friends.
165 public static final String KEY_AUTHTOKEN = "authtoken";
168 * Bundle key used for an {@link Intent} in results from methods that
169 * may require the caller to interact with the user. The Intent can
170 * be used to start the corresponding user interface activity.
172 public static final String KEY_INTENT = "intent";
175 * Bundle key used to supply the password directly in options to
176 * {@link #confirmCredentials}, rather than prompting the user with
177 * the standard password prompt.
179 public static final String KEY_PASSWORD = "password";
181 public static final String KEY_ACCOUNTS = "accounts";
182 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
183 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
184 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
185 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
186 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
187 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
188 public static final String KEY_ERROR_CODE = "errorCode";
189 public static final String KEY_ERROR_MESSAGE = "errorMessage";
190 public static final String KEY_USERDATA = "userdata";
192 public static final String ACTION_AUTHENTICATOR_INTENT =
193 "android.accounts.AccountAuthenticator";
194 public static final String AUTHENTICATOR_META_DATA_NAME =
195 "android.accounts.AccountAuthenticator";
196 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
198 private final Context mContext;
199 private final IAccountManager mService;
200 private final Handler mMainHandler;
203 * Action sent as a broadcast Intent by the AccountsService
204 * when accounts are added, accounts are removed, or an
205 * account's credentials (saved password, etc) are changed.
207 * @see #addOnAccountsUpdatedListener
209 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
210 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
215 public AccountManager(Context context, IAccountManager service) {
218 mMainHandler = new Handler(mContext.getMainLooper());
222 * @hide used for testing only
224 public AccountManager(Context context, IAccountManager service, Handler handler) {
227 mMainHandler = handler;
231 * @hide for internal use only
233 public static Bundle sanitizeResult(Bundle result) {
234 if (result != null) {
235 if (result.containsKey(KEY_AUTHTOKEN)
236 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
237 final Bundle newResult = new Bundle(result);
238 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
246 * Gets an AccountManager instance associated with a Context.
247 * The {@link Context} will be used as long as the AccountManager is
248 * active, so make sure to use a {@link Context} whose lifetime is
249 * commensurate with any listeners registered to
250 * {@link #addOnAccountsUpdatedListener} or similar methods.
252 * <p>It is safe to call this method from the main thread.
254 * <p>No permission is required to call this method.
256 * @param context The {@link Context} to use when necessary
257 * @return An {@link AccountManager} instance
259 public static AccountManager get(Context context) {
260 if (context == null) throw new IllegalArgumentException("context is null");
261 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
265 * Gets the saved password associated with the account.
266 * This is intended for authenticators and related code; applications
267 * should get an auth token instead.
269 * <p>It is safe to call this method from the main thread.
271 * <p>This method requires the caller to hold the permission
272 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
273 * and to have the same UID as the account's authenticator.
275 * @param account The account to query for a password
276 * @return The account's password, null if none or if the account doesn't exist
278 public String getPassword(final Account account) {
279 if (account == null) throw new IllegalArgumentException("account is null");
281 return mService.getPassword(account);
282 } catch (RemoteException e) {
284 throw new RuntimeException(e);
289 * Gets the user data named by "key" associated with the account.
290 * This is intended for authenticators and related code to store
291 * arbitrary metadata along with accounts. The meaning of the keys
292 * and values is up to the authenticator for the account.
294 * <p>It is safe to call this method from the main thread.
296 * <p>This method requires the caller to hold the permission
297 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
298 * and to have the same UID as the account's authenticator.
300 * @param account The account to query for user data
301 * @return The user data, null if the account or key doesn't exist
303 public String getUserData(final Account account, final String key) {
304 if (account == null) throw new IllegalArgumentException("account is null");
305 if (key == null) throw new IllegalArgumentException("key is null");
307 return mService.getUserData(account, key);
308 } catch (RemoteException e) {
310 throw new RuntimeException(e);
315 * Lists the currently registered authenticators.
317 * <p>It is safe to call this method from the main thread.
319 * <p>No permission is required to call this method.
321 * @return An array of {@link AuthenticatorDescription} for every
322 * authenticator known to the AccountManager service. Empty (never
323 * null) if no authenticators are known.
325 public AuthenticatorDescription[] getAuthenticatorTypes() {
327 return mService.getAuthenticatorTypes();
328 } catch (RemoteException e) {
330 throw new RuntimeException(e);
335 * Lists all accounts of any type registered on the device.
336 * Equivalent to getAccountsByType(null).
338 * <p>It is safe to call this method from the main thread.
340 * <p>This method requires the caller to hold the permission
341 * {@link android.Manifest.permission#GET_ACCOUNTS}.
343 * @return An array of {@link Account}, one for each account. Empty
344 * (never null) if no accounts have been added.
346 public Account[] getAccounts() {
348 return mService.getAccounts(null);
349 } catch (RemoteException e) {
351 throw new RuntimeException(e);
356 * Lists all accounts of a particular type. The account type is a
357 * string token corresponding to the authenticator and useful domain
358 * of the account. For example, there are types corresponding to Google
359 * and Facebook. The exact string token to use will be published somewhere
360 * associated with the authenticator in question.
362 * <p>It is safe to call this method from the main thread.
364 * <p>This method requires the caller to hold the permission
365 * {@link android.Manifest.permission#GET_ACCOUNTS}.
367 * @param type The type of accounts to return, null to retrieve all accounts
368 * @return An array of {@link Account}, one per matching account. Empty
369 * (never null) if no accounts of the specified type have been added.
371 public Account[] getAccountsByType(String type) {
373 return mService.getAccounts(type);
374 } catch (RemoteException e) {
376 throw new RuntimeException(e);
381 * Finds out whether a particular account has all the specified features.
382 * Account features are authenticator-specific string tokens identifying
383 * boolean account properties. For example, features are used to tell
384 * whether Google accounts have a particular service (such as Google
385 * Calendar or Google Talk) enabled. The feature names and their meanings
386 * are published somewhere associated with the authenticator in question.
388 * <p>This method may be called from any thread, but the returned
389 * {@link AccountManagerFuture} must not be used on the main thread.
391 * <p>This method requires the caller to hold the permission
392 * {@link android.Manifest.permission#GET_ACCOUNTS}.
394 * @param account The {@link Account} to test
395 * @param features An array of the account features to check
396 * @param callback Callback to invoke when the request completes,
397 * null for no callback
398 * @param handler {@link Handler} identifying the callback thread,
399 * null for the main thread
400 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
401 * true if the account exists and has all of the specified features.
403 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
404 final String[] features,
405 AccountManagerCallback<Boolean> callback, Handler handler) {
406 if (account == null) throw new IllegalArgumentException("account is null");
407 if (features == null) throw new IllegalArgumentException("features is null");
408 return new Future2Task<Boolean>(handler, callback) {
409 public void doWork() throws RemoteException {
410 mService.hasFeatures(mResponse, account, features);
412 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
413 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
414 throw new AuthenticatorException("no result in response");
416 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
422 * Lists all accounts of a type which have certain features. The account
423 * type identifies the authenticator (see {@link #getAccountsByType}).
424 * Account features are authenticator-specific string tokens identifying
425 * boolean account properties (see {@link #hasFeatures}).
427 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
428 * which may contact the server or do other work to check account features,
429 * so the method returns an {@link AccountManagerFuture}.
431 * <p>This method may be called from any thread, but the returned
432 * {@link AccountManagerFuture} must not be used on the main thread.
434 * <p>This method requires the caller to hold the permission
435 * {@link android.Manifest.permission#GET_ACCOUNTS}.
437 * @param type The type of accounts to return, must not be null
438 * @param features An array of the account features to require,
439 * may be null or empty
440 * @param callback Callback to invoke when the request completes,
441 * null for no callback
442 * @param handler {@link Handler} identifying the callback thread,
443 * null for the main thread
444 * @return An {@link AccountManagerFuture} which resolves to an array of
445 * {@link Account}, one per account of the specified type which
446 * matches the requested features.
448 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
449 final String type, final String[] features,
450 AccountManagerCallback<Account[]> callback, Handler handler) {
451 if (type == null) throw new IllegalArgumentException("type is null");
452 return new Future2Task<Account[]>(handler, callback) {
453 public void doWork() throws RemoteException {
454 mService.getAccountsByFeatures(mResponse, type, features);
456 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
457 if (!bundle.containsKey(KEY_ACCOUNTS)) {
458 throw new AuthenticatorException("no result in response");
460 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
461 Account[] descs = new Account[parcelables.length];
462 for (int i = 0; i < parcelables.length; i++) {
463 descs[i] = (Account) parcelables[i];
471 * Adds an account directly to the AccountManager. Normally used by sign-up
472 * wizards associated with authenticators, not directly by applications.
474 * <p>It is safe to call this method from the main thread.
476 * <p>This method requires the caller to hold the permission
477 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
478 * and to have the same UID as the added account's authenticator.
480 * @param account The {@link Account} to add
481 * @param password The password to associate with the account, null for none
482 * @param userdata String values to use for the account's userdata, null for none
483 * @return True if the account was successfully added, false if the account
484 * already exists, the account is null, or another error occurs.
486 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
487 if (account == null) throw new IllegalArgumentException("account is null");
489 return mService.addAccount(account, password, userdata);
490 } catch (RemoteException e) {
492 throw new RuntimeException(e);
497 * Removes an account from the AccountManager. Does nothing if the account
498 * does not exist. Does not delete the account from the server.
499 * The authenticator may have its own policies preventing account
500 * deletion, in which case the account will not be deleted.
502 * <p>This method may be called from any thread, but the returned
503 * {@link AccountManagerFuture} must not be used on the main thread.
505 * <p>This method requires the caller to hold the permission
506 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
508 * @param account The {@link Account} to remove
509 * @param callback Callback to invoke when the request completes,
510 * null for no callback
511 * @param handler {@link Handler} identifying the callback thread,
512 * null for the main thread
513 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
514 * true if the account has been successfully removed,
515 * false if the authenticator forbids deleting this account.
517 public AccountManagerFuture<Boolean> removeAccount(final Account account,
518 AccountManagerCallback<Boolean> callback, Handler handler) {
519 if (account == null) throw new IllegalArgumentException("account is null");
520 return new Future2Task<Boolean>(handler, callback) {
521 public void doWork() throws RemoteException {
522 mService.removeAccount(mResponse, account);
524 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
525 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
526 throw new AuthenticatorException("no result in response");
528 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
534 * Removes an auth token from the AccountManager's cache. Does nothing if
535 * the auth token is not currently in the cache. Applications must call this
536 * method when the auth token is found to have expired or otherwise become
537 * invalid for authenticating requests. The AccountManager does not validate
538 * or expire cached auth tokens otherwise.
540 * <p>It is safe to call this method from the main thread.
542 * <p>This method requires the caller to hold the permission
543 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
544 * {@link android.Manifest.permission#USE_CREDENTIALS}
546 * @param accountType The account type of the auth token to invalidate, must not be null
547 * @param authToken The auth token to invalidate, may be null
549 public void invalidateAuthToken(final String accountType, final String authToken) {
550 if (accountType == null) throw new IllegalArgumentException("accountType is null");
552 if (authToken != null) {
553 mService.invalidateAuthToken(accountType, authToken);
555 } catch (RemoteException e) {
557 throw new RuntimeException(e);
562 * Gets an auth token from the AccountManager's cache. If no auth
563 * token is cached for this account, null will be returned -- a new
564 * auth token will not be generated, and the server will not be contacted.
565 * Intended for use by the authenticator, not directly by applications.
567 * <p>It is safe to call this method from the main thread.
569 * <p>This method requires the caller to hold the permission
570 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
571 * and to have the same UID as the account's authenticator.
573 * @param account The account to fetch an auth token for
574 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
575 * @return The cached auth token for this account and type, or null if
576 * no auth token is cached or the account does not exist.
578 public String peekAuthToken(final Account account, final String authTokenType) {
579 if (account == null) throw new IllegalArgumentException("account is null");
580 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
582 return mService.peekAuthToken(account, authTokenType);
583 } catch (RemoteException e) {
585 throw new RuntimeException(e);
590 * Sets or forgets a saved password. This modifies the local copy of the
591 * password used to automatically authenticate the user; it does
592 * not change the user's account password on the server. Intended for use
593 * by the authenticator, not directly by applications.
595 * <p>It is safe to call this method from the main thread.
597 * <p>This method requires the caller to hold the permission
598 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
599 * and have the same UID as the account's authenticator.
601 * @param account The account to set a password for
602 * @param password The password to set, null to clear the password
604 public void setPassword(final Account account, final String password) {
605 if (account == null) throw new IllegalArgumentException("account is null");
607 mService.setPassword(account, password);
608 } catch (RemoteException e) {
610 throw new RuntimeException(e);
615 * Forgets a saved password. This erases the local copy of the password;
616 * it does not change the user's account password on the server.
617 * Has the same effect as setPassword(account, null) but requires fewer
618 * permissions, and may be used by applications or management interfaces
619 * to "sign out" from an account.
621 * <p>It is safe to call this method from the main thread.
623 * <p>This method requires the caller to hold the permission
624 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
626 * @param account The account whose password to clear
628 public void clearPassword(final Account account) {
629 if (account == null) throw new IllegalArgumentException("account is null");
631 mService.clearPassword(account);
632 } catch (RemoteException e) {
634 throw new RuntimeException(e);
639 * Sets one userdata key for an account. Intended by use for the
640 * authenticator to stash state for itself, not directly by applications.
641 * The meaning of the keys and values is up to the authenticator.
643 * <p>It is safe to call this method from the main thread.
645 * <p>This method requires the caller to hold the permission
646 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
647 * and to have the same UID as the account's authenticator.
649 * @param account The account to set the userdata for
650 * @param key The userdata key to set. Must not be null
651 * @param value The value to set, null to clear this userdata key
653 public void setUserData(final Account account, final String key, final String value) {
654 if (account == null) throw new IllegalArgumentException("account is null");
655 if (key == null) throw new IllegalArgumentException("key is null");
657 mService.setUserData(account, key, value);
658 } catch (RemoteException e) {
660 throw new RuntimeException(e);
665 * Adds an auth token to the AccountManager cache for an account.
666 * If the account does not exist then this call has no effect.
667 * Replaces any previous auth token for this account and auth token type.
668 * Intended for use by the authenticator, not directly by applications.
670 * <p>It is safe to call this method from the main thread.
672 * <p>This method requires the caller to hold the permission
673 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
674 * and to have the same UID as the account's authenticator.
676 * @param account The account to set an auth token for
677 * @param authTokenType The type of the auth token, see {#getAuthToken}
678 * @param authToken The auth token to add to the cache
680 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
681 if (account == null) throw new IllegalArgumentException("account is null");
682 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
684 mService.setAuthToken(account, authTokenType, authToken);
685 } catch (RemoteException e) {
687 throw new RuntimeException(e);
692 * This convenience helper synchronously gets an auth token with
693 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
695 * <p>This method may block while a network request completes, and must
696 * never be made from the main thread.
698 * <p>This method requires the caller to hold the permission
699 * {@link android.Manifest.permission#USE_CREDENTIALS}.
701 * @param account The account to fetch an auth token for
702 * @param authTokenType The auth token type, see {#link getAuthToken}
703 * @param notifyAuthFailure If true, display a notification and return null
704 * if authentication fails; if false, prompt and wait for the user to
705 * re-enter correct credentials before returning
706 * @return An auth token of the specified type for this account, or null
707 * if authentication fails or none can be fetched.
708 * @throws AuthenticatorException if the authenticator failed to respond
709 * @throws OperationCanceledException if the request was canceled for any
710 * reason, including the user canceling a credential request
711 * @throws java.io.IOException if the authenticator experienced an I/O problem
712 * creating a new auth token, usually because of network trouble
714 public String blockingGetAuthToken(Account account, String authTokenType,
715 boolean notifyAuthFailure)
716 throws OperationCanceledException, IOException, AuthenticatorException {
717 if (account == null) throw new IllegalArgumentException("account is null");
718 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
719 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
720 null /* handler */).getResult();
721 if (bundle == null) {
722 // This should never happen, but it does, occasionally. If it does return null to
723 // signify that we were not able to get the authtoken.
724 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
726 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
727 + account + ", authTokenType " + authTokenType);
730 return bundle.getString(KEY_AUTHTOKEN);
734 * Gets an auth token of the specified type for a particular account,
735 * prompting the user for credentials if necessary. This method is
736 * intended for applications running in the foreground where it makes
737 * sense to ask the user directly for a password.
739 * <p>If a previously generated auth token is cached for this account and
740 * type, then it is returned. Otherwise, if a saved password is
741 * available, it is sent to the server to generate a new auth token.
742 * Otherwise, the user is prompted to enter a password.
744 * <p>Some authenticators have auth token <em>types</em>, whose value
745 * is authenticator-dependent. Some services use different token types to
746 * access different functionality -- for example, Google uses different auth
747 * tokens to access Gmail and Google Calendar for the same account.
749 * <p>This method may be called from any thread, but the returned
750 * {@link AccountManagerFuture} must not be used on the main thread.
752 * <p>This method requires the caller to hold the permission
753 * {@link android.Manifest.permission#USE_CREDENTIALS}.
755 * @param account The account to fetch an auth token for
756 * @param authTokenType The auth token type, an authenticator-dependent
757 * string token, must not be null
758 * @param options Authenticator-specific options for the request,
759 * may be null or empty
760 * @param activity The {@link Activity} context to use for launching a new
761 * authenticator-defined sub-Activity to prompt the user for a password
762 * if necessary; used only to call startActivity(); must not be null.
763 * @param callback Callback to invoke when the request completes,
764 * null for no callback
765 * @param handler {@link Handler} identifying the callback thread,
766 * null for the main thread
767 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
768 * at least the following fields:
770 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
771 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
772 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
775 * (Other authenticator-specific values may be returned.) If an auth token
776 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
778 * <li> {@link AuthenticatorException} if the authenticator failed to respond
779 * <li> {@link OperationCanceledException} if the operation is canceled for
780 * any reason, incluidng the user canceling a credential request
781 * <li> {@link IOException} if the authenticator experienced an I/O problem
782 * creating a new auth token, usually because of network trouble
784 * If the account is no longer present on the device, the return value is
785 * authenticator-dependent. The caller should verify the validity of the
786 * account before requesting an auth token.
788 public AccountManagerFuture<Bundle> getAuthToken(
789 final Account account, final String authTokenType, final Bundle options,
790 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
791 if (account == null) throw new IllegalArgumentException("account is null");
792 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
793 return new AmsTask(activity, handler, callback) {
794 public void doWork() throws RemoteException {
795 mService.getAuthToken(mResponse, account, authTokenType,
796 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
803 * Gets an auth token of the specified type for a particular account,
804 * optionally raising a notification if the user must enter credentials.
805 * This method is intended for background tasks and services where the
806 * user should not be immediately interrupted with a password prompt.
808 * <p>If a previously generated auth token is cached for this account and
809 * type, then it is returned. Otherwise, if a saved password is
810 * available, it is sent to the server to generate a new auth token.
811 * Otherwise, an {@link Intent} is returned which, when started, will
812 * prompt the user for a password. If the notifyAuthFailure parameter is
813 * set, a status bar notification is also created with the same Intent,
814 * alerting the user that they need to enter a password at some point.
816 * <p>In that case, you may need to wait until the user responds, which
817 * could take hours or days or forever. When the user does respond and
818 * supply a new password, the account manager will broadcast the
819 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
822 * <p>If notifyAuthFailure is not set, it is the application's
823 * responsibility to launch the returned Intent at some point.
824 * Either way, the result from this call will not wait for user action.
826 * <p>Some authenticators have auth token <em>types</em>, whose value
827 * is authenticator-dependent. Some services use different token types to
828 * access different functionality -- for example, Google uses different auth
829 * tokens to access Gmail and Google Calendar for the same account.
831 * <p>This method may be called from any thread, but the returned
832 * {@link AccountManagerFuture} must not be used on the main thread.
834 * <p>This method requires the caller to hold the permission
835 * {@link android.Manifest.permission#USE_CREDENTIALS}.
837 * @param account The account to fetch an auth token for
838 * @param authTokenType The auth token type, an authenticator-dependent
839 * string token, must not be null
840 * @param notifyAuthFailure True to add a notification to prompt the
841 * user for a password if necessary, false to leave that to the caller
842 * @param callback Callback to invoke when the request completes,
843 * null for no callback
844 * @param handler {@link Handler} identifying the callback thread,
845 * null for the main thread
846 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
847 * at least the following fields on success:
849 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
850 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
851 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
854 * (Other authenticator-specific values may be returned.) If the user
855 * must enter credentials, the returned Bundle contains only
856 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
858 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
860 * <li> {@link AuthenticatorException} if the authenticator failed to respond
861 * <li> {@link OperationCanceledException} if the operation is canceled for
862 * any reason, incluidng the user canceling a credential request
863 * <li> {@link IOException} if the authenticator experienced an I/O problem
864 * creating a new auth token, usually because of network trouble
866 * If the account is no longer present on the device, the return value is
867 * authenticator-dependent. The caller should verify the validity of the
868 * account before requesting an auth token.
870 public AccountManagerFuture<Bundle> getAuthToken(
871 final Account account, final String authTokenType, final boolean notifyAuthFailure,
872 AccountManagerCallback<Bundle> callback, Handler handler) {
873 if (account == null) throw new IllegalArgumentException("account is null");
874 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
875 return new AmsTask(null, handler, callback) {
876 public void doWork() throws RemoteException {
877 mService.getAuthToken(mResponse, account, authTokenType,
878 notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
884 * Asks the user to add an account of a specified type. The authenticator
885 * for this account type processes this request with the appropriate user
886 * interface. If the user does elect to create a new account, the account
889 * <p>This method may be called from any thread, but the returned
890 * {@link AccountManagerFuture} must not be used on the main thread.
892 * <p>This method requires the caller to hold the permission
893 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
895 * @param accountType The type of account to add; must not be null
896 * @param authTokenType The type of auth token (see {@link #getAuthToken})
897 * this account will need to be able to generate, null for none
898 * @param requiredFeatures The features (see {@link #hasFeatures}) this
899 * account must have, null for none
900 * @param addAccountOptions Authenticator-specific options for the request,
901 * may be null or empty
902 * @param activity The {@link Activity} context to use for launching a new
903 * authenticator-defined sub-Activity to prompt the user to create an
904 * account; used only to call startActivity(); if null, the prompt
905 * will not be launched directly, but the necessary {@link Intent}
906 * will be returned to the caller instead
907 * @param callback Callback to invoke when the request completes,
908 * null for no callback
909 * @param handler {@link Handler} identifying the callback thread,
910 * null for the main thread
911 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
912 * these fields if activity was specified and an account was created:
914 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
915 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
918 * If no activity was specified, the returned Bundle contains only
919 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
920 * actual account creation process. If an error occurred,
921 * {@link AccountManagerFuture#getResult()} throws:
923 * <li> {@link AuthenticatorException} if no authenticator was registered for
924 * this account type or the authenticator failed to respond
925 * <li> {@link OperationCanceledException} if the operation was canceled for
926 * any reason, including the user canceling the creation process
927 * <li> {@link IOException} if the authenticator experienced an I/O problem
928 * creating a new account, usually because of network trouble
931 public AccountManagerFuture<Bundle> addAccount(final String accountType,
932 final String authTokenType, final String[] requiredFeatures,
933 final Bundle addAccountOptions,
934 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
935 if (accountType == null) throw new IllegalArgumentException("accountType is null");
936 return new AmsTask(activity, handler, callback) {
937 public void doWork() throws RemoteException {
938 mService.addAcount(mResponse, accountType, authTokenType,
939 requiredFeatures, activity != null, addAccountOptions);
945 * Confirms that the user knows the password for an account to make extra
946 * sure they are the owner of the account. The user-entered password can
947 * be supplied directly, otherwise the authenticator for this account type
948 * prompts the user with the appropriate interface. This method is
949 * intended for applications which want extra assurance; for example, the
950 * phone lock screen uses this to let the user unlock the phone with an
951 * account password if they forget the lock pattern.
953 * <p>If the user-entered password matches a saved password for this
954 * account, the request is considered valid; otherwise the authenticator
955 * verifies the password (usually by contacting the server).
957 * <p>This method may be called from any thread, but the returned
958 * {@link AccountManagerFuture} must not be used on the main thread.
960 * <p>This method requires the caller to hold the permission
961 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
963 * @param account The account to confirm password knowledge for
964 * @param options Authenticator-specific options for the request;
965 * if the {@link #KEY_PASSWORD} string field is present, the
966 * authenticator may use it directly rather than prompting the user;
967 * may be null or empty
968 * @param activity The {@link Activity} context to use for launching a new
969 * authenticator-defined sub-Activity to prompt the user to enter a
970 * password; used only to call startActivity(); if null, the prompt
971 * will not be launched directly, but the necessary {@link Intent}
972 * will be returned to the caller instead
973 * @param callback Callback to invoke when the request completes,
974 * null for no callback
975 * @param handler {@link Handler} identifying the callback thread,
976 * null for the main thread
977 * @return An {@link AccountManagerFuture} which resolves to a Bundle
978 * with these fields if activity or password was supplied and
979 * the account was successfully verified:
981 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
982 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
983 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
986 * If no activity or password was specified, the returned Bundle contains
987 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
988 * password prompt. If an error occurred,
989 * {@link AccountManagerFuture#getResult()} throws:
991 * <li> {@link AuthenticatorException} if the authenticator failed to respond
992 * <li> {@link OperationCanceledException} if the operation was canceled for
993 * any reason, including the user canceling the password prompt
994 * <li> {@link IOException} if the authenticator experienced an I/O problem
995 * verifying the password, usually because of network trouble
998 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
999 final Bundle options,
1000 final Activity activity,
1001 final AccountManagerCallback<Bundle> callback,
1002 final Handler handler) {
1003 if (account == null) throw new IllegalArgumentException("account is null");
1004 return new AmsTask(activity, handler, callback) {
1005 public void doWork() throws RemoteException {
1006 mService.confirmCredentials(mResponse, account, options, activity != null);
1012 * Asks the user to enter a new password for an account, updating the
1013 * saved credentials for the account. Normally this happens automatically
1014 * when the server rejects credentials during an auth token fetch, but this
1015 * can be invoked directly to ensure we have the correct credentials stored.
1017 * <p>This method may be called from any thread, but the returned
1018 * {@link AccountManagerFuture} must not be used on the main thread.
1020 * <p>This method requires the caller to hold the permission
1021 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1023 * @param account The account to update credentials for
1024 * @param authTokenType The credentials entered must allow an auth token
1025 * of this type to be created (but no actual auth token is returned);
1027 * @param options Authenticator-specific options for the request;
1028 * may be null or empty
1029 * @param activity The {@link Activity} context to use for launching a new
1030 * authenticator-defined sub-Activity to prompt the user to enter a
1031 * password; used only to call startActivity(); if null, the prompt
1032 * will not be launched directly, but the necessary {@link Intent}
1033 * will be returned to the caller instead
1034 * @param callback Callback to invoke when the request completes,
1035 * null for no callback
1036 * @param handler {@link Handler} identifying the callback thread,
1037 * null for the main thread
1038 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1039 * with these fields if an activity was supplied and the account
1040 * credentials were successfully updated:
1042 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1043 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1046 * If no activity was specified, the returned Bundle contains only
1047 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1048 * password prompt. If an error occurred,
1049 * {@link AccountManagerFuture#getResult()} throws:
1051 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1052 * <li> {@link OperationCanceledException} if the operation was canceled for
1053 * any reason, including the user canceling the password prompt
1054 * <li> {@link IOException} if the authenticator experienced an I/O problem
1055 * verifying the password, usually because of network trouble
1058 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1059 final String authTokenType,
1060 final Bundle options, final Activity activity,
1061 final AccountManagerCallback<Bundle> callback,
1062 final Handler handler) {
1063 if (account == null) throw new IllegalArgumentException("account is null");
1064 return new AmsTask(activity, handler, callback) {
1065 public void doWork() throws RemoteException {
1066 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
1073 * Offers the user an opportunity to change an authenticator's settings.
1074 * These properties are for the authenticator in general, not a particular
1075 * account. Not all authenticators support this method.
1077 * <p>This method may be called from any thread, but the returned
1078 * {@link AccountManagerFuture} must not be used on the main thread.
1080 * <p>This method requires the caller to hold the permission
1081 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1083 * @param accountType The account type associated with the authenticator
1085 * @param activity The {@link Activity} context to use for launching a new
1086 * authenticator-defined sub-Activity to adjust authenticator settings;
1087 * used only to call startActivity(); if null, the settings dialog will
1088 * not be launched directly, but the necessary {@link Intent} will be
1089 * returned to the caller instead
1090 * @param callback Callback to invoke when the request completes,
1091 * null for no callback
1092 * @param handler {@link Handler} identifying the callback thread,
1093 * null for the main thread
1094 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1095 * which is empty if properties were edited successfully, or
1096 * if no activity was specified, contains only {@link #KEY_INTENT}
1097 * needed to launch the authenticator's settings dialog.
1098 * If an error occurred, {@link AccountManagerFuture#getResult()}
1101 * <li> {@link AuthenticatorException} if no authenticator was registered for
1102 * this account type or the authenticator failed to respond
1103 * <li> {@link OperationCanceledException} if the operation was canceled for
1104 * any reason, including the user canceling the settings dialog
1105 * <li> {@link IOException} if the authenticator experienced an I/O problem
1106 * updating settings, usually because of network trouble
1109 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1110 final Activity activity, final AccountManagerCallback<Bundle> callback,
1111 final Handler handler) {
1112 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1113 return new AmsTask(activity, handler, callback) {
1114 public void doWork() throws RemoteException {
1115 mService.editProperties(mResponse, accountType, activity != null);
1120 private void ensureNotOnMainThread() {
1121 final Looper looper = Looper.myLooper();
1122 if (looper != null && looper == mContext.getMainLooper()) {
1123 final IllegalStateException exception = new IllegalStateException(
1124 "calling this from your main thread can lead to deadlock");
1125 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1127 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1133 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1134 final AccountManagerFuture<Bundle> future) {
1135 handler = handler == null ? mMainHandler : handler;
1136 handler.post(new Runnable() {
1138 callback.run(future);
1143 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
1144 final Account[] accounts) {
1145 final Account[] accountsCopy = new Account[accounts.length];
1146 // send a copy to make sure that one doesn't
1147 // change what another sees
1148 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1149 handler = (handler == null) ? mMainHandler : handler;
1150 handler.post(new Runnable() {
1153 listener.onAccountsUpdated(accountsCopy);
1154 } catch (SQLException e) {
1155 // Better luck next time. If the problem was disk-full,
1156 // the STORAGE_OK intent will re-trigger the update.
1157 Log.e(TAG, "Can't update accounts", e);
1163 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
1164 final IAccountManagerResponse mResponse;
1165 final Handler mHandler;
1166 final AccountManagerCallback<Bundle> mCallback;
1167 final Activity mActivity;
1168 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
1169 super(new Callable<Bundle>() {
1170 public Bundle call() throws Exception {
1171 throw new IllegalStateException("this should never be called");
1176 mCallback = callback;
1177 mActivity = activity;
1178 mResponse = new Response();
1181 public final AccountManagerFuture<Bundle> start() {
1184 } catch (RemoteException e) {
1190 protected void set(Bundle bundle) {
1191 // TODO: somehow a null is being set as the result of the Future. Log this
1192 // case to help debug where this is occurring. When this bug is fixed this
1193 // condition statement should be removed.
1194 if (bundle == null) {
1195 Log.e(TAG, "the bundle must not be null", new Exception());
1200 public abstract void doWork() throws RemoteException;
1202 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1203 throws OperationCanceledException, IOException, AuthenticatorException {
1205 ensureNotOnMainThread();
1208 if (timeout == null) {
1211 return get(timeout, unit);
1213 } catch (CancellationException e) {
1214 throw new OperationCanceledException();
1215 } catch (TimeoutException e) {
1216 // fall through and cancel
1217 } catch (InterruptedException e) {
1218 // fall through and cancel
1219 } catch (ExecutionException e) {
1220 final Throwable cause = e.getCause();
1221 if (cause instanceof IOException) {
1222 throw (IOException) cause;
1223 } else if (cause instanceof UnsupportedOperationException) {
1224 throw new AuthenticatorException(cause);
1225 } else if (cause instanceof AuthenticatorException) {
1226 throw (AuthenticatorException) cause;
1227 } else if (cause instanceof RuntimeException) {
1228 throw (RuntimeException) cause;
1229 } else if (cause instanceof Error) {
1230 throw (Error) cause;
1232 throw new IllegalStateException(cause);
1235 cancel(true /* interrupt if running */);
1237 throw new OperationCanceledException();
1240 public Bundle getResult()
1241 throws OperationCanceledException, IOException, AuthenticatorException {
1242 return internalGetResult(null, null);
1245 public Bundle getResult(long timeout, TimeUnit unit)
1246 throws OperationCanceledException, IOException, AuthenticatorException {
1247 return internalGetResult(timeout, unit);
1250 protected void done() {
1251 if (mCallback != null) {
1252 postToHandler(mHandler, mCallback, this);
1256 /** Handles the responses from the AccountManager */
1257 private class Response extends IAccountManagerResponse.Stub {
1258 public void onResult(Bundle bundle) {
1259 Intent intent = bundle.getParcelable("intent");
1260 if (intent != null && mActivity != null) {
1261 // since the user provided an Activity we will silently start intents
1263 mActivity.startActivity(intent);
1264 // leave the Future running to wait for the real response to this request
1265 } else if (bundle.getBoolean("retry")) {
1268 } catch (RemoteException e) {
1269 // this will only happen if the system process is dead, which means
1270 // we will be dying ourselves
1277 public void onError(int code, String message) {
1278 if (code == ERROR_CODE_CANCELED) {
1279 // the authenticator indicated that this request was canceled, do so now
1280 cancel(true /* mayInterruptIfRunning */);
1283 setException(convertErrorToException(code, message));
1289 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1290 final public IAccountManagerResponse mResponse;
1291 final Handler mHandler;
1293 public BaseFutureTask(Handler handler) {
1294 super(new Callable<T>() {
1295 public T call() throws Exception {
1296 throw new IllegalStateException("this should never be called");
1300 mResponse = new Response();
1303 public abstract void doWork() throws RemoteException;
1305 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
1307 protected void postRunnableToHandler(Runnable runnable) {
1308 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1309 handler.post(runnable);
1312 protected void startTask() {
1315 } catch (RemoteException e) {
1320 protected class Response extends IAccountManagerResponse.Stub {
1321 public void onResult(Bundle bundle) {
1323 T result = bundleToResult(bundle);
1324 if (result == null) {
1329 } catch (ClassCastException e) {
1330 // we will set the exception below
1331 } catch (AuthenticatorException e) {
1332 // we will set the exception below
1334 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
1337 public void onError(int code, String message) {
1338 if (code == ERROR_CODE_CANCELED) {
1339 cancel(true /* mayInterruptIfRunning */);
1342 setException(convertErrorToException(code, message));
1347 private abstract class Future2Task<T>
1348 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1349 final AccountManagerCallback<T> mCallback;
1350 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1352 mCallback = callback;
1355 protected void done() {
1356 if (mCallback != null) {
1357 postRunnableToHandler(new Runnable() {
1359 mCallback.run(Future2Task.this);
1365 public Future2Task<T> start() {
1370 private T internalGetResult(Long timeout, TimeUnit unit)
1371 throws OperationCanceledException, IOException, AuthenticatorException {
1373 ensureNotOnMainThread();
1376 if (timeout == null) {
1379 return get(timeout, unit);
1381 } catch (InterruptedException e) {
1382 // fall through and cancel
1383 } catch (TimeoutException e) {
1384 // fall through and cancel
1385 } catch (CancellationException e) {
1386 // fall through and cancel
1387 } catch (ExecutionException e) {
1388 final Throwable cause = e.getCause();
1389 if (cause instanceof IOException) {
1390 throw (IOException) cause;
1391 } else if (cause instanceof UnsupportedOperationException) {
1392 throw new AuthenticatorException(cause);
1393 } else if (cause instanceof AuthenticatorException) {
1394 throw (AuthenticatorException) cause;
1395 } else if (cause instanceof RuntimeException) {
1396 throw (RuntimeException) cause;
1397 } else if (cause instanceof Error) {
1398 throw (Error) cause;
1400 throw new IllegalStateException(cause);
1403 cancel(true /* interrupt if running */);
1405 throw new OperationCanceledException();
1408 public T getResult()
1409 throws OperationCanceledException, IOException, AuthenticatorException {
1410 return internalGetResult(null, null);
1413 public T getResult(long timeout, TimeUnit unit)
1414 throws OperationCanceledException, IOException, AuthenticatorException {
1415 return internalGetResult(timeout, unit);
1420 private Exception convertErrorToException(int code, String message) {
1421 if (code == ERROR_CODE_NETWORK_ERROR) {
1422 return new IOException(message);
1425 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
1426 return new UnsupportedOperationException(message);
1429 if (code == ERROR_CODE_INVALID_RESPONSE) {
1430 return new AuthenticatorException(message);
1433 if (code == ERROR_CODE_BAD_ARGUMENTS) {
1434 return new IllegalArgumentException(message);
1437 return new AuthenticatorException(message);
1440 private class GetAuthTokenByTypeAndFeaturesTask
1441 extends AmsTask implements AccountManagerCallback<Bundle> {
1442 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1443 final String[] features, Activity activityForPrompting,
1444 final Bundle addAccountOptions, final Bundle loginOptions,
1445 AccountManagerCallback<Bundle> callback, Handler handler) {
1446 super(activityForPrompting, handler, callback);
1447 if (accountType == null) throw new IllegalArgumentException("account type is null");
1448 mAccountType = accountType;
1449 mAuthTokenType = authTokenType;
1450 mFeatures = features;
1451 mAddAccountOptions = addAccountOptions;
1452 mLoginOptions = loginOptions;
1455 volatile AccountManagerFuture<Bundle> mFuture = null;
1456 final String mAccountType;
1457 final String mAuthTokenType;
1458 final String[] mFeatures;
1459 final Bundle mAddAccountOptions;
1460 final Bundle mLoginOptions;
1461 final AccountManagerCallback<Bundle> mMyCallback;
1462 private volatile int mNumAccounts = 0;
1464 public void doWork() throws RemoteException {
1465 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1466 new AccountManagerCallback<Account[]>() {
1467 public void run(AccountManagerFuture<Account[]> future) {
1470 accounts = future.getResult();
1471 } catch (OperationCanceledException e) {
1474 } catch (IOException e) {
1477 } catch (AuthenticatorException e) {
1482 mNumAccounts = accounts.length;
1484 if (accounts.length == 0) {
1485 if (mActivity != null) {
1486 // no accounts, add one now. pretend that the user directly
1487 // made this request
1488 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1489 mAddAccountOptions, mActivity, mMyCallback, mHandler);
1491 // send result since we can't prompt to add an account
1492 Bundle result = new Bundle();
1493 result.putString(KEY_ACCOUNT_NAME, null);
1494 result.putString(KEY_ACCOUNT_TYPE, null);
1495 result.putString(KEY_AUTHTOKEN, null);
1497 mResponse.onResult(result);
1498 } catch (RemoteException e) {
1499 // this will never happen
1503 } else if (accounts.length == 1) {
1504 // have a single account, return an authtoken for it
1505 if (mActivity == null) {
1506 mFuture = getAuthToken(accounts[0], mAuthTokenType,
1507 false /* notifyAuthFailure */, mMyCallback, mHandler);
1509 mFuture = getAuthToken(accounts[0],
1510 mAuthTokenType, mLoginOptions,
1511 mActivity, mMyCallback, mHandler);
1514 if (mActivity != null) {
1515 IAccountManagerResponse chooseResponse =
1516 new IAccountManagerResponse.Stub() {
1517 public void onResult(Bundle value) throws RemoteException {
1518 Account account = new Account(
1519 value.getString(KEY_ACCOUNT_NAME),
1520 value.getString(KEY_ACCOUNT_TYPE));
1521 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1522 mActivity, mMyCallback, mHandler);
1525 public void onError(int errorCode, String errorMessage)
1526 throws RemoteException {
1527 mResponse.onError(errorCode, errorMessage);
1530 // have many accounts, launch the chooser
1531 Intent intent = new Intent();
1532 intent.setClassName("android",
1533 "android.accounts.ChooseAccountActivity");
1534 intent.putExtra(KEY_ACCOUNTS, accounts);
1535 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
1536 new AccountManagerResponse(chooseResponse));
1537 mActivity.startActivity(intent);
1538 // the result will arrive via the IAccountManagerResponse
1540 // send result since we can't prompt to select an account
1541 Bundle result = new Bundle();
1542 result.putString(KEY_ACCOUNTS, null);
1544 mResponse.onResult(result);
1545 } catch (RemoteException e) {
1546 // this will never happen
1554 public void run(AccountManagerFuture<Bundle> future) {
1556 final Bundle result = future.getResult();
1557 if (mNumAccounts == 0) {
1558 final String accountName = result.getString(KEY_ACCOUNT_NAME);
1559 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
1560 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
1561 setException(new AuthenticatorException("account not in result"));
1564 final Account account = new Account(accountName, accountType);
1566 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
1567 mMyCallback, mHandler);
1571 } catch (OperationCanceledException e) {
1572 cancel(true /* mayInterruptIfRUnning */);
1573 } catch (IOException e) {
1575 } catch (AuthenticatorException e) {
1582 * This convenience helper combines the functionality of
1583 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1584 * {@link #addAccount}.
1586 * <p>This method gets a list of the accounts matching the
1587 * specified type and feature set; if there is exactly one, it is
1588 * used; if there are more than one, the user is prompted to pick one;
1589 * if there are none, the user is prompted to add one. Finally,
1590 * an auth token is acquired for the chosen account.
1592 * <p>This method may be called from any thread, but the returned
1593 * {@link AccountManagerFuture} must not be used on the main thread.
1595 * <p>This method requires the caller to hold the permission
1596 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1598 * @param accountType The account type required
1599 * (see {@link #getAccountsByType}), must not be null
1600 * @param authTokenType The desired auth token type
1601 * (see {@link #getAuthToken}), must not be null
1602 * @param features Required features for the account
1603 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1604 * @param activity The {@link Activity} context to use for launching new
1605 * sub-Activities to prompt to add an account, select an account,
1606 * and/or enter a password, as necessary; used only to call
1607 * startActivity(); should not be null
1608 * @param addAccountOptions Authenticator-specific options to use for
1609 * adding new accounts; may be null or empty
1610 * @param getAuthTokenOptions Authenticator-specific options to use for
1611 * getting auth tokens; may be null or empty
1612 * @param callback Callback to invoke when the request completes,
1613 * null for no callback
1614 * @param handler {@link Handler} identifying the callback thread,
1615 * null for the main thread
1616 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1617 * at least the following fields:
1619 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1620 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1621 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1624 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1626 * <li> {@link AuthenticatorException} if no authenticator was registered for
1627 * this account type or the authenticator failed to respond
1628 * <li> {@link OperationCanceledException} if the operation was canceled for
1629 * any reason, including the user canceling any operation
1630 * <li> {@link IOException} if the authenticator experienced an I/O problem
1631 * updating settings, usually because of network trouble
1634 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
1635 final String accountType, final String authTokenType, final String[] features,
1636 final Activity activity, final Bundle addAccountOptions,
1637 final Bundle getAuthTokenOptions,
1638 final AccountManagerCallback<Bundle> callback, final Handler handler) {
1639 if (accountType == null) throw new IllegalArgumentException("account type is null");
1640 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1641 final GetAuthTokenByTypeAndFeaturesTask task =
1642 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
1643 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
1648 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
1652 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1653 * so that it can read the updated list of accounts and send them to the listener
1654 * in mAccountsUpdatedListeners.
1656 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1657 public void onReceive(final Context context, final Intent intent) {
1658 final Account[] accounts = getAccounts();
1659 // send the result to the listeners
1660 synchronized (mAccountsUpdatedListeners) {
1661 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
1662 mAccountsUpdatedListeners.entrySet()) {
1663 postToHandler(entry.getValue(), entry.getKey(), accounts);
1670 * Adds an {@link OnAccountsUpdateListener} to this instance of the
1671 * {@link AccountManager}. This listener will be notified whenever the
1672 * list of accounts on the device changes.
1674 * <p>As long as this listener is present, the AccountManager instance
1675 * will not be garbage-collected, and neither will the {@link Context}
1676 * used to retrieve it, which may be a large Activity instance. To avoid
1677 * memory leaks, you must remove this listener before then. Normally
1678 * listeners are added in an Activity or Service's {@link Activity#onCreate}
1679 * and removed in {@link Activity#onDestroy}.
1681 * <p>It is safe to call this method from the main thread.
1683 * <p>No permission is required to call this method.
1685 * @param listener The listener to send notifications to
1686 * @param handler {@link Handler} identifying the thread to use
1687 * for notifications, null for the main thread
1688 * @param updateImmediately If true, the listener will be invoked
1689 * (on the handler thread) right away with the current account list
1690 * @throws IllegalArgumentException if listener is null
1691 * @throws IllegalStateException if listener was already added
1693 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
1694 Handler handler, boolean updateImmediately) {
1695 if (listener == null) {
1696 throw new IllegalArgumentException("the listener is null");
1698 synchronized (mAccountsUpdatedListeners) {
1699 if (mAccountsUpdatedListeners.containsKey(listener)) {
1700 throw new IllegalStateException("this listener is already added");
1702 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
1704 mAccountsUpdatedListeners.put(listener, handler);
1707 // Register a broadcast receiver to monitor account changes
1708 IntentFilter intentFilter = new IntentFilter();
1709 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
1710 // To recover from disk-full.
1711 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1712 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
1716 if (updateImmediately) {
1717 postToHandler(handler, listener, getAccounts());
1722 * Removes an {@link OnAccountsUpdateListener} previously registered with
1723 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
1724 * receive notifications of account changes.
1726 * <p>It is safe to call this method from the main thread.
1728 * <p>No permission is required to call this method.
1730 * @param listener The previously added listener to remove
1731 * @throws IllegalArgumentException if listener is null
1732 * @throws IllegalStateException if listener was not already added
1734 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
1735 if (listener == null) throw new IllegalArgumentException("listener is null");
1736 synchronized (mAccountsUpdatedListeners) {
1737 if (!mAccountsUpdatedListeners.containsKey(listener)) {
1738 Log.e(TAG, "Listener was not previously added");
1741 mAccountsUpdatedListeners.remove(listener);
1742 if (mAccountsUpdatedListeners.isEmpty()) {
1743 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);