AccountManager.java revision ffb46022b30dffdf1cc4cbd08d4bcbe51e1f8814
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17package android.accounts;
18
19import android.annotation.RequiresPermission;
20import android.annotation.Size;
21import android.app.Activity;
22import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.res.Resources;
28import android.database.SQLException;
29import android.os.Build;
30import android.os.Bundle;
31import android.os.Handler;
32import android.os.Looper;
33import android.os.Parcelable;
34import android.os.Process;
35import android.os.RemoteException;
36import android.os.UserHandle;
37import android.text.TextUtils;
38import android.util.Log;
39
40import com.android.internal.R;
41import com.google.android.collect.Maps;
42
43import java.io.IOException;
44import java.util.ArrayList;
45import java.util.HashMap;
46import java.util.Map;
47import java.util.concurrent.Callable;
48import java.util.concurrent.CancellationException;
49import java.util.concurrent.ExecutionException;
50import java.util.concurrent.FutureTask;
51import java.util.concurrent.TimeUnit;
52import java.util.concurrent.TimeoutException;
53
54import static android.Manifest.permission.GET_ACCOUNTS;
55
56/**
57 * This class provides access to a centralized registry of the user's
58 * online accounts.  The user enters credentials (username and password) once
59 * per account, granting applications access to online resources with
60 * "one-click" approval.
61 *
62 * <p>Different online services have different ways of handling accounts and
63 * authentication, so the account manager uses pluggable <em>authenticator</em>
64 * modules for different <em>account types</em>.  Authenticators (which may be
65 * written by third parties) handle the actual details of validating account
66 * credentials and storing account information.  For example, Google, Facebook,
67 * and Microsoft Exchange each have their own authenticator.
68 *
69 * <p>Many servers support some notion of an <em>authentication token</em>,
70 * which can be used to authenticate a request to the server without sending
71 * the user's actual password.  (Auth tokens are normally created with a
72 * separate request which does include the user's credentials.)  AccountManager
73 * can generate auth tokens for applications, so the application doesn't need to
74 * handle passwords directly.  Auth tokens are normally reusable and cached by
75 * AccountManager, but must be refreshed periodically.  It's the responsibility
76 * of applications to <em>invalidate</em> auth tokens when they stop working so
77 * the AccountManager knows it needs to regenerate them.
78 *
79 * <p>Applications accessing a server normally go through these steps:
80 *
81 * <ul>
82 * <li>Get an instance of AccountManager using {@link #get(Context)}.
83 *
84 * <li>List the available accounts using {@link #getAccountsByType} or
85 * {@link #getAccountsByTypeAndFeatures}.  Normally applications will only
86 * be interested in accounts with one particular <em>type</em>, which
87 * identifies the authenticator.  Account <em>features</em> are used to
88 * identify particular account subtypes and capabilities.  Both the account
89 * type and features are authenticator-specific strings, and must be known by
90 * the application in coordination with its preferred authenticators.
91 *
92 * <li>Select one or more of the available accounts, possibly by asking the
93 * user for their preference.  If no suitable accounts are available,
94 * {@link #addAccount} may be called to prompt the user to create an
95 * account of the appropriate type.
96 *
97 * <li><b>Important:</b> If the application is using a previously remembered
98 * account selection, it must make sure the account is still in the list
99 * of accounts returned by {@link #getAccountsByType}.  Requesting an auth token
100 * for an account no longer on the device results in an undefined failure.
101 *
102 * <li>Request an auth token for the selected account(s) using one of the
103 * {@link #getAuthToken} methods or related helpers.  Refer to the description
104 * of each method for exact usage and error handling details.
105 *
106 * <li>Make the request using the auth token.  The form of the auth token,
107 * the format of the request, and the protocol used are all specific to the
108 * service you are accessing.  The application may use whatever network and
109 * protocol libraries are useful.
110 *
111 * <li><b>Important:</b> If the request fails with an authentication error,
112 * it could be that a cached auth token is stale and no longer honored by
113 * the server.  The application must call {@link #invalidateAuthToken} to remove
114 * the token from the cache, otherwise requests will continue failing!  After
115 * invalidating the auth token, immediately go back to the "Request an auth
116 * token" step above.  If the process fails the second time, then it can be
117 * treated as a "genuine" authentication failure and the user notified or other
118 * appropriate actions taken.
119 * </ul>
120 *
121 * <p>Some AccountManager methods may need to interact with the user to
122 * prompt for credentials, present options, or ask the user to add an account.
123 * The caller may choose whether to allow AccountManager to directly launch the
124 * necessary user interface and wait for the user, or to return an Intent which
125 * the caller may use to launch the interface, or (in some cases) to install a
126 * notification which the user can select at any time to launch the interface.
127 * To have AccountManager launch the interface directly, the caller must supply
128 * the current foreground {@link Activity} context.
129 *
130 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
131 * {@link Handler} as parameters.  These methods return immediately and
132 * run asynchronously. If a callback is provided then
133 * {@link AccountManagerCallback#run} will be invoked on the Handler's
134 * thread when the request completes, successfully or not.
135 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
136 * on the {@link AccountManagerFuture} returned by the method (and also passed
137 * to the callback).  This method waits for the operation to complete (if
138 * necessary) and either returns the result or throws an exception if an error
139 * occurred during the operation.  To make the request synchronously, call
140 * {@link AccountManagerFuture#getResult()} immediately on receiving the
141 * future from the method; no callback need be supplied.
142 *
143 * <p>Requests which may block, including
144 * {@link AccountManagerFuture#getResult()}, must never be called on
145 * the application's main event thread.  These operations throw
146 * {@link IllegalStateException} if they are used on the main thread.
147 */
148public class AccountManager {
149    private static final String TAG = "AccountManager";
150
151    public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
152    public static final int ERROR_CODE_NETWORK_ERROR = 3;
153    public static final int ERROR_CODE_CANCELED = 4;
154    public static final int ERROR_CODE_INVALID_RESPONSE = 5;
155    public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
156    public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
157    public static final int ERROR_CODE_BAD_REQUEST = 8;
158    public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
159
160    /** @hide */
161    public static final int ERROR_CODE_USER_RESTRICTED = 100;
162    /** @hide */
163    public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
164
165    /**
166     * Bundle key used for the {@link String} account name in results
167     * from methods which return information about a particular account.
168     */
169    public static final String KEY_ACCOUNT_NAME = "authAccount";
170
171    /**
172     * Bundle key used for the {@link String} account type in results
173     * from methods which return information about a particular account.
174     */
175    public static final String KEY_ACCOUNT_TYPE = "accountType";
176
177    /**
178     * Bundle key used for the auth token value in results
179     * from {@link #getAuthToken} and friends.
180     */
181    public static final String KEY_AUTHTOKEN = "authtoken";
182
183    /**
184     * Bundle key used for an {@link Intent} in results from methods that
185     * may require the caller to interact with the user.  The Intent can
186     * be used to start the corresponding user interface activity.
187     */
188    public static final String KEY_INTENT = "intent";
189
190    /**
191     * Bundle key used to supply the password directly in options to
192     * {@link #confirmCredentials}, rather than prompting the user with
193     * the standard password prompt.
194     */
195    public static final String KEY_PASSWORD = "password";
196
197    public static final String KEY_ACCOUNTS = "accounts";
198
199    public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
200    public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
201    public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
202    public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
203    public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
204    public static final String KEY_BOOLEAN_RESULT = "booleanResult";
205    public static final String KEY_ERROR_CODE = "errorCode";
206    public static final String KEY_ERROR_MESSAGE = "errorMessage";
207    public static final String KEY_USERDATA = "userdata";
208
209    /**
210     * Bundle key used to supply the last time the credentials of the account
211     * were authenticated successfully. Time is specified in milliseconds since
212     * epoch.
213     */
214    public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
215
216    /**
217     * Authenticators using 'customTokens' option will also get the UID of the
218     * caller
219     */
220    public static final String KEY_CALLER_UID = "callerUid";
221    public static final String KEY_CALLER_PID = "callerPid";
222
223    /**
224     * The Android package of the caller will be set in the options bundle by the
225     * {@link AccountManager} and will be passed to the AccountManagerService and
226     * to the AccountAuthenticators. The uid of the caller will be known by the
227     * AccountManagerService as well as the AccountAuthenticators so they will be able to
228     * verify that the package is consistent with the uid (a uid might be shared by many
229     * packages).
230     */
231    public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
232
233    /**
234     * Boolean, if set and 'customTokens' the authenticator is responsible for
235     * notifications.
236     * @hide
237     */
238    public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
239
240    public static final String ACTION_AUTHENTICATOR_INTENT =
241            "android.accounts.AccountAuthenticator";
242    public static final String AUTHENTICATOR_META_DATA_NAME =
243            "android.accounts.AccountAuthenticator";
244    public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
245
246    private final Context mContext;
247    private final IAccountManager mService;
248    private final Handler mMainHandler;
249
250    /**
251     * Action sent as a broadcast Intent by the AccountsService
252     * when accounts are added, accounts are removed, or an
253     * account's credentials (saved password, etc) are changed.
254     *
255     * @see #addOnAccountsUpdatedListener
256     */
257    public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
258        "android.accounts.LOGIN_ACCOUNTS_CHANGED";
259
260    /**
261     * @hide
262     */
263    public AccountManager(Context context, IAccountManager service) {
264        mContext = context;
265        mService = service;
266        mMainHandler = new Handler(mContext.getMainLooper());
267    }
268
269    /**
270     * @hide used for testing only
271     */
272    public AccountManager(Context context, IAccountManager service, Handler handler) {
273        mContext = context;
274        mService = service;
275        mMainHandler = handler;
276    }
277
278    /**
279     * @hide for internal use only
280     */
281    public static Bundle sanitizeResult(Bundle result) {
282        if (result != null) {
283            if (result.containsKey(KEY_AUTHTOKEN)
284                    && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
285                final Bundle newResult = new Bundle(result);
286                newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
287                return newResult;
288            }
289        }
290        return result;
291    }
292
293    /**
294     * Gets an AccountManager instance associated with a Context.
295     * The {@link Context} will be used as long as the AccountManager is
296     * active, so make sure to use a {@link Context} whose lifetime is
297     * commensurate with any listeners registered to
298     * {@link #addOnAccountsUpdatedListener} or similar methods.
299     *
300     * <p>It is safe to call this method from the main thread.
301     *
302     * <p>No permission is required to call this method.
303     *
304     * @param context The {@link Context} to use when necessary
305     * @return An {@link AccountManager} instance
306     */
307    public static AccountManager get(Context context) {
308        if (context == null) throw new IllegalArgumentException("context is null");
309        return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
310    }
311
312    /**
313     * Gets the saved password associated with the account.
314     * This is intended for authenticators and related code; applications
315     * should get an auth token instead.
316     *
317     * <p>It is safe to call this method from the main thread.
318     *
319     * <p>This method requires the caller to have a signature match with the
320     * authenticator that owns the specified account.
321     *
322     * @param account The account to query for a password. Must not be {@code null}.
323     * @return The account's password, null if none or if the account doesn't exist
324     */
325    public String getPassword(final Account account) {
326        if (account == null) throw new IllegalArgumentException("account is null");
327        try {
328            return mService.getPassword(account);
329        } catch (RemoteException e) {
330            // will never happen
331            throw new RuntimeException(e);
332        }
333    }
334
335    /**
336     * Gets the user data named by "key" associated with the account.
337     * This is intended for authenticators and related code to store
338     * arbitrary metadata along with accounts.  The meaning of the keys
339     * and values is up to the authenticator for the account.
340     *
341     * <p>It is safe to call this method from the main thread.
342     *
343     * <p>This method requires the caller to have a signature match with the
344     * authenticator that owns the specified account.
345     *
346     * @param account The account to query for user data
347     * @return The user data, null if the account or key doesn't exist
348     */
349    public String getUserData(final Account account, final String key) {
350        if (account == null) throw new IllegalArgumentException("account is null");
351        if (key == null) throw new IllegalArgumentException("key is null");
352        try {
353            return mService.getUserData(account, key);
354        } catch (RemoteException e) {
355            // will never happen
356            throw new RuntimeException(e);
357        }
358    }
359
360    /**
361     * Lists the currently registered authenticators.
362     *
363     * <p>It is safe to call this method from the main thread.
364     *
365     * <p>No permission is required to call this method.
366     *
367     * @return An array of {@link AuthenticatorDescription} for every
368     *     authenticator known to the AccountManager service.  Empty (never
369     *     null) if no authenticators are known.
370     */
371    public AuthenticatorDescription[] getAuthenticatorTypes() {
372        try {
373            return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
374        } catch (RemoteException e) {
375            // will never happen
376            throw new RuntimeException(e);
377        }
378    }
379
380    /**
381     * @hide
382     * Lists the currently registered authenticators for a given user id.
383     *
384     * <p>It is safe to call this method from the main thread.
385     *
386     * <p>The caller has to be in the same user or have the permission
387     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
388     *
389     * @return An array of {@link AuthenticatorDescription} for every
390     *     authenticator known to the AccountManager service.  Empty (never
391     *     null) if no authenticators are known.
392     */
393    public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
394        try {
395            return mService.getAuthenticatorTypes(userId);
396        } catch (RemoteException e) {
397            // will never happen
398            throw new RuntimeException(e);
399        }
400    }
401
402    /**
403     * Lists all accounts of any type registered on the device.
404     * Equivalent to getAccountsByType(null).
405     *
406     * <p>It is safe to call this method from the main thread.
407     *
408     * <p>This method requires the caller to hold the permission
409     * {@link android.Manifest.permission#GET_ACCOUNTS}.
410     *
411     * @return An array of {@link Account}, one for each account.  Empty
412     *     (never null) if no accounts have been added.
413     */
414    @RequiresPermission(GET_ACCOUNTS)
415    public Account[] getAccounts() {
416        try {
417            return mService.getAccounts(null);
418        } catch (RemoteException e) {
419            // won't ever happen
420            throw new RuntimeException(e);
421        }
422    }
423
424    /**
425     * @hide
426     * Lists all accounts of any type registered on the device for a given
427     * user id. Equivalent to getAccountsByType(null).
428     *
429     * <p>It is safe to call this method from the main thread.
430     *
431     * <p>This method requires the caller to hold the permission
432     * {@link android.Manifest.permission#GET_ACCOUNTS}.
433     *
434     * @return An array of {@link Account}, one for each account.  Empty
435     *     (never null) if no accounts have been added.
436     */
437    @RequiresPermission(GET_ACCOUNTS)
438    public Account[] getAccountsAsUser(int userId) {
439        try {
440            return mService.getAccountsAsUser(null, userId);
441        } catch (RemoteException e) {
442            // won't ever happen
443            throw new RuntimeException(e);
444        }
445    }
446
447    /**
448     * @hide
449     * For use by internal activities. Returns the list of accounts that the calling package
450     * is authorized to use, particularly for shared accounts.
451     * @param packageName package name of the calling app.
452     * @param uid the uid of the calling app.
453     * @return the accounts that are available to this package and user.
454     */
455    public Account[] getAccountsForPackage(String packageName, int uid) {
456        try {
457            return mService.getAccountsForPackage(packageName, uid);
458        } catch (RemoteException re) {
459            // possible security exception
460            throw new RuntimeException(re);
461        }
462    }
463
464    /**
465     * Returns the accounts visible to the specified package, in an environment where some apps
466     * are not authorized to view all accounts. This method can only be called by system apps.
467     * @param type The type of accounts to return, null to retrieve all accounts
468     * @param packageName The package name of the app for which the accounts are to be returned
469     * @return An array of {@link Account}, one per matching account.  Empty
470     *     (never null) if no accounts of the specified type have been added.
471     */
472    public Account[] getAccountsByTypeForPackage(String type, String packageName) {
473        try {
474            return mService.getAccountsByTypeForPackage(type, packageName);
475        } catch (RemoteException re) {
476            // possible security exception
477            throw new RuntimeException(re);
478        }
479    }
480
481    /**
482     * Lists all accounts of a particular type.  The account type is a
483     * string token corresponding to the authenticator and useful domain
484     * of the account.  For example, there are types corresponding to Google
485     * and Facebook.  The exact string token to use will be published somewhere
486     * associated with the authenticator in question.
487     *
488     * <p>It is safe to call this method from the main thread.
489     *
490     * <p>This method requires the caller to hold the permission
491     * {@link android.Manifest.permission#GET_ACCOUNTS}.
492     *
493     * @param type The type of accounts to return, null to retrieve all accounts
494     * @return An array of {@link Account}, one per matching account.  Empty
495     *     (never null) if no accounts of the specified type have been added.
496     */
497    @RequiresPermission(GET_ACCOUNTS)
498    public Account[] getAccountsByType(String type) {
499        return getAccountsByTypeAsUser(type, Process.myUserHandle());
500    }
501
502    /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
503    public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
504        try {
505            return mService.getAccountsAsUser(type, userHandle.getIdentifier());
506        } catch (RemoteException e) {
507            // won't ever happen
508            throw new RuntimeException(e);
509        }
510    }
511
512    /**
513     * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
514     * for an account.
515     * <p>
516     * This is only meant to be used by system activities and is not in the SDK.
517     * @param account The account whose permissions are being modified
518     * @param authTokenType The type of token whose permissions are being modified
519     * @param uid The uid that identifies the app which is being granted or revoked permission.
520     * @param value true is permission is being granted, false for revoked
521     * @hide
522     */
523    public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
524        try {
525            mService.updateAppPermission(account, authTokenType, uid, value);
526        } catch (RemoteException e) {
527            // won't ever happen
528            throw new RuntimeException(e);
529        }
530    }
531
532    /**
533     * Get the user-friendly label associated with an authenticator's auth token.
534     * @param accountType the type of the authenticator. must not be null.
535     * @param authTokenType the token type. must not be null.
536     * @param callback callback to invoke when the result is available. may be null.
537     * @param handler the handler on which to invoke the callback, or null for the main thread
538     * @return a future containing the label string
539     * @hide
540     */
541    public AccountManagerFuture<String> getAuthTokenLabel(
542            final String accountType, final String authTokenType,
543            AccountManagerCallback<String> callback, Handler handler) {
544        if (accountType == null) throw new IllegalArgumentException("accountType is null");
545        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
546        return new Future2Task<String>(handler, callback) {
547            public void doWork() throws RemoteException {
548                mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
549            }
550
551            @Override
552            public String bundleToResult(Bundle bundle) throws AuthenticatorException {
553                if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
554                    throw new AuthenticatorException("no result in response");
555                }
556                return bundle.getString(KEY_AUTH_TOKEN_LABEL);
557            }
558        }.start();
559    }
560
561    /**
562     * Finds out whether a particular account has all the specified features.
563     * Account features are authenticator-specific string tokens identifying
564     * boolean account properties.  For example, features are used to tell
565     * whether Google accounts have a particular service (such as Google
566     * Calendar or Google Talk) enabled.  The feature names and their meanings
567     * are published somewhere associated with the authenticator in question.
568     *
569     * <p>This method may be called from any thread, but the returned
570     * {@link AccountManagerFuture} must not be used on the main thread.
571     *
572     * <p>This method requires the caller to hold the permission
573     * {@link android.Manifest.permission#GET_ACCOUNTS}.
574     *
575     * @param account The {@link Account} to test
576     * @param features An array of the account features to check
577     * @param callback Callback to invoke when the request completes,
578     *     null for no callback
579     * @param handler {@link Handler} identifying the callback thread,
580     *     null for the main thread
581     * @return An {@link AccountManagerFuture} which resolves to a Boolean,
582     * true if the account exists and has all of the specified features.
583     */
584    @RequiresPermission(GET_ACCOUNTS)
585    public AccountManagerFuture<Boolean> hasFeatures(final Account account,
586            final String[] features,
587            AccountManagerCallback<Boolean> callback, Handler handler) {
588        if (account == null) throw new IllegalArgumentException("account is null");
589        if (features == null) throw new IllegalArgumentException("features is null");
590        return new Future2Task<Boolean>(handler, callback) {
591            public void doWork() throws RemoteException {
592                mService.hasFeatures(mResponse, account, features);
593            }
594            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
595                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
596                    throw new AuthenticatorException("no result in response");
597                }
598                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
599            }
600        }.start();
601    }
602
603    /**
604     * Lists all accounts of a type which have certain features.  The account
605     * type identifies the authenticator (see {@link #getAccountsByType}).
606     * Account features are authenticator-specific string tokens identifying
607     * boolean account properties (see {@link #hasFeatures}).
608     *
609     * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
610     * which may contact the server or do other work to check account features,
611     * so the method returns an {@link AccountManagerFuture}.
612     *
613     * <p>This method may be called from any thread, but the returned
614     * {@link AccountManagerFuture} must not be used on the main thread.
615     *
616     * <p>This method requires the caller to hold the permission
617     * {@link android.Manifest.permission#GET_ACCOUNTS}.
618     *
619     * @param type The type of accounts to return, must not be null
620     * @param features An array of the account features to require,
621     *     may be null or empty
622     * @param callback Callback to invoke when the request completes,
623     *     null for no callback
624     * @param handler {@link Handler} identifying the callback thread,
625     *     null for the main thread
626     * @return An {@link AccountManagerFuture} which resolves to an array of
627     *     {@link Account}, one per account of the specified type which
628     *     matches the requested features.
629     */
630    @RequiresPermission(GET_ACCOUNTS)
631    public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
632            final String type, final String[] features,
633            AccountManagerCallback<Account[]> callback, Handler handler) {
634        if (type == null) throw new IllegalArgumentException("type is null");
635        return new Future2Task<Account[]>(handler, callback) {
636            public void doWork() throws RemoteException {
637                mService.getAccountsByFeatures(mResponse, type, features);
638            }
639            public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
640                if (!bundle.containsKey(KEY_ACCOUNTS)) {
641                    throw new AuthenticatorException("no result in response");
642                }
643                final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
644                Account[] descs = new Account[parcelables.length];
645                for (int i = 0; i < parcelables.length; i++) {
646                    descs[i] = (Account) parcelables[i];
647                }
648                return descs;
649            }
650        }.start();
651    }
652
653    /**
654     * Adds an account directly to the AccountManager.  Normally used by sign-up
655     * wizards associated with authenticators, not directly by applications.
656     *
657     * <p>It is safe to call this method from the main thread.
658     * <p>This method requires the caller to have a signature match with the
659     * authenticator that owns the specified account.
660     *
661     * @param account The {@link Account} to add
662     * @param password The password to associate with the account, null for none
663     * @param userdata String values to use for the account's userdata, null for none
664     * @return True if the account was successfully added, false if the account
665     *     already exists, the account is null, or another error occurs.
666     */
667    public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
668        if (account == null) throw new IllegalArgumentException("account is null");
669        try {
670            return mService.addAccountExplicitly(account, password, userdata);
671        } catch (RemoteException e) {
672            // won't ever happen
673            throw new RuntimeException(e);
674        }
675    }
676
677    /**
678     * Notifies the system that the account has just been authenticated. This
679     * information may be used by other applications to verify the account. This
680     * should be called only when the user has entered correct credentials for
681     * the account.
682     * <p>
683     * It is not safe to call this method from the main thread. As such, call it
684     * from another thread.
685     * <p>This method requires the caller to have a signature match with the
686     * authenticator that owns the specified account.
687     *
688     * @param account The {@link Account} to be updated.
689     * @return boolean {@code true} if the authentication of the account has been successfully
690     *         acknowledged. Otherwise {@code false}.
691     */
692    public boolean notifyAccountAuthenticated(Account account) {
693        if (account == null)
694            throw new IllegalArgumentException("account is null");
695        try {
696            return mService.accountAuthenticated(account);
697        } catch (RemoteException e) {
698            throw new RuntimeException(e);
699        }
700    }
701
702    /**
703     * Rename the specified {@link Account}.  This is equivalent to removing
704     * the existing account and adding a new renamed account with the old
705     * account's user data.
706     *
707     * <p>It is safe to call this method from the main thread.
708     *
709     * <p>This method requires the caller to have a signature match with the
710     * authenticator that manages the specified account.
711     *
712     * @param account The {@link Account} to rename
713     * @param newName String name to be associated with the account.
714     * @param callback Callback to invoke when the request completes, null for
715     *     no callback
716     * @param handler {@link Handler} identifying the callback thread, null for
717     *     the main thread
718     * @return An {@link AccountManagerFuture} which resolves to the Account
719     *     after the name change. If successful the account's name will be the
720     *     specified new name.
721     */
722    public AccountManagerFuture<Account> renameAccount(
723            final Account account,
724            @Size(min = 1) final String newName,
725            AccountManagerCallback<Account> callback,
726            Handler handler) {
727        if (account == null) throw new IllegalArgumentException("account is null.");
728        if (TextUtils.isEmpty(newName)) {
729              throw new IllegalArgumentException("newName is empty or null.");
730        }
731        return new Future2Task<Account>(handler, callback) {
732            @Override
733            public void doWork() throws RemoteException {
734                mService.renameAccount(mResponse, account, newName);
735            }
736            @Override
737            public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
738                String name = bundle.getString(KEY_ACCOUNT_NAME);
739                String type = bundle.getString(KEY_ACCOUNT_TYPE);
740                return new Account(name, type);
741            }
742        }.start();
743    }
744
745    /**
746     * Gets the previous name associated with the account or {@code null}, if
747     * none. This is intended so that clients of {@link
748     * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
749     * authenticator has renamed an account.
750     *
751     * <p>It is safe to call this method from the main thread.
752     *
753     * @param account The account to query for a previous name.
754     * @return The account's previous name, null if the account has never been
755     *         renamed.
756     */
757    public String getPreviousName(final Account account) {
758        if (account == null) throw new IllegalArgumentException("account is null");
759        try {
760            return mService.getPreviousName(account);
761        } catch (RemoteException e) {
762            // will never happen
763            throw new RuntimeException(e);
764        }
765    }
766
767    /**
768     * Removes an account from the AccountManager.  Does nothing if the account
769     * does not exist.  Does not delete the account from the server.
770     * The authenticator may have its own policies preventing account
771     * deletion, in which case the account will not be deleted.
772     *
773     * <p>This method requires the caller to have a signature match with the
774     * authenticator that manages the specified account.
775     *
776     * @param account The {@link Account} to remove
777     * @param callback Callback to invoke when the request completes,
778     *     null for no callback
779     * @param handler {@link Handler} identifying the callback thread,
780     *     null for the main thread
781     * @return An {@link AccountManagerFuture} which resolves to a Boolean,
782     *     true if the account has been successfully removed
783     * @deprecated use
784     *     {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
785     *     instead
786     */
787    @Deprecated
788    public AccountManagerFuture<Boolean> removeAccount(final Account account,
789            AccountManagerCallback<Boolean> callback, Handler handler) {
790        if (account == null) throw new IllegalArgumentException("account is null");
791        return new Future2Task<Boolean>(handler, callback) {
792            @Override
793            public void doWork() throws RemoteException {
794                mService.removeAccount(mResponse, account, false);
795            }
796            @Override
797            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
798                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
799                    throw new AuthenticatorException("no result in response");
800                }
801                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
802            }
803        }.start();
804    }
805
806    /**
807     * Removes an account from the AccountManager. Does nothing if the account
808     * does not exist.  Does not delete the account from the server.
809     * The authenticator may have its own policies preventing account
810     * deletion, in which case the account will not be deleted.
811     *
812     * <p>This method may be called from any thread, but the returned
813     * {@link AccountManagerFuture} must not be used on the main thread.
814     *
815     * <p>This method requires the caller to have a signature match with the
816     * authenticator that manages the specified account.
817     *
818     * @param account The {@link Account} to remove
819     * @param activity The {@link Activity} context to use for launching a new
820     *     authenticator-defined sub-Activity to prompt the user to delete an
821     *     account; used only to call startActivity(); if null, the prompt
822     *     will not be launched directly, but the {@link Intent} may be
823     *     returned to the caller instead
824     * @param callback Callback to invoke when the request completes,
825     *     null for no callback
826     * @param handler {@link Handler} identifying the callback thread,
827     *     null for the main thread
828     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
829     *     {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
830     *     was removed or if active. If no activity was specified, the returned
831     *     Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
832     *     needed to launch the actual account removal process, if authenticator
833     *     needs the activity launch. If an error occurred,
834     *     {@link AccountManagerFuture#getResult()} throws:
835     * <ul>
836     * <li> {@link AuthenticatorException} if no authenticator was registered for
837     *      this account type or the authenticator failed to respond
838     * <li> {@link OperationCanceledException} if the operation was canceled for
839     *      any reason, including the user canceling the creation process or
840     *      adding accounts (of this type) has been disabled by policy
841     * </ul>
842     */
843    public AccountManagerFuture<Bundle> removeAccount(final Account account,
844            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
845        if (account == null) throw new IllegalArgumentException("account is null");
846        return new AmsTask(activity, handler, callback) {
847            @Override
848            public void doWork() throws RemoteException {
849                mService.removeAccount(mResponse, account, activity != null);
850            }
851        }.start();
852    }
853
854    /**
855     * @see #removeAccount(Account, AccountManagerCallback, Handler)
856     * @hide
857     * @deprecated use
858     *     {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
859     *     instead
860     */
861    @Deprecated
862    public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
863            AccountManagerCallback<Boolean> callback, Handler handler,
864            final UserHandle userHandle) {
865        if (account == null) throw new IllegalArgumentException("account is null");
866        if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
867        return new Future2Task<Boolean>(handler, callback) {
868            @Override
869            public void doWork() throws RemoteException {
870                mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
871            }
872            @Override
873            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
874                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
875                    throw new AuthenticatorException("no result in response");
876                }
877                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
878            }
879        }.start();
880    }
881
882    /**
883     * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
884     * @hide
885     */
886    public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
887            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
888            final UserHandle userHandle) {
889        if (account == null)
890            throw new IllegalArgumentException("account is null");
891        if (userHandle == null)
892            throw new IllegalArgumentException("userHandle is null");
893        return new AmsTask(activity, handler, callback) {
894            public void doWork() throws RemoteException {
895                mService.removeAccountAsUser(mResponse, account, activity != null,
896                        userHandle.getIdentifier());
897            }
898        }.start();
899    }
900
901    /**
902     * Removes an account directly. Normally used by authenticators, not
903     * directly by applications. Does not delete the account from the server.
904     * The authenticator may have its own policies preventing account deletion,
905     * in which case the account will not be deleted.
906     * <p>
907     * It is safe to call this method from the main thread.
908     * <p>This method requires the caller to have a signature match with the
909     * authenticator that manages the specified account.
910     *
911     * @param account The {@link Account} to delete.
912     * @return True if the account was successfully deleted, false if the
913     *         account did not exist, the account is null, or another error
914     *         occurs.
915     */
916    public boolean removeAccountExplicitly(Account account) {
917        if (account == null) throw new IllegalArgumentException("account is null");
918        try {
919            return mService.removeAccountExplicitly(account);
920        } catch (RemoteException e) {
921            // won't ever happen
922            throw new RuntimeException(e);
923        }
924    }
925
926    /**
927     * Removes an auth token from the AccountManager's cache.  Does nothing if
928     * the auth token is not currently in the cache.  Applications must call this
929     * method when the auth token is found to have expired or otherwise become
930     * invalid for authenticating requests.  The AccountManager does not validate
931     * or expire cached auth tokens otherwise.
932     *
933     * <p>It is safe to call this method from the main thread.
934     *
935     * @param accountType The account type of the auth token to invalidate, must not be null
936     * @param authToken The auth token to invalidate, may be null
937     */
938    public void invalidateAuthToken(final String accountType, final String authToken) {
939        if (accountType == null) throw new IllegalArgumentException("accountType is null");
940        try {
941            if (authToken != null) {
942                mService.invalidateAuthToken(accountType, authToken);
943            }
944        } catch (RemoteException e) {
945            // won't ever happen
946            throw new RuntimeException(e);
947        }
948    }
949
950    /**
951     * Gets an auth token from the AccountManager's cache.  If no auth
952     * token is cached for this account, null will be returned -- a new
953     * auth token will not be generated, and the server will not be contacted.
954     * Intended for use by the authenticator, not directly by applications.
955     *
956     * <p>It is safe to call this method from the main thread.
957     *
958     * <p>This method requires the caller to have a signature match with the
959     * authenticator that manages the specified account.
960     *
961     * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
962     * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
963     * @return The cached auth token for this account and type, or null if
964     *     no auth token is cached or the account does not exist.
965     * @see #getAuthToken
966     */
967    public String peekAuthToken(final Account account, final String authTokenType) {
968        if (account == null) throw new IllegalArgumentException("account is null");
969        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
970        try {
971            return mService.peekAuthToken(account, authTokenType);
972        } catch (RemoteException e) {
973            // won't ever happen
974            throw new RuntimeException(e);
975        }
976    }
977
978    /**
979     * Sets or forgets a saved password.  This modifies the local copy of the
980     * password used to automatically authenticate the user; it does
981     * not change the user's account password on the server.  Intended for use
982     * by the authenticator, not directly by applications.
983     *
984     * <p>It is safe to call this method from the main thread.
985     *
986     * <p>This method requires the caller to have a signature match with the
987     * authenticator that manages the specified account.
988     *
989     * @param account The account whose password is to be set. Cannot be {@code null}.
990     * @param password The password to set, null to clear the password
991     */
992    public void setPassword(final Account account, final String password) {
993        if (account == null) throw new IllegalArgumentException("account is null");
994        try {
995            mService.setPassword(account, password);
996        } catch (RemoteException e) {
997            // won't ever happen
998            throw new RuntimeException(e);
999        }
1000    }
1001
1002    /**
1003     * Forgets a saved password.  This erases the local copy of the password;
1004     * it does not change the user's account password on the server.
1005     * Has the same effect as setPassword(account, null) but requires fewer
1006     * permissions, and may be used by applications or management interfaces
1007     * to "sign out" from an account.
1008     *
1009     * <p>This method only successfully clear the account's password when the
1010     * caller has the same signature as the authenticator that owns the
1011     * specified account. Otherwise, this method will silently fail.
1012     *
1013     * <p>It is safe to call this method from the main thread.
1014     *
1015     * @param account The account whose password to clear
1016     */
1017    public void clearPassword(final Account account) {
1018        if (account == null) throw new IllegalArgumentException("account is null");
1019        try {
1020            mService.clearPassword(account);
1021        } catch (RemoteException e) {
1022            // won't ever happen
1023            throw new RuntimeException(e);
1024        }
1025    }
1026
1027    /**
1028     * Sets one userdata key for an account.  Intended by use for the
1029     * authenticator to stash state for itself, not directly by applications.
1030     * The meaning of the keys and values is up to the authenticator.
1031     *
1032     * <p>It is safe to call this method from the main thread.
1033     *
1034     * <p>This method requires the caller to have a signature match with the
1035     * authenticator that manages the specified account.
1036     *
1037     * @param account Account whose user data is to be set. Must not be {@code null}.
1038     * @param key String user data key to set.  Must not be null
1039     * @param value String value to set, {@code null} to clear this user data key
1040     */
1041    public void setUserData(final Account account, final String key, final String value) {
1042        if (account == null) throw new IllegalArgumentException("account is null");
1043        if (key == null) throw new IllegalArgumentException("key is null");
1044        try {
1045            mService.setUserData(account, key, value);
1046        } catch (RemoteException e) {
1047            // won't ever happen
1048            throw new RuntimeException(e);
1049        }
1050    }
1051
1052    /**
1053     * Adds an auth token to the AccountManager cache for an account.
1054     * If the account does not exist then this call has no effect.
1055     * Replaces any previous auth token for this account and auth token type.
1056     * Intended for use by the authenticator, not directly by applications.
1057     *
1058     * <p>It is safe to call this method from the main thread.
1059     *
1060     * <p>This method requires the caller to have a signature match with the
1061     * authenticator that manages the specified account.
1062     *
1063     * @param account The account to set an auth token for
1064     * @param authTokenType The type of the auth token, see {#getAuthToken}
1065     * @param authToken The auth token to add to the cache
1066     */
1067    public void setAuthToken(Account account, final String authTokenType, final String authToken) {
1068        if (account == null) throw new IllegalArgumentException("account is null");
1069        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1070        try {
1071            mService.setAuthToken(account, authTokenType, authToken);
1072        } catch (RemoteException e) {
1073            // won't ever happen
1074            throw new RuntimeException(e);
1075        }
1076    }
1077
1078    /**
1079     * This convenience helper synchronously gets an auth token with
1080     * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1081     *
1082     * <p>This method may block while a network request completes, and must
1083     * never be made from the main thread.
1084     *
1085     * @param account The account to fetch an auth token for
1086     * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
1087     * @param notifyAuthFailure If true, display a notification and return null
1088     *     if authentication fails; if false, prompt and wait for the user to
1089     *     re-enter correct credentials before returning
1090     * @return An auth token of the specified type for this account, or null
1091     *     if authentication fails or none can be fetched.
1092     * @throws AuthenticatorException if the authenticator failed to respond
1093     * @throws OperationCanceledException if the request was canceled for any
1094     *     reason, including the user canceling a credential request
1095     * @throws java.io.IOException if the authenticator experienced an I/O problem
1096     *     creating a new auth token, usually because of network trouble
1097     */
1098    public String blockingGetAuthToken(Account account, String authTokenType,
1099            boolean notifyAuthFailure)
1100            throws OperationCanceledException, IOException, AuthenticatorException {
1101        if (account == null) throw new IllegalArgumentException("account is null");
1102        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1103        Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1104                null /* handler */).getResult();
1105        if (bundle == null) {
1106            // This should never happen, but it does, occasionally. If it does return null to
1107            // signify that we were not able to get the authtoken.
1108            // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1109            // returned
1110            Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1111                    + account + ", authTokenType " + authTokenType);
1112            return null;
1113        }
1114        return bundle.getString(KEY_AUTHTOKEN);
1115    }
1116
1117    /**
1118     * Gets an auth token of the specified type for a particular account,
1119     * prompting the user for credentials if necessary.  This method is
1120     * intended for applications running in the foreground where it makes
1121     * sense to ask the user directly for a password.
1122     *
1123     * <p>If a previously generated auth token is cached for this account and
1124     * type, then it is returned.  Otherwise, if a saved password is
1125     * available, it is sent to the server to generate a new auth token.
1126     * Otherwise, the user is prompted to enter a password.
1127     *
1128     * <p>Some authenticators have auth token <em>types</em>, whose value
1129     * is authenticator-dependent.  Some services use different token types to
1130     * access different functionality -- for example, Google uses different auth
1131     * tokens to access Gmail and Google Calendar for the same account.
1132     *
1133     * <p>This method may be called from any thread, but the returned
1134     * {@link AccountManagerFuture} must not be used on the main thread.
1135     *
1136     * @param account The account to fetch an auth token for
1137     * @param authTokenType The auth token type, an authenticator-dependent
1138     *     string token, must not be null
1139     * @param options Authenticator-specific options for the request,
1140     *     may be null or empty
1141     * @param activity The {@link Activity} context to use for launching a new
1142     *     authenticator-defined sub-Activity to prompt the user for a password
1143     *     if necessary; used only to call startActivity(); must not be null.
1144     * @param callback Callback to invoke when the request completes,
1145     *     null for no callback
1146     * @param handler {@link Handler} identifying the callback thread,
1147     *     null for the main thread
1148     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1149     *     at least the following fields:
1150     * <ul>
1151     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1152     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1153     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1154     * </ul>
1155     *
1156     * (Other authenticator-specific values may be returned.)  If an auth token
1157     * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1158     * <ul>
1159     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1160     * <li> {@link OperationCanceledException} if the operation is canceled for
1161     *      any reason, incluidng the user canceling a credential request
1162     * <li> {@link IOException} if the authenticator experienced an I/O problem
1163     *      creating a new auth token, usually because of network trouble
1164     * </ul>
1165     * If the account is no longer present on the device, the return value is
1166     * authenticator-dependent.  The caller should verify the validity of the
1167     * account before requesting an auth token.
1168     */
1169    public AccountManagerFuture<Bundle> getAuthToken(
1170            final Account account, final String authTokenType, final Bundle options,
1171            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
1172        if (account == null) throw new IllegalArgumentException("account is null");
1173        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1174        final Bundle optionsIn = new Bundle();
1175        if (options != null) {
1176            optionsIn.putAll(options);
1177        }
1178        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1179        return new AmsTask(activity, handler, callback) {
1180            public void doWork() throws RemoteException {
1181                mService.getAuthToken(mResponse, account, authTokenType,
1182                        false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
1183                        optionsIn);
1184            }
1185        }.start();
1186    }
1187
1188    /**
1189     * Gets an auth token of the specified type for a particular account,
1190     * optionally raising a notification if the user must enter credentials.
1191     * This method is intended for background tasks and services where the
1192     * user should not be immediately interrupted with a password prompt.
1193     *
1194     * <p>If a previously generated auth token is cached for this account and
1195     * type, then it is returned.  Otherwise, if a saved password is
1196     * available, it is sent to the server to generate a new auth token.
1197     * Otherwise, an {@link Intent} is returned which, when started, will
1198     * prompt the user for a password.  If the notifyAuthFailure parameter is
1199     * set, a status bar notification is also created with the same Intent,
1200     * alerting the user that they need to enter a password at some point.
1201     *
1202     * <p>In that case, you may need to wait until the user responds, which
1203     * could take hours or days or forever.  When the user does respond and
1204     * supply a new password, the account manager will broadcast the
1205     * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1206     * use to try again.
1207     *
1208     * <p>If notifyAuthFailure is not set, it is the application's
1209     * responsibility to launch the returned Intent at some point.
1210     * Either way, the result from this call will not wait for user action.
1211     *
1212     * <p>Some authenticators have auth token <em>types</em>, whose value
1213     * is authenticator-dependent.  Some services use different token types to
1214     * access different functionality -- for example, Google uses different auth
1215     * tokens to access Gmail and Google Calendar for the same account.
1216     *
1217     * <p>This method may be called from any thread, but the returned
1218     * {@link AccountManagerFuture} must not be used on the main thread.
1219     *
1220     * @param account The account to fetch an auth token for
1221     * @param authTokenType The auth token type, an authenticator-dependent
1222     *     string token, must not be null
1223     * @param notifyAuthFailure True to add a notification to prompt the
1224     *     user for a password if necessary, false to leave that to the caller
1225     * @param callback Callback to invoke when the request completes,
1226     *     null for no callback
1227     * @param handler {@link Handler} identifying the callback thread,
1228     *     null for the main thread
1229     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1230     *     at least the following fields on success:
1231     * <ul>
1232     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1233     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1234     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1235     * </ul>
1236     *
1237     * (Other authenticator-specific values may be returned.)  If the user
1238     * must enter credentials, the returned Bundle contains only
1239     * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1240     *
1241     * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1242     * <ul>
1243     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1244     * <li> {@link OperationCanceledException} if the operation is canceled for
1245     *      any reason, incluidng the user canceling a credential request
1246     * <li> {@link IOException} if the authenticator experienced an I/O problem
1247     *      creating a new auth token, usually because of network trouble
1248     * </ul>
1249     * If the account is no longer present on the device, the return value is
1250     * authenticator-dependent.  The caller should verify the validity of the
1251     * account before requesting an auth token.
1252     * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1253     * boolean, AccountManagerCallback, android.os.Handler)} instead
1254     */
1255    @Deprecated
1256    public AccountManagerFuture<Bundle> getAuthToken(
1257            final Account account, final String authTokenType,
1258            final boolean notifyAuthFailure,
1259            AccountManagerCallback<Bundle> callback, Handler handler) {
1260        return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
1261                handler);
1262    }
1263
1264    /**
1265     * Gets an auth token of the specified type for a particular account,
1266     * optionally raising a notification if the user must enter credentials.
1267     * This method is intended for background tasks and services where the
1268     * user should not be immediately interrupted with a password prompt.
1269     *
1270     * <p>If a previously generated auth token is cached for this account and
1271     * type, then it is returned.  Otherwise, if a saved password is
1272     * available, it is sent to the server to generate a new auth token.
1273     * Otherwise, an {@link Intent} is returned which, when started, will
1274     * prompt the user for a password.  If the notifyAuthFailure parameter is
1275     * set, a status bar notification is also created with the same Intent,
1276     * alerting the user that they need to enter a password at some point.
1277     *
1278     * <p>In that case, you may need to wait until the user responds, which
1279     * could take hours or days or forever.  When the user does respond and
1280     * supply a new password, the account manager will broadcast the
1281     * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1282     * use to try again.
1283     *
1284     * <p>If notifyAuthFailure is not set, it is the application's
1285     * responsibility to launch the returned Intent at some point.
1286     * Either way, the result from this call will not wait for user action.
1287     *
1288     * <p>Some authenticators have auth token <em>types</em>, whose value
1289     * is authenticator-dependent.  Some services use different token types to
1290     * access different functionality -- for example, Google uses different auth
1291     * tokens to access Gmail and Google Calendar for the same account.
1292     *
1293     * <p>This method may be called from any thread, but the returned
1294     * {@link AccountManagerFuture} must not be used on the main thread.
1295     *
1296     * @param account The account to fetch an auth token for
1297     * @param authTokenType The auth token type, an authenticator-dependent
1298     *     string token, must not be null
1299     * @param options Authenticator-specific options for the request,
1300     *     may be null or empty
1301     * @param notifyAuthFailure True to add a notification to prompt the
1302     *     user for a password if necessary, false to leave that to the caller
1303     * @param callback Callback to invoke when the request completes,
1304     *     null for no callback
1305     * @param handler {@link Handler} identifying the callback thread,
1306     *     null for the main thread
1307     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1308     *     at least the following fields on success:
1309     * <ul>
1310     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1311     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1312     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1313     * </ul>
1314     *
1315     * (Other authenticator-specific values may be returned.)  If the user
1316     * must enter credentials, the returned Bundle contains only
1317     * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1318     *
1319     * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1320     * <ul>
1321     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1322     * <li> {@link OperationCanceledException} if the operation is canceled for
1323     *      any reason, incluidng the user canceling a credential request
1324     * <li> {@link IOException} if the authenticator experienced an I/O problem
1325     *      creating a new auth token, usually because of network trouble
1326     * </ul>
1327     * If the account is no longer present on the device, the return value is
1328     * authenticator-dependent.  The caller should verify the validity of the
1329     * account before requesting an auth token.
1330     */
1331    public AccountManagerFuture<Bundle> getAuthToken(
1332            final Account account, final String authTokenType, final Bundle options,
1333            final boolean notifyAuthFailure,
1334            AccountManagerCallback<Bundle> callback, Handler handler) {
1335
1336        if (account == null) throw new IllegalArgumentException("account is null");
1337        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1338        final Bundle optionsIn = new Bundle();
1339        if (options != null) {
1340            optionsIn.putAll(options);
1341        }
1342        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1343        return new AmsTask(null, handler, callback) {
1344            public void doWork() throws RemoteException {
1345                mService.getAuthToken(mResponse, account, authTokenType,
1346                        notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
1347            }
1348        }.start();
1349    }
1350
1351    /**
1352     * Asks the user to add an account of a specified type.  The authenticator
1353     * for this account type processes this request with the appropriate user
1354     * interface.  If the user does elect to create a new account, the account
1355     * name is returned.
1356     *
1357     * <p>This method may be called from any thread, but the returned
1358     * {@link AccountManagerFuture} must not be used on the main thread.
1359     *
1360     * @param accountType The type of account to add; must not be null
1361     * @param authTokenType The type of auth token (see {@link #getAuthToken})
1362     *     this account will need to be able to generate, null for none
1363     * @param requiredFeatures The features (see {@link #hasFeatures}) this
1364     *     account must have, null for none
1365     * @param addAccountOptions Authenticator-specific options for the request,
1366     *     may be null or empty
1367     * @param activity The {@link Activity} context to use for launching a new
1368     *     authenticator-defined sub-Activity to prompt the user to create an
1369     *     account; used only to call startActivity(); if null, the prompt
1370     *     will not be launched directly, but the necessary {@link Intent}
1371     *     will be returned to the caller instead
1372     * @param callback Callback to invoke when the request completes,
1373     *     null for no callback
1374     * @param handler {@link Handler} identifying the callback thread,
1375     *     null for the main thread
1376     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1377     *     these fields if activity was specified and an account was created:
1378     * <ul>
1379     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1380     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1381     * </ul>
1382     *
1383     * If no activity was specified, the returned Bundle contains only
1384     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1385     * actual account creation process.  If an error occurred,
1386     * {@link AccountManagerFuture#getResult()} throws:
1387     * <ul>
1388     * <li> {@link AuthenticatorException} if no authenticator was registered for
1389     *      this account type or the authenticator failed to respond
1390     * <li> {@link OperationCanceledException} if the operation was canceled for
1391     *      any reason, including the user canceling the creation process or adding accounts
1392     *      (of this type) has been disabled by policy
1393     * <li> {@link IOException} if the authenticator experienced an I/O problem
1394     *      creating a new account, usually because of network trouble
1395     * </ul>
1396     */
1397    public AccountManagerFuture<Bundle> addAccount(final String accountType,
1398            final String authTokenType, final String[] requiredFeatures,
1399            final Bundle addAccountOptions,
1400            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
1401        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1402        final Bundle optionsIn = new Bundle();
1403        if (addAccountOptions != null) {
1404            optionsIn.putAll(addAccountOptions);
1405        }
1406        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1407
1408        return new AmsTask(activity, handler, callback) {
1409            public void doWork() throws RemoteException {
1410                mService.addAccount(mResponse, accountType, authTokenType,
1411                        requiredFeatures, activity != null, optionsIn);
1412            }
1413        }.start();
1414    }
1415
1416    /**
1417     * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1418     * @hide
1419     */
1420    public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1421            final String authTokenType, final String[] requiredFeatures,
1422            final Bundle addAccountOptions, final Activity activity,
1423            AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1424        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1425        if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1426        final Bundle optionsIn = new Bundle();
1427        if (addAccountOptions != null) {
1428            optionsIn.putAll(addAccountOptions);
1429        }
1430        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1431
1432        return new AmsTask(activity, handler, callback) {
1433            public void doWork() throws RemoteException {
1434                mService.addAccountAsUser(mResponse, accountType, authTokenType,
1435                        requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1436            }
1437        }.start();
1438    }
1439
1440    /**
1441     * Adds a shared account from the primary user to a secondary user. Adding the shared account
1442     * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1443     * are attempted to be copied to the target user from the primary via calls to the
1444     * authenticator.
1445     * @param account the account to share
1446     * @param user the target user
1447     * @return
1448     * @hide
1449     */
1450    public boolean addSharedAccount(final Account account, UserHandle user) {
1451        try {
1452            boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1453            return val;
1454        } catch (RemoteException re) {
1455            // won't ever happen
1456            throw new RuntimeException(re);
1457        }
1458    }
1459
1460    /**
1461     * Copies an account from the primary user to another user.
1462     * @param account the account to copy
1463     * @param user the target user
1464     * @param callback Callback to invoke when the request completes,
1465     *     null for no callback
1466     * @param handler {@link Handler} identifying the callback thread,
1467     *     null for the main thread
1468     * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1469     * succeeded.
1470     * @hide
1471     */
1472    public AccountManagerFuture<Boolean> copyAccountToUser(
1473            final Account account, final UserHandle user,
1474            AccountManagerCallback<Boolean> callback, Handler handler) {
1475        if (account == null) throw new IllegalArgumentException("account is null");
1476        if (user == null) throw new IllegalArgumentException("user is null");
1477
1478        return new Future2Task<Boolean>(handler, callback) {
1479            @Override
1480            public void doWork() throws RemoteException {
1481                mService.copyAccountToUser(
1482                        mResponse, account, UserHandle.USER_OWNER, user.getIdentifier());
1483            }
1484            @Override
1485            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1486                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1487                    throw new AuthenticatorException("no result in response");
1488                }
1489                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1490            }
1491        }.start();
1492    }
1493
1494    /**
1495     * @hide
1496     * Removes the shared account.
1497     * @param account the account to remove
1498     * @param user the user to remove the account from
1499     * @return
1500     */
1501    public boolean removeSharedAccount(final Account account, UserHandle user) {
1502        try {
1503            boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1504            return val;
1505        } catch (RemoteException re) {
1506            // won't ever happen
1507            throw new RuntimeException(re);
1508        }
1509    }
1510
1511    /**
1512     * @hide
1513     * @param user
1514     * @return
1515     */
1516    public Account[] getSharedAccounts(UserHandle user) {
1517        try {
1518            return mService.getSharedAccountsAsUser(user.getIdentifier());
1519        } catch (RemoteException re) {
1520            // won't ever happen
1521            throw new RuntimeException(re);
1522        }
1523    }
1524
1525    /**
1526     * Confirms that the user knows the password for an account to make extra
1527     * sure they are the owner of the account.  The user-entered password can
1528     * be supplied directly, otherwise the authenticator for this account type
1529     * prompts the user with the appropriate interface.  This method is
1530     * intended for applications which want extra assurance; for example, the
1531     * phone lock screen uses this to let the user unlock the phone with an
1532     * account password if they forget the lock pattern.
1533     *
1534     * <p>If the user-entered password matches a saved password for this
1535     * account, the request is considered valid; otherwise the authenticator
1536     * verifies the password (usually by contacting the server).
1537     *
1538     * <p>This method may be called from any thread, but the returned
1539     * {@link AccountManagerFuture} must not be used on the main thread.
1540     *
1541     * @param account The account to confirm password knowledge for
1542     * @param options Authenticator-specific options for the request;
1543     *     if the {@link #KEY_PASSWORD} string field is present, the
1544     *     authenticator may use it directly rather than prompting the user;
1545     *     may be null or empty
1546     * @param activity The {@link Activity} context to use for launching a new
1547     *     authenticator-defined sub-Activity to prompt the user to enter a
1548     *     password; used only to call startActivity(); if null, the prompt
1549     *     will not be launched directly, but the necessary {@link Intent}
1550     *     will be returned to the caller instead
1551     * @param callback Callback to invoke when the request completes,
1552     *     null for no callback
1553     * @param handler {@link Handler} identifying the callback thread,
1554     *     null for the main thread
1555     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1556     *     with these fields if activity or password was supplied and
1557     *     the account was successfully verified:
1558     * <ul>
1559     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
1560     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1561     * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1562     * </ul>
1563     *
1564     * If no activity or password was specified, the returned Bundle contains
1565     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1566     * password prompt.
1567     *
1568     * <p>Also the returning Bundle may contain {@link
1569     * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
1570     * credential was validated/created.
1571     *
1572     * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
1573     * <ul>
1574     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1575     * <li> {@link OperationCanceledException} if the operation was canceled for
1576     *      any reason, including the user canceling the password prompt
1577     * <li> {@link IOException} if the authenticator experienced an I/O problem
1578     *      verifying the password, usually because of network trouble
1579     * </ul>
1580     */
1581    public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1582            final Bundle options,
1583            final Activity activity,
1584            final AccountManagerCallback<Bundle> callback,
1585            final Handler handler) {
1586        return confirmCredentialsAsUser(account, options, activity, callback, handler,
1587                Process.myUserHandle());
1588    }
1589
1590    /**
1591     * @hide
1592     * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1593     * but for the specified user.
1594     */
1595    public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1596            final Bundle options,
1597            final Activity activity,
1598            final AccountManagerCallback<Bundle> callback,
1599            final Handler handler, UserHandle userHandle) {
1600        if (account == null) throw new IllegalArgumentException("account is null");
1601        final int userId = userHandle.getIdentifier();
1602        return new AmsTask(activity, handler, callback) {
1603            public void doWork() throws RemoteException {
1604                mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1605                        userId);
1606            }
1607        }.start();
1608    }
1609
1610    /**
1611     * Asks the user to enter a new password for an account, updating the
1612     * saved credentials for the account.  Normally this happens automatically
1613     * when the server rejects credentials during an auth token fetch, but this
1614     * can be invoked directly to ensure we have the correct credentials stored.
1615     *
1616     * <p>This method may be called from any thread, but the returned
1617     * {@link AccountManagerFuture} must not be used on the main thread.
1618     *
1619     * @param account The account to update credentials for
1620     * @param authTokenType The credentials entered must allow an auth token
1621     *     of this type to be created (but no actual auth token is returned);
1622     *     may be null
1623     * @param options Authenticator-specific options for the request;
1624     *     may be null or empty
1625     * @param activity The {@link Activity} context to use for launching a new
1626     *     authenticator-defined sub-Activity to prompt the user to enter a
1627     *     password; used only to call startActivity(); if null, the prompt
1628     *     will not be launched directly, but the necessary {@link Intent}
1629     *     will be returned to the caller instead
1630     * @param callback Callback to invoke when the request completes,
1631     *     null for no callback
1632     * @param handler {@link Handler} identifying the callback thread,
1633     *     null for the main thread
1634     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1635     *     with these fields if an activity was supplied and the account
1636     *     credentials were successfully updated:
1637     * <ul>
1638     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1639     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1640     * </ul>
1641     *
1642     * If no activity was specified, the returned Bundle contains
1643     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1644     * password prompt. If an error occurred,
1645     * {@link AccountManagerFuture#getResult()} throws:
1646     * <ul>
1647     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1648     * <li> {@link OperationCanceledException} if the operation was canceled for
1649     *      any reason, including the user canceling the password prompt
1650     * <li> {@link IOException} if the authenticator experienced an I/O problem
1651     *      verifying the password, usually because of network trouble
1652     * </ul>
1653     */
1654    public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1655            final String authTokenType,
1656            final Bundle options, final Activity activity,
1657            final AccountManagerCallback<Bundle> callback,
1658            final Handler handler) {
1659        if (account == null) throw new IllegalArgumentException("account is null");
1660        return new AmsTask(activity, handler, callback) {
1661            public void doWork() throws RemoteException {
1662                mService.updateCredentials(mResponse, account, authTokenType, activity != null,
1663                        options);
1664            }
1665        }.start();
1666    }
1667
1668    /**
1669     * Offers the user an opportunity to change an authenticator's settings.
1670     * These properties are for the authenticator in general, not a particular
1671     * account.  Not all authenticators support this method.
1672     *
1673     * <p>This method may be called from any thread, but the returned
1674     * {@link AccountManagerFuture} must not be used on the main thread.
1675     *
1676     * <p>This method requires the caller to have the same signature as the
1677     * authenticator associated with the specified account type.
1678     *
1679     * @param accountType The account type associated with the authenticator
1680     *     to adjust
1681     * @param activity The {@link Activity} context to use for launching a new
1682     *     authenticator-defined sub-Activity to adjust authenticator settings;
1683     *     used only to call startActivity(); if null, the settings dialog will
1684     *     not be launched directly, but the necessary {@link Intent} will be
1685     *     returned to the caller instead
1686     * @param callback Callback to invoke when the request completes,
1687     *     null for no callback
1688     * @param handler {@link Handler} identifying the callback thread,
1689     *     null for the main thread
1690     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1691     *     which is empty if properties were edited successfully, or
1692     *     if no activity was specified, contains only {@link #KEY_INTENT}
1693     *     needed to launch the authenticator's settings dialog.
1694     *     If an error occurred, {@link AccountManagerFuture#getResult()}
1695     *     throws:
1696     * <ul>
1697     * <li> {@link AuthenticatorException} if no authenticator was registered for
1698     *      this account type or the authenticator failed to respond
1699     * <li> {@link OperationCanceledException} if the operation was canceled for
1700     *      any reason, including the user canceling the settings dialog
1701     * <li> {@link IOException} if the authenticator experienced an I/O problem
1702     *      updating settings, usually because of network trouble
1703     * </ul>
1704     */
1705    public AccountManagerFuture<Bundle> editProperties(final String accountType,
1706            final Activity activity, final AccountManagerCallback<Bundle> callback,
1707            final Handler handler) {
1708        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1709        return new AmsTask(activity, handler, callback) {
1710            public void doWork() throws RemoteException {
1711                mService.editProperties(mResponse, accountType, activity != null);
1712            }
1713        }.start();
1714    }
1715
1716    private void ensureNotOnMainThread() {
1717        final Looper looper = Looper.myLooper();
1718        if (looper != null && looper == mContext.getMainLooper()) {
1719            final IllegalStateException exception = new IllegalStateException(
1720                    "calling this from your main thread can lead to deadlock");
1721            Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1722                    exception);
1723            if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1724                throw exception;
1725            }
1726        }
1727    }
1728
1729    private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1730            final AccountManagerFuture<Bundle> future) {
1731        handler = handler == null ? mMainHandler : handler;
1732        handler.post(new Runnable() {
1733            public void run() {
1734                callback.run(future);
1735            }
1736        });
1737    }
1738
1739    private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
1740            final Account[] accounts) {
1741        final Account[] accountsCopy = new Account[accounts.length];
1742        // send a copy to make sure that one doesn't
1743        // change what another sees
1744        System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1745        handler = (handler == null) ? mMainHandler : handler;
1746        handler.post(new Runnable() {
1747            public void run() {
1748                try {
1749                    listener.onAccountsUpdated(accountsCopy);
1750                } catch (SQLException e) {
1751                    // Better luck next time.  If the problem was disk-full,
1752                    // the STORAGE_OK intent will re-trigger the update.
1753                    Log.e(TAG, "Can't update accounts", e);
1754                }
1755            }
1756        });
1757    }
1758
1759    private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
1760        final IAccountManagerResponse mResponse;
1761        final Handler mHandler;
1762        final AccountManagerCallback<Bundle> mCallback;
1763        final Activity mActivity;
1764        public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
1765            super(new Callable<Bundle>() {
1766                public Bundle call() throws Exception {
1767                    throw new IllegalStateException("this should never be called");
1768                }
1769            });
1770
1771            mHandler = handler;
1772            mCallback = callback;
1773            mActivity = activity;
1774            mResponse = new Response();
1775        }
1776
1777        public final AccountManagerFuture<Bundle> start() {
1778            try {
1779                doWork();
1780            } catch (RemoteException e) {
1781                setException(e);
1782            }
1783            return this;
1784        }
1785
1786        protected void set(Bundle bundle) {
1787            // TODO: somehow a null is being set as the result of the Future. Log this
1788            // case to help debug where this is occurring. When this bug is fixed this
1789            // condition statement should be removed.
1790            if (bundle == null) {
1791                Log.e(TAG, "the bundle must not be null", new Exception());
1792            }
1793            super.set(bundle);
1794        }
1795
1796        public abstract void doWork() throws RemoteException;
1797
1798        private Bundle internalGetResult(Long timeout, TimeUnit unit)
1799                throws OperationCanceledException, IOException, AuthenticatorException {
1800            if (!isDone()) {
1801                ensureNotOnMainThread();
1802            }
1803            try {
1804                if (timeout == null) {
1805                    return get();
1806                } else {
1807                    return get(timeout, unit);
1808                }
1809            } catch (CancellationException e) {
1810                throw new OperationCanceledException();
1811            } catch (TimeoutException e) {
1812                // fall through and cancel
1813            } catch (InterruptedException e) {
1814                // fall through and cancel
1815            } catch (ExecutionException e) {
1816                final Throwable cause = e.getCause();
1817                if (cause instanceof IOException) {
1818                    throw (IOException) cause;
1819                } else if (cause instanceof UnsupportedOperationException) {
1820                    throw new AuthenticatorException(cause);
1821                } else if (cause instanceof AuthenticatorException) {
1822                    throw (AuthenticatorException) cause;
1823                } else if (cause instanceof RuntimeException) {
1824                    throw (RuntimeException) cause;
1825                } else if (cause instanceof Error) {
1826                    throw (Error) cause;
1827                } else {
1828                    throw new IllegalStateException(cause);
1829                }
1830            } finally {
1831                cancel(true /* interrupt if running */);
1832            }
1833            throw new OperationCanceledException();
1834        }
1835
1836        public Bundle getResult()
1837                throws OperationCanceledException, IOException, AuthenticatorException {
1838            return internalGetResult(null, null);
1839        }
1840
1841        public Bundle getResult(long timeout, TimeUnit unit)
1842                throws OperationCanceledException, IOException, AuthenticatorException {
1843            return internalGetResult(timeout, unit);
1844        }
1845
1846        protected void done() {
1847            if (mCallback != null) {
1848                postToHandler(mHandler, mCallback, this);
1849            }
1850        }
1851
1852        /** Handles the responses from the AccountManager */
1853        private class Response extends IAccountManagerResponse.Stub {
1854            public void onResult(Bundle bundle) {
1855                Intent intent = bundle.getParcelable(KEY_INTENT);
1856                if (intent != null && mActivity != null) {
1857                    // since the user provided an Activity we will silently start intents
1858                    // that we see
1859                    mActivity.startActivity(intent);
1860                    // leave the Future running to wait for the real response to this request
1861                } else if (bundle.getBoolean("retry")) {
1862                    try {
1863                        doWork();
1864                    } catch (RemoteException e) {
1865                        // this will only happen if the system process is dead, which means
1866                        // we will be dying ourselves
1867                    }
1868                } else {
1869                    set(bundle);
1870                }
1871            }
1872
1873            public void onError(int code, String message) {
1874                if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1875                        || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1876                    // the authenticator indicated that this request was canceled or we were
1877                    // forbidden to fulfill; cancel now
1878                    cancel(true /* mayInterruptIfRunning */);
1879                    return;
1880                }
1881                setException(convertErrorToException(code, message));
1882            }
1883        }
1884
1885    }
1886
1887    private abstract class BaseFutureTask<T> extends FutureTask<T> {
1888        final public IAccountManagerResponse mResponse;
1889        final Handler mHandler;
1890
1891        public BaseFutureTask(Handler handler) {
1892            super(new Callable<T>() {
1893                public T call() throws Exception {
1894                    throw new IllegalStateException("this should never be called");
1895                }
1896            });
1897            mHandler = handler;
1898            mResponse = new Response();
1899        }
1900
1901        public abstract void doWork() throws RemoteException;
1902
1903        public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
1904
1905        protected void postRunnableToHandler(Runnable runnable) {
1906            Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1907            handler.post(runnable);
1908        }
1909
1910        protected void startTask() {
1911            try {
1912                doWork();
1913            } catch (RemoteException e) {
1914                setException(e);
1915            }
1916        }
1917
1918        protected class Response extends IAccountManagerResponse.Stub {
1919            public void onResult(Bundle bundle) {
1920                try {
1921                    T result = bundleToResult(bundle);
1922                    if (result == null) {
1923                        return;
1924                    }
1925                    set(result);
1926                    return;
1927                } catch (ClassCastException e) {
1928                    // we will set the exception below
1929                } catch (AuthenticatorException e) {
1930                    // we will set the exception below
1931                }
1932                onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
1933            }
1934
1935            public void onError(int code, String message) {
1936                if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1937                        || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1938                    // the authenticator indicated that this request was canceled or we were
1939                    // forbidden to fulfill; cancel now
1940                    cancel(true /* mayInterruptIfRunning */);
1941                    return;
1942                }
1943                setException(convertErrorToException(code, message));
1944            }
1945        }
1946    }
1947
1948    private abstract class Future2Task<T>
1949            extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1950        final AccountManagerCallback<T> mCallback;
1951        public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1952            super(handler);
1953            mCallback = callback;
1954        }
1955
1956        protected void done() {
1957            if (mCallback != null) {
1958                postRunnableToHandler(new Runnable() {
1959                    public void run() {
1960                        mCallback.run(Future2Task.this);
1961                    }
1962                });
1963            }
1964        }
1965
1966        public Future2Task<T> start() {
1967            startTask();
1968            return this;
1969        }
1970
1971        private T internalGetResult(Long timeout, TimeUnit unit)
1972                throws OperationCanceledException, IOException, AuthenticatorException {
1973            if (!isDone()) {
1974                ensureNotOnMainThread();
1975            }
1976            try {
1977                if (timeout == null) {
1978                    return get();
1979                } else {
1980                    return get(timeout, unit);
1981                }
1982            } catch (InterruptedException e) {
1983                // fall through and cancel
1984            } catch (TimeoutException e) {
1985                // fall through and cancel
1986            } catch (CancellationException e) {
1987                // fall through and cancel
1988            } catch (ExecutionException e) {
1989                final Throwable cause = e.getCause();
1990                if (cause instanceof IOException) {
1991                    throw (IOException) cause;
1992                } else if (cause instanceof UnsupportedOperationException) {
1993                    throw new AuthenticatorException(cause);
1994                } else if (cause instanceof AuthenticatorException) {
1995                    throw (AuthenticatorException) cause;
1996                } else if (cause instanceof RuntimeException) {
1997                    throw (RuntimeException) cause;
1998                } else if (cause instanceof Error) {
1999                    throw (Error) cause;
2000                } else {
2001                    throw new IllegalStateException(cause);
2002                }
2003            } finally {
2004                cancel(true /* interrupt if running */);
2005            }
2006            throw new OperationCanceledException();
2007        }
2008
2009        public T getResult()
2010                throws OperationCanceledException, IOException, AuthenticatorException {
2011            return internalGetResult(null, null);
2012        }
2013
2014        public T getResult(long timeout, TimeUnit unit)
2015                throws OperationCanceledException, IOException, AuthenticatorException {
2016            return internalGetResult(timeout, unit);
2017        }
2018
2019    }
2020
2021    private Exception convertErrorToException(int code, String message) {
2022        if (code == ERROR_CODE_NETWORK_ERROR) {
2023            return new IOException(message);
2024        }
2025
2026        if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
2027            return new UnsupportedOperationException(message);
2028        }
2029
2030        if (code == ERROR_CODE_INVALID_RESPONSE) {
2031            return new AuthenticatorException(message);
2032        }
2033
2034        if (code == ERROR_CODE_BAD_ARGUMENTS) {
2035            return new IllegalArgumentException(message);
2036        }
2037
2038        return new AuthenticatorException(message);
2039    }
2040
2041    private class GetAuthTokenByTypeAndFeaturesTask
2042            extends AmsTask implements AccountManagerCallback<Bundle> {
2043        GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2044                final String[] features, Activity activityForPrompting,
2045                final Bundle addAccountOptions, final Bundle loginOptions,
2046                AccountManagerCallback<Bundle> callback, Handler handler) {
2047            super(activityForPrompting, handler, callback);
2048            if (accountType == null) throw new IllegalArgumentException("account type is null");
2049            mAccountType = accountType;
2050            mAuthTokenType = authTokenType;
2051            mFeatures = features;
2052            mAddAccountOptions = addAccountOptions;
2053            mLoginOptions = loginOptions;
2054            mMyCallback = this;
2055        }
2056        volatile AccountManagerFuture<Bundle> mFuture = null;
2057        final String mAccountType;
2058        final String mAuthTokenType;
2059        final String[] mFeatures;
2060        final Bundle mAddAccountOptions;
2061        final Bundle mLoginOptions;
2062        final AccountManagerCallback<Bundle> mMyCallback;
2063        private volatile int mNumAccounts = 0;
2064
2065        public void doWork() throws RemoteException {
2066            getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2067                    new AccountManagerCallback<Account[]>() {
2068                        public void run(AccountManagerFuture<Account[]> future) {
2069                            Account[] accounts;
2070                            try {
2071                                accounts = future.getResult();
2072                            } catch (OperationCanceledException e) {
2073                                setException(e);
2074                                return;
2075                            } catch (IOException e) {
2076                                setException(e);
2077                                return;
2078                            } catch (AuthenticatorException e) {
2079                                setException(e);
2080                                return;
2081                            }
2082
2083                            mNumAccounts = accounts.length;
2084
2085                            if (accounts.length == 0) {
2086                                if (mActivity != null) {
2087                                    // no accounts, add one now. pretend that the user directly
2088                                    // made this request
2089                                    mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2090                                            mAddAccountOptions, mActivity, mMyCallback, mHandler);
2091                                } else {
2092                                    // send result since we can't prompt to add an account
2093                                    Bundle result = new Bundle();
2094                                    result.putString(KEY_ACCOUNT_NAME, null);
2095                                    result.putString(KEY_ACCOUNT_TYPE, null);
2096                                    result.putString(KEY_AUTHTOKEN, null);
2097                                    try {
2098                                        mResponse.onResult(result);
2099                                    } catch (RemoteException e) {
2100                                        // this will never happen
2101                                    }
2102                                    // we are done
2103                                }
2104                            } else if (accounts.length == 1) {
2105                                // have a single account, return an authtoken for it
2106                                if (mActivity == null) {
2107                                    mFuture = getAuthToken(accounts[0], mAuthTokenType,
2108                                            false /* notifyAuthFailure */, mMyCallback, mHandler);
2109                                } else {
2110                                    mFuture = getAuthToken(accounts[0],
2111                                            mAuthTokenType, mLoginOptions,
2112                                            mActivity, mMyCallback, mHandler);
2113                                }
2114                            } else {
2115                                if (mActivity != null) {
2116                                    IAccountManagerResponse chooseResponse =
2117                                            new IAccountManagerResponse.Stub() {
2118                                        public void onResult(Bundle value) throws RemoteException {
2119                                            Account account = new Account(
2120                                                    value.getString(KEY_ACCOUNT_NAME),
2121                                                    value.getString(KEY_ACCOUNT_TYPE));
2122                                            mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2123                                                    mActivity, mMyCallback, mHandler);
2124                                        }
2125
2126                                        public void onError(int errorCode, String errorMessage)
2127                                                throws RemoteException {
2128                                            mResponse.onError(errorCode, errorMessage);
2129                                        }
2130                                    };
2131                                    // have many accounts, launch the chooser
2132                                    Intent intent = new Intent();
2133                                    ComponentName componentName = ComponentName.unflattenFromString(
2134                                            Resources.getSystem().getString(
2135                                                    R.string.config_chooseAccountActivity));
2136                                    intent.setClassName(componentName.getPackageName(),
2137                                            componentName.getClassName());
2138                                    intent.putExtra(KEY_ACCOUNTS, accounts);
2139                                    intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
2140                                            new AccountManagerResponse(chooseResponse));
2141                                    mActivity.startActivity(intent);
2142                                    // the result will arrive via the IAccountManagerResponse
2143                                } else {
2144                                    // send result since we can't prompt to select an account
2145                                    Bundle result = new Bundle();
2146                                    result.putString(KEY_ACCOUNTS, null);
2147                                    try {
2148                                        mResponse.onResult(result);
2149                                    } catch (RemoteException e) {
2150                                        // this will never happen
2151                                    }
2152                                    // we are done
2153                                }
2154                            }
2155                        }}, mHandler);
2156        }
2157
2158        public void run(AccountManagerFuture<Bundle> future) {
2159            try {
2160                final Bundle result = future.getResult();
2161                if (mNumAccounts == 0) {
2162                    final String accountName = result.getString(KEY_ACCOUNT_NAME);
2163                    final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2164                    if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2165                        setException(new AuthenticatorException("account not in result"));
2166                        return;
2167                    }
2168                    final Account account = new Account(accountName, accountType);
2169                    mNumAccounts = 1;
2170                    getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2171                            mMyCallback, mHandler);
2172                    return;
2173                }
2174                set(result);
2175            } catch (OperationCanceledException e) {
2176                cancel(true /* mayInterruptIfRUnning */);
2177            } catch (IOException e) {
2178                setException(e);
2179            } catch (AuthenticatorException e) {
2180                setException(e);
2181            }
2182        }
2183    }
2184
2185    /**
2186     * This convenience helper combines the functionality of
2187     * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2188     * {@link #addAccount}.
2189     *
2190     * <p>This method gets a list of the accounts matching the
2191     * specified type and feature set; if there is exactly one, it is
2192     * used; if there are more than one, the user is prompted to pick one;
2193     * if there are none, the user is prompted to add one.  Finally,
2194     * an auth token is acquired for the chosen account.
2195     *
2196     * <p>This method may be called from any thread, but the returned
2197     * {@link AccountManagerFuture} must not be used on the main thread.
2198     *
2199     * @param accountType The account type required
2200     *     (see {@link #getAccountsByType}), must not be null
2201     * @param authTokenType The desired auth token type
2202     *     (see {@link #getAuthToken}), must not be null
2203     * @param features Required features for the account
2204     *     (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2205     * @param activity The {@link Activity} context to use for launching new
2206     *     sub-Activities to prompt to add an account, select an account,
2207     *     and/or enter a password, as necessary; used only to call
2208     *     startActivity(); should not be null
2209     * @param addAccountOptions Authenticator-specific options to use for
2210     *     adding new accounts; may be null or empty
2211     * @param getAuthTokenOptions Authenticator-specific options to use for
2212     *     getting auth tokens; may be null or empty
2213     * @param callback Callback to invoke when the request completes,
2214     *     null for no callback
2215     * @param handler {@link Handler} identifying the callback thread,
2216     *     null for the main thread
2217     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2218     *     at least the following fields:
2219     * <ul>
2220     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2221     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2222     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
2223     * </ul>
2224     *
2225     * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
2226     * <ul>
2227     * <li> {@link AuthenticatorException} if no authenticator was registered for
2228     *      this account type or the authenticator failed to respond
2229     * <li> {@link OperationCanceledException} if the operation was canceled for
2230     *      any reason, including the user canceling any operation
2231     * <li> {@link IOException} if the authenticator experienced an I/O problem
2232     *      updating settings, usually because of network trouble
2233     * </ul>
2234     */
2235    public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
2236            final String accountType, final String authTokenType, final String[] features,
2237            final Activity activity, final Bundle addAccountOptions,
2238            final Bundle getAuthTokenOptions,
2239            final AccountManagerCallback<Bundle> callback, final Handler handler) {
2240        if (accountType == null) throw new IllegalArgumentException("account type is null");
2241        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2242        final GetAuthTokenByTypeAndFeaturesTask task =
2243                new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
2244                activity, addAccountOptions, getAuthTokenOptions, callback, handler);
2245        task.start();
2246        return task;
2247    }
2248
2249    /**
2250     * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2251     * accounts.
2252     * The caller will then typically start the activity by calling
2253     * <code>startActivityForResult(intent, ...);</code>.
2254     * <p>
2255     * On success the activity returns a Bundle with the account name and type specified using
2256     * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2257     * <p>
2258     * The most common case is to call this with one account type, e.g.:
2259     * <p>
2260     * <pre>  newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
2261     * null, null, null);</pre>
2262     * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2263     * selected one, according to the caller's definition of selected.
2264     * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
2265     * shown. If not specified then this field will not limit the displayed accounts.
2266     * @param allowableAccountTypes an optional string array of account types. These are used
2267     * both to filter the shown accounts and to filter the list of account types that are shown
2268     * when adding an account. If not specified then this field will not limit the displayed
2269     * account types when adding an account.
2270     * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
2271     * it is only shown when there is more than one account from which to choose
2272     * @param descriptionOverrideText if non-null this string is used as the description in the
2273     * accounts chooser screen rather than the default
2274     * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2275     * authTokenType parameter
2276     * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2277     * requiredFeatures parameter
2278     * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2279     * parameter
2280     * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2281     */
2282    static public Intent newChooseAccountIntent(Account selectedAccount,
2283            ArrayList<Account> allowableAccounts,
2284            String[] allowableAccountTypes,
2285            boolean alwaysPromptForAccount,
2286            String descriptionOverrideText,
2287            String addAccountAuthTokenType,
2288            String[] addAccountRequiredFeatures,
2289            Bundle addAccountOptions) {
2290        Intent intent = new Intent();
2291        ComponentName componentName = ComponentName.unflattenFromString(
2292                Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2293        intent.setClassName(componentName.getPackageName(),
2294                componentName.getClassName());
2295        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
2296                allowableAccounts);
2297        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2298                allowableAccountTypes);
2299        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2300                addAccountOptions);
2301        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
2302        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
2303                alwaysPromptForAccount);
2304        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2305                descriptionOverrideText);
2306        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2307                addAccountAuthTokenType);
2308        intent.putExtra(
2309                ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2310                addAccountRequiredFeatures);
2311        return intent;
2312    }
2313
2314    private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
2315            Maps.newHashMap();
2316
2317    /**
2318     * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2319     * so that it can read the updated list of accounts and send them to the listener
2320     * in mAccountsUpdatedListeners.
2321     */
2322    private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
2323        public void onReceive(final Context context, final Intent intent) {
2324            final Account[] accounts = getAccounts();
2325            // send the result to the listeners
2326            synchronized (mAccountsUpdatedListeners) {
2327                for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
2328                        mAccountsUpdatedListeners.entrySet()) {
2329                    postToHandler(entry.getValue(), entry.getKey(), accounts);
2330                }
2331            }
2332        }
2333    };
2334
2335    /**
2336     * Adds an {@link OnAccountsUpdateListener} to this instance of the
2337     * {@link AccountManager}.  This listener will be notified whenever the
2338     * list of accounts on the device changes.
2339     *
2340     * <p>As long as this listener is present, the AccountManager instance
2341     * will not be garbage-collected, and neither will the {@link Context}
2342     * used to retrieve it, which may be a large Activity instance.  To avoid
2343     * memory leaks, you must remove this listener before then.  Normally
2344     * listeners are added in an Activity or Service's {@link Activity#onCreate}
2345     * and removed in {@link Activity#onDestroy}.
2346     *
2347     * <p>It is safe to call this method from the main thread.
2348     *
2349     * <p>This method requires the caller to hold the permission
2350     * {@link android.Manifest.permission#GET_ACCOUNTS}.
2351     *
2352     * @param listener The listener to send notifications to
2353     * @param handler {@link Handler} identifying the thread to use
2354     *     for notifications, null for the main thread
2355     * @param updateImmediately If true, the listener will be invoked
2356     *     (on the handler thread) right away with the current account list
2357     * @throws IllegalArgumentException if listener is null
2358     * @throws IllegalStateException if listener was already added
2359     */
2360    @RequiresPermission(GET_ACCOUNTS)
2361    public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
2362            Handler handler, boolean updateImmediately) {
2363        if (listener == null) {
2364            throw new IllegalArgumentException("the listener is null");
2365        }
2366        synchronized (mAccountsUpdatedListeners) {
2367            if (mAccountsUpdatedListeners.containsKey(listener)) {
2368                throw new IllegalStateException("this listener is already added");
2369            }
2370            final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2371
2372            mAccountsUpdatedListeners.put(listener, handler);
2373
2374            if (wasEmpty) {
2375                // Register a broadcast receiver to monitor account changes
2376                IntentFilter intentFilter = new IntentFilter();
2377                intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
2378                // To recover from disk-full.
2379                intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
2380                mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2381            }
2382        }
2383
2384        if (updateImmediately) {
2385            postToHandler(handler, listener, getAccounts());
2386        }
2387    }
2388
2389    /**
2390     * Removes an {@link OnAccountsUpdateListener} previously registered with
2391     * {@link #addOnAccountsUpdatedListener}.  The listener will no longer
2392     * receive notifications of account changes.
2393     *
2394     * <p>It is safe to call this method from the main thread.
2395     *
2396     * <p>No permission is required to call this method.
2397     *
2398     * @param listener The previously added listener to remove
2399     * @throws IllegalArgumentException if listener is null
2400     * @throws IllegalStateException if listener was not already added
2401     */
2402    public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
2403        if (listener == null) throw new IllegalArgumentException("listener is null");
2404        synchronized (mAccountsUpdatedListeners) {
2405            if (!mAccountsUpdatedListeners.containsKey(listener)) {
2406                Log.e(TAG, "Listener was not previously added");
2407                return;
2408            }
2409            mAccountsUpdatedListeners.remove(listener);
2410            if (mAccountsUpdatedListeners.isEmpty()) {
2411                mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2412            }
2413        }
2414    }
2415}
2416