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