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