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