AccountManager.java revision 661f0130de6a4e1592b679a212c8f758133d36ee
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}.
520     *
521     * @param accountType The account type of the auth token to invalidate
522     * @param authToken The auth token to invalidate
523     */
524    public void invalidateAuthToken(final String accountType, final String authToken) {
525        try {
526            mService.invalidateAuthToken(accountType, authToken);
527        } catch (RemoteException e) {
528            // won't ever happen
529            throw new RuntimeException(e);
530        }
531    }
532
533    /**
534     * Gets an auth token from the AccountManager's cache.  If no auth
535     * token is cached for this account, null will be returned -- a new
536     * auth token will not be generated, and the server will not be contacted.
537     * Intended for use by the authenticator, not directly by applications.
538     *
539     * <p>It is safe to call this method from the main thread.
540     *
541     * <p>This method requires the caller to hold the permission
542     * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
543     * and to have the same UID as the account's authenticator.
544     *
545     * @param account The account to fetch an auth token for
546     * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
547     * @return The cached auth token for this account and type, or null if
548     *     no auth token is cached or the account does not exist.
549     */
550    public String peekAuthToken(final Account account, final String authTokenType) {
551        if (account == null) {
552            Log.e(TAG, "peekAuthToken: the account must not be null");
553            return null;
554        }
555        if (authTokenType == null) {
556            return null;
557        }
558        try {
559            return mService.peekAuthToken(account, authTokenType);
560        } catch (RemoteException e) {
561            // won't ever happen
562            throw new RuntimeException(e);
563        }
564    }
565
566    /**
567     * Sets or forgets a saved password.  This modifies the local copy of the
568     * password used to automatically authenticate the user; it does
569     * not change the user's account password on the server.  Intended for use
570     * by the authenticator, not directly by applications.
571     *
572     * <p>It is safe to call this method from the main thread.
573     *
574     * <p>This method requires the caller to hold the permission
575     * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
576     * and have the same UID as the account's authenticator.
577     *
578     * @param account The account to set a password for
579     * @param password The password to set, null to clear the password
580     */
581    public void setPassword(final Account account, final String password) {
582        if (account == null) {
583            Log.e(TAG, "the account must not be null");
584            return;
585        }
586        try {
587            mService.setPassword(account, password);
588        } catch (RemoteException e) {
589            // won't ever happen
590            throw new RuntimeException(e);
591        }
592    }
593
594    /**
595     * Forgets a saved password.  This erases the local copy of the password;
596     * it does not change the user's account password on the server.
597     * Has the same effect as setPassword(account, null) but requires fewer
598     * permissions, and may be used by applications or management interfaces
599     * to "sign out" from an account.
600     *
601     * <p>It is safe to call this method from the main thread.
602     *
603     * <p>This method requires the caller to hold the permission
604     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
605     *
606     * @param account The account whose password to clear
607     */
608    public void clearPassword(final Account account) {
609        if (account == null) {
610            Log.e(TAG, "the account must not be null");
611            return;
612        }
613        try {
614            mService.clearPassword(account);
615        } catch (RemoteException e) {
616            // won't ever happen
617            throw new RuntimeException(e);
618        }
619    }
620
621    /**
622     * Sets one userdata key for an account.  Intended by use for the
623     * authenticator to stash state for itself, not directly by applications.
624     * The meaning of the keys and values is up to the authenticator.
625     *
626     * <p>It is safe to call this method from the main thread.
627     *
628     * <p>This method requires the caller to hold the permission
629     * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
630     * and to have the same UID as the account's authenticator.
631     *
632     * @param account The account to set the userdata for
633     * @param key The userdata key to set.  Must not be null
634     * @param value The value to set, null to clear this userdata key
635     */
636    public void setUserData(final Account account, final String key, final String value) {
637        if (account == null) {
638            Log.e(TAG, "the account must not be null");
639            return;
640        }
641        if (key == null) {
642            Log.e(TAG, "the key must not be null");
643            return;
644        }
645        try {
646            mService.setUserData(account, key, value);
647        } catch (RemoteException e) {
648            // won't ever happen
649            throw new RuntimeException(e);
650        }
651    }
652
653    /**
654     * Adds an auth token to the AccountManager cache for an account.
655     * If the account does not exist then this call has no effect.
656     * Replaces any previous auth token for this account and auth token type.
657     * Intended for use by the authenticator, not directly by applications.
658     *
659     * <p>It is safe to call this method from the main thread.
660     *
661     * <p>This method requires the caller to hold the permission
662     * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
663     * and to have the same UID as the account's authenticator.
664     *
665     * @param account The account to set an auth token for
666     * @param authTokenType The type of the auth token, see {#getAuthToken}
667     * @param authToken The auth token to add to the cache
668     */
669    public void setAuthToken(Account account, final String authTokenType, final String authToken) {
670        try {
671            mService.setAuthToken(account, authTokenType, authToken);
672        } catch (RemoteException e) {
673            // won't ever happen
674            throw new RuntimeException(e);
675        }
676    }
677
678    /**
679     * This convenience helper synchronously gets an auth token with
680     * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
681     *
682     * <p>This method may block while a network request completes, and must
683     * never be made from the main thread.
684     *
685     * <p>This method requires the caller to hold the permission
686     * {@link android.Manifest.permission#USE_CREDENTIALS}.
687     *
688     * @param account The account to fetch an auth token for
689     * @param authTokenType The auth token type, see {#link getAuthToken}
690     * @param notifyAuthFailure If true, display a notification and return null
691     *     if authentication fails; if false, prompt and wait for the user to
692     *     re-enter correct credentials before returning
693     * @return An auth token of the specified type for this account, or null
694     *     if authentication fails or none can be fetched.
695     * @throws AuthenticatorException if the authenticator failed to respond
696     * @throws OperationCanceledException if the request was canceled for any
697     *     reason, including the user canceling a credential request
698     * @throws java.io.IOException if the authenticator experienced an I/O problem
699     *     creating a new auth token, usually because of network trouble
700     */
701    public String blockingGetAuthToken(Account account, String authTokenType,
702            boolean notifyAuthFailure)
703            throws OperationCanceledException, IOException, AuthenticatorException {
704        Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
705                null /* handler */).getResult();
706        return bundle.getString(KEY_AUTHTOKEN);
707    }
708
709    /**
710     * Gets an auth token of the specified type for a particular account,
711     * prompting the user for credentials if necessary.  This method is
712     * intended for applications running in the foreground where it makes
713     * sense to ask the user directly for a password.
714     *
715     * <p>If a previously generated auth token is cached for this account and
716     * type, then it will be returned.  Otherwise, if we have a saved password
717     * the server accepts, it will be used to generate a new auth token.
718     * Otherwise, the user will be asked for a password, which will be sent to
719     * the server to generate a new auth token.
720     *
721     * <p>The value of the auth token type depends on the authenticator.
722     * Some services use different tokens to access different functionality --
723     * for example, Google uses different auth tokens to access Gmail and
724     * Google Calendar for the same account.
725     *
726     * <p>This method may be called from any thread, but the returned
727     * {@link AccountManagerFuture} must not be used on the main thread.
728     *
729     * <p>This method requires the caller to hold the permission
730     * {@link android.Manifest.permission#USE_CREDENTIALS}.
731     *
732     * @param account The account to fetch an auth token for
733     * @param authTokenType The auth token type, an authenticator-dependent
734     *     string token, must not be null
735     * @param options Authenticator-specific options for the request,
736     *     may be null or empty
737     * @param activity The {@link Activity} context to use for launching a new
738     *     authenticator-defined sub-Activity to prompt the user for a password
739     *     if necessary; used only to call startActivity(); must not be null.
740     * @param callback Callback to invoke when the request completes,
741     *     null for no callback
742     * @param handler {@link Handler} identifying the callback thread,
743     *     null for the main thread
744     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
745     *     at least the following fields:
746     * <ul>
747     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
748     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
749     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
750     * </ul>
751     *
752     * (Other authenticator-specific values may be returned.)  If an auth token
753     * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
754     * <ul>
755     * <li> {@link AuthenticatorException} if the authenticator failed to respond
756     * <li> {@link OperationCanceledException} if the operation is canceled for
757     *      any reason, incluidng the user canceling a credential request
758     * <li> {@link IOException} if the authenticator experienced an I/O problem
759     *      creating a new auth token, usually because of network trouble
760     * </ul>
761     */
762    public AccountManagerFuture<Bundle> getAuthToken(
763            final Account account, final String authTokenType, final Bundle options,
764            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
765        if (activity == null) throw new IllegalArgumentException("activity is null");
766        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
767        return new AmsTask(activity, handler, callback) {
768            public void doWork() throws RemoteException {
769                mService.getAuthToken(mResponse, account, authTokenType,
770                        false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
771                        options);
772            }
773        }.start();
774    }
775
776    /**
777     * Gets an auth token of the specified type for a particular account,
778     * optionally raising a notification if the user must enter credentials.
779     * This method is intended for background tasks and services where the
780     * user should not be immediately interrupted with a password prompt.
781     *
782     * <p>If a previously generated auth token is cached for this account and
783     * type, then it will be returned.  Otherwise, if we have saved credentials
784     * the server accepts, it will be used to generate a new auth token.
785     * Otherwise, an Intent will be returned which, when started, will prompt
786     * the user for a password.  If the notifyAuthFailure parameter is set,
787     * the same Intent will be associated with a status bar notification,
788     * alerting the user that they need to enter a password at some point.
789     *
790     * <p>If the intent is left in a notification, you will need to wait until
791     * the user gets around to entering a password before trying again,
792     * which could be hours or days or never.  When it does happen, the
793     * account manager will broadcast the {@link #LOGIN_ACCOUNTS_CHANGED_ACTION}
794     * {@link Intent}, which applications can use to trigger another attempt
795     * to fetch an auth token.
796     *
797     * <p>If notifications are not enabled, it is the application's
798     * responsibility to launch the returned intent at some point to let
799     * the user enter credentials.  In either case, the result from this
800     * call will not wait for user action.
801     *
802     * <p>The value of the auth token type depends on the authenticator.
803     * Some services use different tokens to access different functionality --
804     * for example, Google uses different auth tokens to access Gmail and
805     * Google Calendar for the same account.
806     *
807     * <p>This method may be called from any thread, but the returned
808     * {@link AccountManagerFuture} must not be used on the main thread.
809     *
810     * <p>This method requires the caller to hold the permission
811     * {@link android.Manifest.permission#USE_CREDENTIALS}.
812     *
813     * @param account The account to fetch an auth token for
814     * @param authTokenType The auth token type, an authenticator-dependent
815     *     string token, must not be null
816     * @param options Authenticator-specific options for the request,
817     *     may be null or empty
818     * @param notifyAuthFailure True to add a notification to prompt the
819     *     user for a password if necessary, false to leave that to the caller
820     * @param callback Callback to invoke when the request completes,
821     *     null for no callback
822     * @param handler {@link Handler} identifying the callback thread,
823     *     null for the main thread
824     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
825     *     at least the following fields on success:
826     * <ul>
827     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
828     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
829     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
830     * </ul>
831     *
832     * (Other authenticator-specific values may be returned.)  If the user
833     * must enter credentials, the returned Bundle contains only
834     * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
835     *
836     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
837     * <ul>
838     * <li> {@link AuthenticatorException} if the authenticator failed to respond
839     * <li> {@link OperationCanceledException} if the operation is canceled for
840     *      any reason, incluidng the user canceling a credential request
841     * <li> {@link IOException} if the authenticator experienced an I/O problem
842     *      creating a new auth token, usually because of network trouble
843     * </ul>
844     */
845    public AccountManagerFuture<Bundle> getAuthToken(
846            final Account account, final String authTokenType, final boolean notifyAuthFailure,
847            AccountManagerCallback<Bundle> callback, Handler handler) {
848        if (account == null) throw new IllegalArgumentException("account is null");
849        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
850        return new AmsTask(null, handler, callback) {
851            public void doWork() throws RemoteException {
852                mService.getAuthToken(mResponse, account, authTokenType,
853                        notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
854            }
855        }.start();
856    }
857
858    /**
859     * Asks the user to add an account of a specified type.  The authenticator
860     * for this account type processes this request with the appropriate user
861     * interface.  If the user does elect to create a new account, the account
862     * name is returned.
863     *
864     * <p>This method may be called from any thread, but the returned
865     * {@link AccountManagerFuture} must not be used on the main thread.
866     *
867     * <p>This method requires the caller to hold the permission
868     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
869     *
870     * @param accountType The type of account to add; must not be null
871     * @param authTokenType The type of auth token (see {@link #getAuthToken})
872     *     this account will need to be able to generate, null for none
873     * @param requiredFeatures The features (see {@link #hasFeatures}) this
874     *     account must have, null for none
875     * @param addAccountOptions Authenticator-specific options for the request,
876     *     may be null or empty
877     * @param activity The {@link Activity} context to use for launching a new
878     *     authenticator-defined sub-Activity to prompt the user to create an
879     *     account; used only to call startActivity(); if null, the prompt
880     *     will not be launched directly, but the necessary {@link Intent}
881     *     will be returned to the caller instead
882     * @param callback Callback to invoke when the request completes,
883     *     null for no callback
884     * @param handler {@link Handler} identifying the callback thread,
885     *     null for the main thread
886     * @return An {@link AccountManagerFeature} which resolves to a Bundle with
887     *     these fields if activity was specified and an account was created:
888     * <ul>
889     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
890     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
891     * </ul>
892     *
893     * If no activity was specified, the returned Bundle contains only
894     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
895     * actual account creation process.
896     *
897     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
898     * <ul>
899     * <li> {@link AuthenticatorException} if no authenticator was registered for
900     *      this account type or the authenticator failed to respond
901     * <li> {@link OperationCanceledException} if the operation was canceled for
902     *      any reason, including the user canceling the creation process
903     * <li> {@link IOException} if the authenticator experienced an I/O problem
904     *      creating a new account, usually because of network trouble
905     * </ul>
906     */
907    public AccountManagerFuture<Bundle> addAccount(final String accountType,
908            final String authTokenType, final String[] requiredFeatures,
909            final Bundle addAccountOptions,
910            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
911        return new AmsTask(activity, handler, callback) {
912            public void doWork() throws RemoteException {
913                if (accountType == null) {
914                    Log.e(TAG, "the account must not be null");
915                    // to unblock caller waiting on Future.get()
916                    set(new Bundle());
917                    return;
918                }
919                mService.addAcount(mResponse, accountType, authTokenType,
920                        requiredFeatures, activity != null, addAccountOptions);
921            }
922        }.start();
923    }
924
925    /**
926     * Confirms that the user knows the password for an account to make extra
927     * sure they are the owner of the account.  The user-entered password can
928     * be supplied directly, otherwise the authenticator for this account type
929     * prompts the user with the appropriate interface.  This method is
930     * intended for applications which want extra assurance; for example, the
931     * phone lock screen uses this to let the user unlock the phone with an
932     * account password if they forget the lock pattern.
933     *
934     * <p>If the user-entered password matches a saved password for this
935     * account, the request is considered valid; otherwise the authenticator
936     * verifies the password (usually by contacting the server).
937     *
938     * <p>This method may be called from any thread, but the returned
939     * {@link AccountManagerFuture} must not be used on the main thread.
940     *
941     * <p>This method requires the caller to hold the permission
942     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
943     *
944     * @param account The account to confirm password knowledge for
945     * @param options Authenticator-specific options for the request;
946     *     if the {@link #KEY_PASSWORD} string field is present, the
947     *     authenticator may use it directly rather than prompting the user;
948     *     may be null or empty
949     * @param activity The {@link Activity} context to use for launching a new
950     *     authenticator-defined sub-Activity to prompt the user to enter a
951     *     password; used only to call startActivity(); if null, the prompt
952     *     will not be launched directly, but the necessary {@link Intent}
953     *     will be returned to the caller instead
954     * @param callback Callback to invoke when the request completes,
955     *     null for no callback
956     * @param handler {@link Handler} identifying the callback thread,
957     *     null for the main thread
958     * @return An {@link AccountManagerFuture} which resolves to a Bundle
959     *     with these fields if activity or password was supplied and
960     *     the account was successfully verified:
961     * <ul>
962     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
963     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
964     * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
965     * </ul>
966     *
967     * If no activity or password was specified, the returned Bundle contains
968     * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
969     * password prompt.
970     *
971     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
972     * <ul>
973     * <li> {@link AuthenticatorException} if the authenticator failed to respond
974     * <li> {@link OperationCanceledException} if the operation was canceled for
975     *      any reason, including the user canceling the password prompt
976     * <li> {@link IOException} if the authenticator experienced an I/O problem
977     *      verifying the password, usually because of network trouble
978     * </ul>
979     */
980    public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
981            final Bundle options,
982            final Activity activity,
983            final AccountManagerCallback<Bundle> callback,
984            final Handler handler) {
985        return new AmsTask(activity, handler, callback) {
986            public void doWork() throws RemoteException {
987                mService.confirmCredentials(mResponse, account, options, activity != null);
988            }
989        }.start();
990    }
991
992    /**
993     * Asks the user to enter a new password for an account, updating the
994     * saved credentials for the account.  Normally this happens automatically
995     * when the server rejects credentials during an auth token fetch, but this
996     * can be invoked directly to ensure we have the correct credentials stored.
997     *
998     * <p>This method may be called from any thread, but the returned
999     * {@link AccountManagerFuture} must not be used on the main thread.
1000     *
1001     * <p>This method requires the caller to hold the permission
1002     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1003     *
1004     * @param account The account to update credentials for
1005     * @param authTokenType The credentials entered must allow an auth token
1006     *     of this type to be created (but no actual auth token is returned);
1007     *     may be null
1008     * @param options Authenticator-specific options for the request;
1009     *     may be null or empty
1010     * @param activity The {@link Activity} context to use for launching a new
1011     *     authenticator-defined sub-Activity to prompt the user to enter a
1012     *     password; used only to call startActivity(); if null, the prompt
1013     *     will not be launched directly, but the necessary {@link Intent}
1014     *     will be returned to the caller instead
1015     * @param callback Callback to invoke when the request completes,
1016     *     null for no callback
1017     * @param handler {@link Handler} identifying the callback thread,
1018     *     null for the main thread
1019     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1020     *     with these fields if an activity was supplied and the account
1021     *     credentials were successfully updated:
1022     * <ul>
1023     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1024     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1025     * </ul>
1026     *
1027     * If no activity was specified, the returned Bundle contains only
1028     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1029     * password prompt.
1030     *
1031     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1032     * <ul>
1033     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1034     * <li> {@link OperationCanceledException} if the operation was canceled for
1035     *      any reason, including the user canceling the password prompt
1036     * <li> {@link IOException} if the authenticator experienced an I/O problem
1037     *      verifying the password, usually because of network trouble
1038     * </ul>
1039     */
1040    public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1041            final String authTokenType,
1042            final Bundle options, final Activity activity,
1043            final AccountManagerCallback<Bundle> callback,
1044            final Handler handler) {
1045        return new AmsTask(activity, handler, callback) {
1046            public void doWork() throws RemoteException {
1047                mService.updateCredentials(mResponse, account, authTokenType, activity != null,
1048                        options);
1049            }
1050        }.start();
1051    }
1052
1053    /**
1054     * Offers the user an opportunity to change an authenticator's settings.
1055     * These properties are for the authenticator in general, not a particular
1056     * account.  Not all authenticators support this method.
1057     *
1058     * <p>This method may be called from any thread, but the returned
1059     * {@link AccountManagerFuture} must not be used on the main thread.
1060     *
1061     * <p>This method requires the caller to hold the permission
1062     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1063     *
1064     * @param accountType The account type associated with the authenticator
1065     *     to adjust
1066     * @param activity The {@link Activity} context to use for launching a new
1067     *     authenticator-defined sub-Activity to adjust authenticator settings;
1068     *     used only to call startActivity(); if null, the settings dialog will
1069     *     not be launched directly, but the necessary {@link Intent} will be
1070     *     returned to the caller instead
1071     * @param callback Callback to invoke when the request completes,
1072     *     null for no callback
1073     * @param handler {@link Handler} identifying the callback thread,
1074     *     null for the main thread
1075     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1076     *     which is empty if properties were edited successfully, or
1077     *     if no activity was specified, contains only {@link #KEY_INTENT}
1078     *     needed to launch the authenticator's settings dialog.
1079     *
1080     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1081     * <ul>
1082     * <li> {@link AuthenticatorException} if no authenticator was registered for
1083     *      this account type or the authenticator failed to respond
1084     * <li> {@link OperationCanceledException} if the operation was canceled for
1085     *      any reason, including the user canceling the settings dialog
1086     * <li> {@link IOException} if the authenticator experienced an I/O problem
1087     *      updating settings, usually because of network trouble
1088     * </ul>
1089     */
1090    public AccountManagerFuture<Bundle> editProperties(final String accountType,
1091            final Activity activity, final AccountManagerCallback<Bundle> callback,
1092            final Handler handler) {
1093        return new AmsTask(activity, handler, callback) {
1094            public void doWork() throws RemoteException {
1095                mService.editProperties(mResponse, accountType, activity != null);
1096            }
1097        }.start();
1098    }
1099
1100    private void ensureNotOnMainThread() {
1101        final Looper looper = Looper.myLooper();
1102        if (looper != null && looper == mContext.getMainLooper()) {
1103            final IllegalStateException exception = new IllegalStateException(
1104                    "calling this from your main thread can lead to deadlock");
1105            Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1106                    exception);
1107            if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1108                throw exception;
1109            }
1110        }
1111    }
1112
1113    private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1114            final AccountManagerFuture<Bundle> future) {
1115        handler = handler == null ? mMainHandler : handler;
1116        handler.post(new Runnable() {
1117            public void run() {
1118                callback.run(future);
1119            }
1120        });
1121    }
1122
1123    private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
1124            final Account[] accounts) {
1125        final Account[] accountsCopy = new Account[accounts.length];
1126        // send a copy to make sure that one doesn't
1127        // change what another sees
1128        System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1129        handler = (handler == null) ? mMainHandler : handler;
1130        handler.post(new Runnable() {
1131            public void run() {
1132                try {
1133                    listener.onAccountsUpdated(accountsCopy);
1134                } catch (SQLException e) {
1135                    // Better luck next time.  If the problem was disk-full,
1136                    // the STORAGE_OK intent will re-trigger the update.
1137                    Log.e(TAG, "Can't update accounts", e);
1138                }
1139            }
1140        });
1141    }
1142
1143    private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
1144        final IAccountManagerResponse mResponse;
1145        final Handler mHandler;
1146        final AccountManagerCallback<Bundle> mCallback;
1147        final Activity mActivity;
1148        public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
1149            super(new Callable<Bundle>() {
1150                public Bundle call() throws Exception {
1151                    throw new IllegalStateException("this should never be called");
1152                }
1153            });
1154
1155            mHandler = handler;
1156            mCallback = callback;
1157            mActivity = activity;
1158            mResponse = new Response();
1159        }
1160
1161        public final AccountManagerFuture<Bundle> start() {
1162            try {
1163                doWork();
1164            } catch (RemoteException e) {
1165                setException(e);
1166            }
1167            return this;
1168        }
1169
1170        public abstract void doWork() throws RemoteException;
1171
1172        private Bundle internalGetResult(Long timeout, TimeUnit unit)
1173                throws OperationCanceledException, IOException, AuthenticatorException {
1174            if (!isDone()) {
1175                ensureNotOnMainThread();
1176            }
1177            try {
1178                if (timeout == null) {
1179                    return get();
1180                } else {
1181                    return get(timeout, unit);
1182                }
1183            } catch (CancellationException e) {
1184                throw new OperationCanceledException();
1185            } catch (TimeoutException e) {
1186                // fall through and cancel
1187            } catch (InterruptedException e) {
1188                // fall through and cancel
1189            } catch (ExecutionException e) {
1190                final Throwable cause = e.getCause();
1191                if (cause instanceof IOException) {
1192                    throw (IOException) cause;
1193                } else if (cause instanceof UnsupportedOperationException) {
1194                    throw new AuthenticatorException(cause);
1195                } else if (cause instanceof AuthenticatorException) {
1196                    throw (AuthenticatorException) cause;
1197                } else if (cause instanceof RuntimeException) {
1198                    throw (RuntimeException) cause;
1199                } else if (cause instanceof Error) {
1200                    throw (Error) cause;
1201                } else {
1202                    throw new IllegalStateException(cause);
1203                }
1204            } finally {
1205                cancel(true /* interrupt if running */);
1206            }
1207            throw new OperationCanceledException();
1208        }
1209
1210        public Bundle getResult()
1211                throws OperationCanceledException, IOException, AuthenticatorException {
1212            return internalGetResult(null, null);
1213        }
1214
1215        public Bundle getResult(long timeout, TimeUnit unit)
1216                throws OperationCanceledException, IOException, AuthenticatorException {
1217            return internalGetResult(timeout, unit);
1218        }
1219
1220        protected void done() {
1221            if (mCallback != null) {
1222                postToHandler(mHandler, mCallback, this);
1223            }
1224        }
1225
1226        /** Handles the responses from the AccountManager */
1227        private class Response extends IAccountManagerResponse.Stub {
1228            public void onResult(Bundle bundle) {
1229                Intent intent = bundle.getParcelable("intent");
1230                if (intent != null && mActivity != null) {
1231                    // since the user provided an Activity we will silently start intents
1232                    // that we see
1233                    mActivity.startActivity(intent);
1234                    // leave the Future running to wait for the real response to this request
1235                } else if (bundle.getBoolean("retry")) {
1236                    try {
1237                        doWork();
1238                    } catch (RemoteException e) {
1239                        // this will only happen if the system process is dead, which means
1240                        // we will be dying ourselves
1241                    }
1242                } else {
1243                    set(bundle);
1244                }
1245            }
1246
1247            public void onError(int code, String message) {
1248                if (code == ERROR_CODE_CANCELED) {
1249                    // the authenticator indicated that this request was canceled, do so now
1250                    cancel(true /* mayInterruptIfRunning */);
1251                    return;
1252                }
1253                setException(convertErrorToException(code, message));
1254            }
1255        }
1256
1257    }
1258
1259    private abstract class BaseFutureTask<T> extends FutureTask<T> {
1260        final public IAccountManagerResponse mResponse;
1261        final Handler mHandler;
1262
1263        public BaseFutureTask(Handler handler) {
1264            super(new Callable<T>() {
1265                public T call() throws Exception {
1266                    throw new IllegalStateException("this should never be called");
1267                }
1268            });
1269            mHandler = handler;
1270            mResponse = new Response();
1271        }
1272
1273        public abstract void doWork() throws RemoteException;
1274
1275        public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
1276
1277        protected void postRunnableToHandler(Runnable runnable) {
1278            Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1279            handler.post(runnable);
1280        }
1281
1282        protected void startTask() {
1283            try {
1284                doWork();
1285            } catch (RemoteException e) {
1286                setException(e);
1287            }
1288        }
1289
1290        protected class Response extends IAccountManagerResponse.Stub {
1291            public void onResult(Bundle bundle) {
1292                try {
1293                    T result = bundleToResult(bundle);
1294                    if (result == null) {
1295                        return;
1296                    }
1297                    set(result);
1298                    return;
1299                } catch (ClassCastException e) {
1300                    // we will set the exception below
1301                } catch (AuthenticatorException e) {
1302                    // we will set the exception below
1303                }
1304                onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
1305            }
1306
1307            public void onError(int code, String message) {
1308                if (code == ERROR_CODE_CANCELED) {
1309                    cancel(true /* mayInterruptIfRunning */);
1310                    return;
1311                }
1312                setException(convertErrorToException(code, message));
1313            }
1314        }
1315    }
1316
1317    private abstract class Future2Task<T>
1318            extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1319        final AccountManagerCallback<T> mCallback;
1320        public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1321            super(handler);
1322            mCallback = callback;
1323        }
1324
1325        protected void done() {
1326            if (mCallback != null) {
1327                postRunnableToHandler(new Runnable() {
1328                    public void run() {
1329                        mCallback.run(Future2Task.this);
1330                    }
1331                });
1332            }
1333        }
1334
1335        public Future2Task<T> start() {
1336            startTask();
1337            return this;
1338        }
1339
1340        private T internalGetResult(Long timeout, TimeUnit unit)
1341                throws OperationCanceledException, IOException, AuthenticatorException {
1342            if (!isDone()) {
1343                ensureNotOnMainThread();
1344            }
1345            try {
1346                if (timeout == null) {
1347                    return get();
1348                } else {
1349                    return get(timeout, unit);
1350                }
1351            } catch (InterruptedException e) {
1352                // fall through and cancel
1353            } catch (TimeoutException e) {
1354                // fall through and cancel
1355            } catch (CancellationException e) {
1356                // fall through and cancel
1357            } catch (ExecutionException e) {
1358                final Throwable cause = e.getCause();
1359                if (cause instanceof IOException) {
1360                    throw (IOException) cause;
1361                } else if (cause instanceof UnsupportedOperationException) {
1362                    throw new AuthenticatorException(cause);
1363                } else if (cause instanceof AuthenticatorException) {
1364                    throw (AuthenticatorException) cause;
1365                } else if (cause instanceof RuntimeException) {
1366                    throw (RuntimeException) cause;
1367                } else if (cause instanceof Error) {
1368                    throw (Error) cause;
1369                } else {
1370                    throw new IllegalStateException(cause);
1371                }
1372            } finally {
1373                cancel(true /* interrupt if running */);
1374            }
1375            throw new OperationCanceledException();
1376        }
1377
1378        public T getResult()
1379                throws OperationCanceledException, IOException, AuthenticatorException {
1380            return internalGetResult(null, null);
1381        }
1382
1383        public T getResult(long timeout, TimeUnit unit)
1384                throws OperationCanceledException, IOException, AuthenticatorException {
1385            return internalGetResult(timeout, unit);
1386        }
1387
1388    }
1389
1390    private Exception convertErrorToException(int code, String message) {
1391        if (code == ERROR_CODE_NETWORK_ERROR) {
1392            return new IOException(message);
1393        }
1394
1395        if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
1396            return new UnsupportedOperationException(message);
1397        }
1398
1399        if (code == ERROR_CODE_INVALID_RESPONSE) {
1400            return new AuthenticatorException(message);
1401        }
1402
1403        if (code == ERROR_CODE_BAD_ARGUMENTS) {
1404            return new IllegalArgumentException(message);
1405        }
1406
1407        return new AuthenticatorException(message);
1408    }
1409
1410    private class GetAuthTokenByTypeAndFeaturesTask
1411            extends AmsTask implements AccountManagerCallback<Bundle> {
1412        GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1413                final String[] features, Activity activityForPrompting,
1414                final Bundle addAccountOptions, final Bundle loginOptions,
1415                AccountManagerCallback<Bundle> callback, Handler handler) {
1416            super(activityForPrompting, handler, callback);
1417            if (accountType == null) throw new IllegalArgumentException("account type is null");
1418            mAccountType = accountType;
1419            mAuthTokenType = authTokenType;
1420            mFeatures = features;
1421            mAddAccountOptions = addAccountOptions;
1422            mLoginOptions = loginOptions;
1423            mMyCallback = this;
1424        }
1425        volatile AccountManagerFuture<Bundle> mFuture = null;
1426        final String mAccountType;
1427        final String mAuthTokenType;
1428        final String[] mFeatures;
1429        final Bundle mAddAccountOptions;
1430        final Bundle mLoginOptions;
1431        final AccountManagerCallback<Bundle> mMyCallback;
1432
1433        public void doWork() throws RemoteException {
1434            getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1435                    new AccountManagerCallback<Account[]>() {
1436                        public void run(AccountManagerFuture<Account[]> future) {
1437                            Account[] accounts;
1438                            try {
1439                                accounts = future.getResult();
1440                            } catch (OperationCanceledException e) {
1441                                setException(e);
1442                                return;
1443                            } catch (IOException e) {
1444                                setException(e);
1445                                return;
1446                            } catch (AuthenticatorException e) {
1447                                setException(e);
1448                                return;
1449                            }
1450
1451                            if (accounts.length == 0) {
1452                                if (mActivity != null) {
1453                                    // no accounts, add one now. pretend that the user directly
1454                                    // made this request
1455                                    mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1456                                            mAddAccountOptions, mActivity, mMyCallback, mHandler);
1457                                } else {
1458                                    // send result since we can't prompt to add an account
1459                                    Bundle result = new Bundle();
1460                                    result.putString(KEY_ACCOUNT_NAME, null);
1461                                    result.putString(KEY_ACCOUNT_TYPE, null);
1462                                    result.putString(KEY_AUTHTOKEN, null);
1463                                    try {
1464                                        mResponse.onResult(result);
1465                                    } catch (RemoteException e) {
1466                                        // this will never happen
1467                                    }
1468                                    // we are done
1469                                }
1470                            } else if (accounts.length == 1) {
1471                                // have a single account, return an authtoken for it
1472                                if (mActivity == null) {
1473                                    mFuture = getAuthToken(accounts[0], mAuthTokenType,
1474                                            false /* notifyAuthFailure */, mMyCallback, mHandler);
1475                                } else {
1476                                    mFuture = getAuthToken(accounts[0],
1477                                            mAuthTokenType, mLoginOptions,
1478                                            mActivity, mMyCallback, mHandler);
1479                                }
1480                            } else {
1481                                if (mActivity != null) {
1482                                    IAccountManagerResponse chooseResponse =
1483                                            new IAccountManagerResponse.Stub() {
1484                                        public void onResult(Bundle value) throws RemoteException {
1485                                            Account account = new Account(
1486                                                    value.getString(KEY_ACCOUNT_NAME),
1487                                                    value.getString(KEY_ACCOUNT_TYPE));
1488                                            mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1489                                                    mActivity, mMyCallback, mHandler);
1490                                        }
1491
1492                                        public void onError(int errorCode, String errorMessage)
1493                                                throws RemoteException {
1494                                            mResponse.onError(errorCode, errorMessage);
1495                                        }
1496                                    };
1497                                    // have many accounts, launch the chooser
1498                                    Intent intent = new Intent();
1499                                    intent.setClassName("android",
1500                                            "android.accounts.ChooseAccountActivity");
1501                                    intent.putExtra(KEY_ACCOUNTS, accounts);
1502                                    intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
1503                                            new AccountManagerResponse(chooseResponse));
1504                                    mActivity.startActivity(intent);
1505                                    // the result will arrive via the IAccountManagerResponse
1506                                } else {
1507                                    // send result since we can't prompt to select an account
1508                                    Bundle result = new Bundle();
1509                                    result.putString(KEY_ACCOUNTS, null);
1510                                    try {
1511                                        mResponse.onResult(result);
1512                                    } catch (RemoteException e) {
1513                                        // this will never happen
1514                                    }
1515                                    // we are done
1516                                }
1517                            }
1518                        }}, mHandler);
1519        }
1520
1521        public void run(AccountManagerFuture<Bundle> future) {
1522            try {
1523                set(future.getResult());
1524            } catch (OperationCanceledException e) {
1525                cancel(true /* mayInterruptIfRUnning */);
1526            } catch (IOException e) {
1527                setException(e);
1528            } catch (AuthenticatorException e) {
1529                setException(e);
1530            }
1531        }
1532    }
1533
1534    /**
1535     * This convenience helper combines the functionality of
1536     * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1537     * {@link #addAccount}.
1538     *
1539     * <p>This method gets a list of the accounts matching the
1540     * specified type and feature set; if there is exactly one, it is
1541     * used; if there are more than one, the user is prompted to pick one;
1542     * if there are none, the user is prompted to add one.  Finally,
1543     * an auth token is acquired for the chosen account.
1544     *
1545     * <p>This method may be called from any thread, but the returned
1546     * {@link AccountManagerFuture} must not be used on the main thread.
1547     *
1548     * <p>This method requires the caller to hold the permission
1549     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1550     *
1551     * @param accountType The account type required
1552     *     (see {@link getAccountsByType}), must not be null
1553     * @param authTokenType The desired auth token type
1554     *     (see {@link #getAuthToken}), must not be null
1555     * @param features Required features for the account
1556     *     (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1557     * @param activity The {@link Activity} context to use for launching new
1558     *     sub-Activities to prompt to add an account, select an account,
1559     *     and/or enter a password, as necessary; used only to call
1560     *     startActivity(); should not be null
1561     * @param addAccountOptions Authenticator-specific options to use for
1562     *     adding new accounts; may be null or empty
1563     * @param getAuthTokenOptions Authenticator-specific options to use for
1564     *     getting auth tokens; may be null or empty
1565     * @param callback Callback to invoke when the request completes,
1566     *     null for no callback
1567     * @param handler {@link Handler} identifying the callback thread,
1568     *     null for the main thread
1569     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1570     *     at least the following fields:
1571     * <ul>
1572     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1573     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1574     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1575     * </ul>
1576     *
1577     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1578     * <ul>
1579     * <li> {@link AuthenticatorException} if no authenticator was registered for
1580     *      this account type or the authenticator failed to respond
1581     * <li> {@link OperationCanceledException} if the operation was canceled for
1582     *      any reason, including the user canceling any operation
1583     * <li> {@link IOException} if the authenticator experienced an I/O problem
1584     *      updating settings, usually because of network trouble
1585     * </ul>
1586     */
1587    public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
1588            final String accountType, final String authTokenType, final String[] features,
1589            final Activity activity, final Bundle addAccountOptions,
1590            final Bundle getAuthTokenOptions,
1591            final AccountManagerCallback<Bundle> callback, final Handler handler) {
1592        if (accountType == null) throw new IllegalArgumentException("account type is null");
1593        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1594        final GetAuthTokenByTypeAndFeaturesTask task =
1595                new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
1596                activity, addAccountOptions, getAuthTokenOptions, callback, handler);
1597        task.start();
1598        return task;
1599    }
1600
1601    private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
1602            Maps.newHashMap();
1603
1604    /**
1605     * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1606     * so that it can read the updated list of accounts and send them to the listener
1607     * in mAccountsUpdatedListeners.
1608     */
1609    private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1610        public void onReceive(final Context context, final Intent intent) {
1611            final Account[] accounts = getAccounts();
1612            // send the result to the listeners
1613            synchronized (mAccountsUpdatedListeners) {
1614                for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
1615                        mAccountsUpdatedListeners.entrySet()) {
1616                    postToHandler(entry.getValue(), entry.getKey(), accounts);
1617                }
1618            }
1619        }
1620    };
1621
1622    /**
1623     * Adds an {@link OnAccountsUpdateListener} to this instance of the
1624     * {@link AccountManager}.  This listener will be notified whenever the
1625     * list of accounts on the device changes.
1626     *
1627     * <p>As long as this listener is present, the AccountManager instance
1628     * will not be garbage-collected, and neither will the {@link Context}
1629     * used to retrieve it, which may be a large Activity instance.  To avoid
1630     * memory leaks, you must remove this listener before then.  Normally
1631     * listeners are added in an Activity or Service's {@link Activity#onCreate}
1632     * and removed in {@link Activity#onDestroy}.
1633     *
1634     * <p>It is safe to call this method from the main thread.
1635     *
1636     * <p>No permission is required to call this method.
1637     *
1638     * @param listener The listener to send notifications to
1639     * @param handler {@link Handler} identifying the thread to use
1640     *     for notifications, null for the main thread
1641     * @param updateImmediately If true, the listener will be invoked
1642     *     (on the handler thread) right away with the current account list
1643     * @throws IllegalArgumentException if listener is null
1644     * @throws IllegalStateException if listener was already added
1645     */
1646    public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
1647            Handler handler, boolean updateImmediately) {
1648        if (listener == null) {
1649            throw new IllegalArgumentException("the listener is null");
1650        }
1651        synchronized (mAccountsUpdatedListeners) {
1652            if (mAccountsUpdatedListeners.containsKey(listener)) {
1653                throw new IllegalStateException("this listener is already added");
1654            }
1655            final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
1656
1657            mAccountsUpdatedListeners.put(listener, handler);
1658
1659            if (wasEmpty) {
1660                // Register a broadcast receiver to monitor account changes
1661                IntentFilter intentFilter = new IntentFilter();
1662                intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
1663                // To recover from disk-full.
1664                intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1665                mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
1666            }
1667        }
1668
1669        if (updateImmediately) {
1670            postToHandler(handler, listener, getAccounts());
1671        }
1672    }
1673
1674    /**
1675     * Removes an {@link OnAccountsUpdateListener} previously registered with
1676     * {@link #addOnAccountsUpdatedListener}.  The listener will no longer
1677     * receive notifications of account changes.
1678     *
1679     * <p>It is safe to call this method from the main thread.
1680     *
1681     * <p>No permission is required to call this method.
1682     *
1683     * @param listener The previously added listener to remove
1684     * @throws IllegalArgumentException if listener is null
1685     * @throws IllegalStateException if listener was not already added
1686     */
1687    public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
1688        if (listener == null) {
1689            Log.e(TAG, "Missing listener");
1690            return;
1691        }
1692        synchronized (mAccountsUpdatedListeners) {
1693            if (!mAccountsUpdatedListeners.containsKey(listener)) {
1694                Log.e(TAG, "Listener was not previously added");
1695                return;
1696            }
1697            mAccountsUpdatedListeners.remove(listener);
1698            if (mAccountsUpdatedListeners.isEmpty()) {
1699                mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
1700            }
1701        }
1702    }
1703}
1704