AccountManager.java revision ff592dc2fa53d48e4121d9b8fd70efc19938c4a1
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 notifyAuthFailure True to add a notification to prompt the
817     *     user for a password if necessary, false to leave that to the caller
818     * @param callback Callback to invoke when the request completes,
819     *     null for no callback
820     * @param handler {@link Handler} identifying the callback thread,
821     *     null for the main thread
822     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
823     *     at least the following fields on success:
824     * <ul>
825     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
826     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
827     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
828     * </ul>
829     *
830     * (Other authenticator-specific values may be returned.)  If the user
831     * must enter credentials, the returned Bundle contains only
832     * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
833     *
834     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
835     * <ul>
836     * <li> {@link AuthenticatorException} if the authenticator failed to respond
837     * <li> {@link OperationCanceledException} if the operation is canceled for
838     *      any reason, incluidng the user canceling a credential request
839     * <li> {@link IOException} if the authenticator experienced an I/O problem
840     *      creating a new auth token, usually because of network trouble
841     * </ul>
842     */
843    public AccountManagerFuture<Bundle> getAuthToken(
844            final Account account, final String authTokenType, final boolean notifyAuthFailure,
845            AccountManagerCallback<Bundle> callback, Handler handler) {
846        if (account == null) throw new IllegalArgumentException("account is null");
847        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
848        return new AmsTask(null, handler, callback) {
849            public void doWork() throws RemoteException {
850                mService.getAuthToken(mResponse, account, authTokenType,
851                        notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
852            }
853        }.start();
854    }
855
856    /**
857     * Asks the user to add an account of a specified type.  The authenticator
858     * for this account type processes this request with the appropriate user
859     * interface.  If the user does elect to create a new account, the account
860     * name is returned.
861     *
862     * <p>This method may be called from any thread, but the returned
863     * {@link AccountManagerFuture} must not be used on the main thread.
864     *
865     * <p>This method requires the caller to hold the permission
866     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
867     *
868     * @param accountType The type of account to add; must not be null
869     * @param authTokenType The type of auth token (see {@link #getAuthToken})
870     *     this account will need to be able to generate, null for none
871     * @param requiredFeatures The features (see {@link #hasFeatures}) this
872     *     account must have, null for none
873     * @param addAccountOptions Authenticator-specific options for the request,
874     *     may be null or empty
875     * @param activity The {@link Activity} context to use for launching a new
876     *     authenticator-defined sub-Activity to prompt the user to create an
877     *     account; used only to call startActivity(); if null, the prompt
878     *     will not be launched directly, but the necessary {@link Intent}
879     *     will be returned to the caller instead
880     * @param callback Callback to invoke when the request completes,
881     *     null for no callback
882     * @param handler {@link Handler} identifying the callback thread,
883     *     null for the main thread
884     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
885     *     these fields if activity was specified and an account was created:
886     * <ul>
887     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
888     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
889     * </ul>
890     *
891     * If no activity was specified, the returned Bundle contains only
892     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
893     * actual account creation process.
894     *
895     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
896     * <ul>
897     * <li> {@link AuthenticatorException} if no authenticator was registered for
898     *      this account type or the authenticator failed to respond
899     * <li> {@link OperationCanceledException} if the operation was canceled for
900     *      any reason, including the user canceling the creation process
901     * <li> {@link IOException} if the authenticator experienced an I/O problem
902     *      creating a new account, usually because of network trouble
903     * </ul>
904     */
905    public AccountManagerFuture<Bundle> addAccount(final String accountType,
906            final String authTokenType, final String[] requiredFeatures,
907            final Bundle addAccountOptions,
908            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
909        return new AmsTask(activity, handler, callback) {
910            public void doWork() throws RemoteException {
911                if (accountType == null) {
912                    Log.e(TAG, "the account must not be null");
913                    // to unblock caller waiting on Future.get()
914                    set(new Bundle());
915                    return;
916                }
917                mService.addAcount(mResponse, accountType, authTokenType,
918                        requiredFeatures, activity != null, addAccountOptions);
919            }
920        }.start();
921    }
922
923    /**
924     * Confirms that the user knows the password for an account to make extra
925     * sure they are the owner of the account.  The user-entered password can
926     * be supplied directly, otherwise the authenticator for this account type
927     * prompts the user with the appropriate interface.  This method is
928     * intended for applications which want extra assurance; for example, the
929     * phone lock screen uses this to let the user unlock the phone with an
930     * account password if they forget the lock pattern.
931     *
932     * <p>If the user-entered password matches a saved password for this
933     * account, the request is considered valid; otherwise the authenticator
934     * verifies the password (usually by contacting the server).
935     *
936     * <p>This method may be called from any thread, but the returned
937     * {@link AccountManagerFuture} must not be used on the main thread.
938     *
939     * <p>This method requires the caller to hold the permission
940     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
941     *
942     * @param account The account to confirm password knowledge for
943     * @param options Authenticator-specific options for the request;
944     *     if the {@link #KEY_PASSWORD} string field is present, the
945     *     authenticator may use it directly rather than prompting the user;
946     *     may be null or empty
947     * @param activity The {@link Activity} context to use for launching a new
948     *     authenticator-defined sub-Activity to prompt the user to enter a
949     *     password; used only to call startActivity(); if null, the prompt
950     *     will not be launched directly, but the necessary {@link Intent}
951     *     will be returned to the caller instead
952     * @param callback Callback to invoke when the request completes,
953     *     null for no callback
954     * @param handler {@link Handler} identifying the callback thread,
955     *     null for the main thread
956     * @return An {@link AccountManagerFuture} which resolves to a Bundle
957     *     with these fields if activity or password was supplied and
958     *     the account was successfully verified:
959     * <ul>
960     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
961     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
962     * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
963     * </ul>
964     *
965     * If no activity or password was specified, the returned Bundle contains
966     * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
967     * password prompt.
968     *
969     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
970     * <ul>
971     * <li> {@link AuthenticatorException} if the authenticator failed to respond
972     * <li> {@link OperationCanceledException} if the operation was canceled for
973     *      any reason, including the user canceling the password prompt
974     * <li> {@link IOException} if the authenticator experienced an I/O problem
975     *      verifying the password, usually because of network trouble
976     * </ul>
977     */
978    public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
979            final Bundle options,
980            final Activity activity,
981            final AccountManagerCallback<Bundle> callback,
982            final Handler handler) {
983        return new AmsTask(activity, handler, callback) {
984            public void doWork() throws RemoteException {
985                mService.confirmCredentials(mResponse, account, options, activity != null);
986            }
987        }.start();
988    }
989
990    /**
991     * Asks the user to enter a new password for an account, updating the
992     * saved credentials for the account.  Normally this happens automatically
993     * when the server rejects credentials during an auth token fetch, but this
994     * can be invoked directly to ensure we have the correct credentials stored.
995     *
996     * <p>This method may be called from any thread, but the returned
997     * {@link AccountManagerFuture} must not be used on the main thread.
998     *
999     * <p>This method requires the caller to hold the permission
1000     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1001     *
1002     * @param account The account to update credentials for
1003     * @param authTokenType The credentials entered must allow an auth token
1004     *     of this type to be created (but no actual auth token is returned);
1005     *     may be null
1006     * @param options Authenticator-specific options for the request;
1007     *     may be null or empty
1008     * @param activity The {@link Activity} context to use for launching a new
1009     *     authenticator-defined sub-Activity to prompt the user to enter a
1010     *     password; used only to call startActivity(); if null, the prompt
1011     *     will not be launched directly, but the necessary {@link Intent}
1012     *     will be returned to the caller instead
1013     * @param callback Callback to invoke when the request completes,
1014     *     null for no callback
1015     * @param handler {@link Handler} identifying the callback thread,
1016     *     null for the main thread
1017     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1018     *     with these fields if an activity was supplied and the account
1019     *     credentials were successfully updated:
1020     * <ul>
1021     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1022     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1023     * </ul>
1024     *
1025     * If no activity was specified, the returned Bundle contains only
1026     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1027     * password prompt.
1028     *
1029     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1030     * <ul>
1031     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1032     * <li> {@link OperationCanceledException} if the operation was canceled for
1033     *      any reason, including the user canceling the password prompt
1034     * <li> {@link IOException} if the authenticator experienced an I/O problem
1035     *      verifying the password, usually because of network trouble
1036     * </ul>
1037     */
1038    public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1039            final String authTokenType,
1040            final Bundle options, final Activity activity,
1041            final AccountManagerCallback<Bundle> callback,
1042            final Handler handler) {
1043        return new AmsTask(activity, handler, callback) {
1044            public void doWork() throws RemoteException {
1045                mService.updateCredentials(mResponse, account, authTokenType, activity != null,
1046                        options);
1047            }
1048        }.start();
1049    }
1050
1051    /**
1052     * Offers the user an opportunity to change an authenticator's settings.
1053     * These properties are for the authenticator in general, not a particular
1054     * account.  Not all authenticators support this method.
1055     *
1056     * <p>This method may be called from any thread, but the returned
1057     * {@link AccountManagerFuture} must not be used on the main thread.
1058     *
1059     * <p>This method requires the caller to hold the permission
1060     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1061     *
1062     * @param accountType The account type associated with the authenticator
1063     *     to adjust
1064     * @param activity The {@link Activity} context to use for launching a new
1065     *     authenticator-defined sub-Activity to adjust authenticator settings;
1066     *     used only to call startActivity(); if null, the settings dialog will
1067     *     not be launched directly, but the necessary {@link Intent} will be
1068     *     returned to the caller instead
1069     * @param callback Callback to invoke when the request completes,
1070     *     null for no callback
1071     * @param handler {@link Handler} identifying the callback thread,
1072     *     null for the main thread
1073     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1074     *     which is empty if properties were edited successfully, or
1075     *     if no activity was specified, contains only {@link #KEY_INTENT}
1076     *     needed to launch the authenticator's settings dialog.
1077     *
1078     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1079     * <ul>
1080     * <li> {@link AuthenticatorException} if no authenticator was registered for
1081     *      this account type or the authenticator failed to respond
1082     * <li> {@link OperationCanceledException} if the operation was canceled for
1083     *      any reason, including the user canceling the settings dialog
1084     * <li> {@link IOException} if the authenticator experienced an I/O problem
1085     *      updating settings, usually because of network trouble
1086     * </ul>
1087     */
1088    public AccountManagerFuture<Bundle> editProperties(final String accountType,
1089            final Activity activity, final AccountManagerCallback<Bundle> callback,
1090            final Handler handler) {
1091        return new AmsTask(activity, handler, callback) {
1092            public void doWork() throws RemoteException {
1093                mService.editProperties(mResponse, accountType, activity != null);
1094            }
1095        }.start();
1096    }
1097
1098    private void ensureNotOnMainThread() {
1099        final Looper looper = Looper.myLooper();
1100        if (looper != null && looper == mContext.getMainLooper()) {
1101            final IllegalStateException exception = new IllegalStateException(
1102                    "calling this from your main thread can lead to deadlock");
1103            Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1104                    exception);
1105            if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1106                throw exception;
1107            }
1108        }
1109    }
1110
1111    private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1112            final AccountManagerFuture<Bundle> future) {
1113        handler = handler == null ? mMainHandler : handler;
1114        handler.post(new Runnable() {
1115            public void run() {
1116                callback.run(future);
1117            }
1118        });
1119    }
1120
1121    private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
1122            final Account[] accounts) {
1123        final Account[] accountsCopy = new Account[accounts.length];
1124        // send a copy to make sure that one doesn't
1125        // change what another sees
1126        System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1127        handler = (handler == null) ? mMainHandler : handler;
1128        handler.post(new Runnable() {
1129            public void run() {
1130                try {
1131                    listener.onAccountsUpdated(accountsCopy);
1132                } catch (SQLException e) {
1133                    // Better luck next time.  If the problem was disk-full,
1134                    // the STORAGE_OK intent will re-trigger the update.
1135                    Log.e(TAG, "Can't update accounts", e);
1136                }
1137            }
1138        });
1139    }
1140
1141    private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
1142        final IAccountManagerResponse mResponse;
1143        final Handler mHandler;
1144        final AccountManagerCallback<Bundle> mCallback;
1145        final Activity mActivity;
1146        public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
1147            super(new Callable<Bundle>() {
1148                public Bundle call() throws Exception {
1149                    throw new IllegalStateException("this should never be called");
1150                }
1151            });
1152
1153            mHandler = handler;
1154            mCallback = callback;
1155            mActivity = activity;
1156            mResponse = new Response();
1157        }
1158
1159        public final AccountManagerFuture<Bundle> start() {
1160            try {
1161                doWork();
1162            } catch (RemoteException e) {
1163                setException(e);
1164            }
1165            return this;
1166        }
1167
1168        public abstract void doWork() throws RemoteException;
1169
1170        private Bundle internalGetResult(Long timeout, TimeUnit unit)
1171                throws OperationCanceledException, IOException, AuthenticatorException {
1172            if (!isDone()) {
1173                ensureNotOnMainThread();
1174            }
1175            try {
1176                if (timeout == null) {
1177                    return get();
1178                } else {
1179                    return get(timeout, unit);
1180                }
1181            } catch (CancellationException e) {
1182                throw new OperationCanceledException();
1183            } catch (TimeoutException e) {
1184                // fall through and cancel
1185            } catch (InterruptedException e) {
1186                // fall through and cancel
1187            } catch (ExecutionException e) {
1188                final Throwable cause = e.getCause();
1189                if (cause instanceof IOException) {
1190                    throw (IOException) cause;
1191                } else if (cause instanceof UnsupportedOperationException) {
1192                    throw new AuthenticatorException(cause);
1193                } else if (cause instanceof AuthenticatorException) {
1194                    throw (AuthenticatorException) cause;
1195                } else if (cause instanceof RuntimeException) {
1196                    throw (RuntimeException) cause;
1197                } else if (cause instanceof Error) {
1198                    throw (Error) cause;
1199                } else {
1200                    throw new IllegalStateException(cause);
1201                }
1202            } finally {
1203                cancel(true /* interrupt if running */);
1204            }
1205            throw new OperationCanceledException();
1206        }
1207
1208        public Bundle getResult()
1209                throws OperationCanceledException, IOException, AuthenticatorException {
1210            return internalGetResult(null, null);
1211        }
1212
1213        public Bundle getResult(long timeout, TimeUnit unit)
1214                throws OperationCanceledException, IOException, AuthenticatorException {
1215            return internalGetResult(timeout, unit);
1216        }
1217
1218        protected void done() {
1219            if (mCallback != null) {
1220                postToHandler(mHandler, mCallback, this);
1221            }
1222        }
1223
1224        /** Handles the responses from the AccountManager */
1225        private class Response extends IAccountManagerResponse.Stub {
1226            public void onResult(Bundle bundle) {
1227                Intent intent = bundle.getParcelable("intent");
1228                if (intent != null && mActivity != null) {
1229                    // since the user provided an Activity we will silently start intents
1230                    // that we see
1231                    mActivity.startActivity(intent);
1232                    // leave the Future running to wait for the real response to this request
1233                } else if (bundle.getBoolean("retry")) {
1234                    try {
1235                        doWork();
1236                    } catch (RemoteException e) {
1237                        // this will only happen if the system process is dead, which means
1238                        // we will be dying ourselves
1239                    }
1240                } else {
1241                    set(bundle);
1242                }
1243            }
1244
1245            public void onError(int code, String message) {
1246                if (code == ERROR_CODE_CANCELED) {
1247                    // the authenticator indicated that this request was canceled, do so now
1248                    cancel(true /* mayInterruptIfRunning */);
1249                    return;
1250                }
1251                setException(convertErrorToException(code, message));
1252            }
1253        }
1254
1255    }
1256
1257    private abstract class BaseFutureTask<T> extends FutureTask<T> {
1258        final public IAccountManagerResponse mResponse;
1259        final Handler mHandler;
1260
1261        public BaseFutureTask(Handler handler) {
1262            super(new Callable<T>() {
1263                public T call() throws Exception {
1264                    throw new IllegalStateException("this should never be called");
1265                }
1266            });
1267            mHandler = handler;
1268            mResponse = new Response();
1269        }
1270
1271        public abstract void doWork() throws RemoteException;
1272
1273        public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
1274
1275        protected void postRunnableToHandler(Runnable runnable) {
1276            Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1277            handler.post(runnable);
1278        }
1279
1280        protected void startTask() {
1281            try {
1282                doWork();
1283            } catch (RemoteException e) {
1284                setException(e);
1285            }
1286        }
1287
1288        protected class Response extends IAccountManagerResponse.Stub {
1289            public void onResult(Bundle bundle) {
1290                try {
1291                    T result = bundleToResult(bundle);
1292                    if (result == null) {
1293                        return;
1294                    }
1295                    set(result);
1296                    return;
1297                } catch (ClassCastException e) {
1298                    // we will set the exception below
1299                } catch (AuthenticatorException e) {
1300                    // we will set the exception below
1301                }
1302                onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
1303            }
1304
1305            public void onError(int code, String message) {
1306                if (code == ERROR_CODE_CANCELED) {
1307                    cancel(true /* mayInterruptIfRunning */);
1308                    return;
1309                }
1310                setException(convertErrorToException(code, message));
1311            }
1312        }
1313    }
1314
1315    private abstract class Future2Task<T>
1316            extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1317        final AccountManagerCallback<T> mCallback;
1318        public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1319            super(handler);
1320            mCallback = callback;
1321        }
1322
1323        protected void done() {
1324            if (mCallback != null) {
1325                postRunnableToHandler(new Runnable() {
1326                    public void run() {
1327                        mCallback.run(Future2Task.this);
1328                    }
1329                });
1330            }
1331        }
1332
1333        public Future2Task<T> start() {
1334            startTask();
1335            return this;
1336        }
1337
1338        private T internalGetResult(Long timeout, TimeUnit unit)
1339                throws OperationCanceledException, IOException, AuthenticatorException {
1340            if (!isDone()) {
1341                ensureNotOnMainThread();
1342            }
1343            try {
1344                if (timeout == null) {
1345                    return get();
1346                } else {
1347                    return get(timeout, unit);
1348                }
1349            } catch (InterruptedException e) {
1350                // fall through and cancel
1351            } catch (TimeoutException e) {
1352                // fall through and cancel
1353            } catch (CancellationException e) {
1354                // fall through and cancel
1355            } catch (ExecutionException e) {
1356                final Throwable cause = e.getCause();
1357                if (cause instanceof IOException) {
1358                    throw (IOException) cause;
1359                } else if (cause instanceof UnsupportedOperationException) {
1360                    throw new AuthenticatorException(cause);
1361                } else if (cause instanceof AuthenticatorException) {
1362                    throw (AuthenticatorException) cause;
1363                } else if (cause instanceof RuntimeException) {
1364                    throw (RuntimeException) cause;
1365                } else if (cause instanceof Error) {
1366                    throw (Error) cause;
1367                } else {
1368                    throw new IllegalStateException(cause);
1369                }
1370            } finally {
1371                cancel(true /* interrupt if running */);
1372            }
1373            throw new OperationCanceledException();
1374        }
1375
1376        public T getResult()
1377                throws OperationCanceledException, IOException, AuthenticatorException {
1378            return internalGetResult(null, null);
1379        }
1380
1381        public T getResult(long timeout, TimeUnit unit)
1382                throws OperationCanceledException, IOException, AuthenticatorException {
1383            return internalGetResult(timeout, unit);
1384        }
1385
1386    }
1387
1388    private Exception convertErrorToException(int code, String message) {
1389        if (code == ERROR_CODE_NETWORK_ERROR) {
1390            return new IOException(message);
1391        }
1392
1393        if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
1394            return new UnsupportedOperationException(message);
1395        }
1396
1397        if (code == ERROR_CODE_INVALID_RESPONSE) {
1398            return new AuthenticatorException(message);
1399        }
1400
1401        if (code == ERROR_CODE_BAD_ARGUMENTS) {
1402            return new IllegalArgumentException(message);
1403        }
1404
1405        return new AuthenticatorException(message);
1406    }
1407
1408    private class GetAuthTokenByTypeAndFeaturesTask
1409            extends AmsTask implements AccountManagerCallback<Bundle> {
1410        GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1411                final String[] features, Activity activityForPrompting,
1412                final Bundle addAccountOptions, final Bundle loginOptions,
1413                AccountManagerCallback<Bundle> callback, Handler handler) {
1414            super(activityForPrompting, handler, callback);
1415            if (accountType == null) throw new IllegalArgumentException("account type is null");
1416            mAccountType = accountType;
1417            mAuthTokenType = authTokenType;
1418            mFeatures = features;
1419            mAddAccountOptions = addAccountOptions;
1420            mLoginOptions = loginOptions;
1421            mMyCallback = this;
1422        }
1423        volatile AccountManagerFuture<Bundle> mFuture = null;
1424        final String mAccountType;
1425        final String mAuthTokenType;
1426        final String[] mFeatures;
1427        final Bundle mAddAccountOptions;
1428        final Bundle mLoginOptions;
1429        final AccountManagerCallback<Bundle> mMyCallback;
1430
1431        public void doWork() throws RemoteException {
1432            getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1433                    new AccountManagerCallback<Account[]>() {
1434                        public void run(AccountManagerFuture<Account[]> future) {
1435                            Account[] accounts;
1436                            try {
1437                                accounts = future.getResult();
1438                            } catch (OperationCanceledException e) {
1439                                setException(e);
1440                                return;
1441                            } catch (IOException e) {
1442                                setException(e);
1443                                return;
1444                            } catch (AuthenticatorException e) {
1445                                setException(e);
1446                                return;
1447                            }
1448
1449                            if (accounts.length == 0) {
1450                                if (mActivity != null) {
1451                                    // no accounts, add one now. pretend that the user directly
1452                                    // made this request
1453                                    mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1454                                            mAddAccountOptions, mActivity, mMyCallback, mHandler);
1455                                } else {
1456                                    // send result since we can't prompt to add an account
1457                                    Bundle result = new Bundle();
1458                                    result.putString(KEY_ACCOUNT_NAME, null);
1459                                    result.putString(KEY_ACCOUNT_TYPE, null);
1460                                    result.putString(KEY_AUTHTOKEN, null);
1461                                    try {
1462                                        mResponse.onResult(result);
1463                                    } catch (RemoteException e) {
1464                                        // this will never happen
1465                                    }
1466                                    // we are done
1467                                }
1468                            } else if (accounts.length == 1) {
1469                                // have a single account, return an authtoken for it
1470                                if (mActivity == null) {
1471                                    mFuture = getAuthToken(accounts[0], mAuthTokenType,
1472                                            false /* notifyAuthFailure */, mMyCallback, mHandler);
1473                                } else {
1474                                    mFuture = getAuthToken(accounts[0],
1475                                            mAuthTokenType, mLoginOptions,
1476                                            mActivity, mMyCallback, mHandler);
1477                                }
1478                            } else {
1479                                if (mActivity != null) {
1480                                    IAccountManagerResponse chooseResponse =
1481                                            new IAccountManagerResponse.Stub() {
1482                                        public void onResult(Bundle value) throws RemoteException {
1483                                            Account account = new Account(
1484                                                    value.getString(KEY_ACCOUNT_NAME),
1485                                                    value.getString(KEY_ACCOUNT_TYPE));
1486                                            mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1487                                                    mActivity, mMyCallback, mHandler);
1488                                        }
1489
1490                                        public void onError(int errorCode, String errorMessage)
1491                                                throws RemoteException {
1492                                            mResponse.onError(errorCode, errorMessage);
1493                                        }
1494                                    };
1495                                    // have many accounts, launch the chooser
1496                                    Intent intent = new Intent();
1497                                    intent.setClassName("android",
1498                                            "android.accounts.ChooseAccountActivity");
1499                                    intent.putExtra(KEY_ACCOUNTS, accounts);
1500                                    intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
1501                                            new AccountManagerResponse(chooseResponse));
1502                                    mActivity.startActivity(intent);
1503                                    // the result will arrive via the IAccountManagerResponse
1504                                } else {
1505                                    // send result since we can't prompt to select an account
1506                                    Bundle result = new Bundle();
1507                                    result.putString(KEY_ACCOUNTS, null);
1508                                    try {
1509                                        mResponse.onResult(result);
1510                                    } catch (RemoteException e) {
1511                                        // this will never happen
1512                                    }
1513                                    // we are done
1514                                }
1515                            }
1516                        }}, mHandler);
1517        }
1518
1519        public void run(AccountManagerFuture<Bundle> future) {
1520            try {
1521                set(future.getResult());
1522            } catch (OperationCanceledException e) {
1523                cancel(true /* mayInterruptIfRUnning */);
1524            } catch (IOException e) {
1525                setException(e);
1526            } catch (AuthenticatorException e) {
1527                setException(e);
1528            }
1529        }
1530    }
1531
1532    /**
1533     * This convenience helper combines the functionality of
1534     * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1535     * {@link #addAccount}.
1536     *
1537     * <p>This method gets a list of the accounts matching the
1538     * specified type and feature set; if there is exactly one, it is
1539     * used; if there are more than one, the user is prompted to pick one;
1540     * if there are none, the user is prompted to add one.  Finally,
1541     * an auth token is acquired for the chosen account.
1542     *
1543     * <p>This method may be called from any thread, but the returned
1544     * {@link AccountManagerFuture} must not be used on the main thread.
1545     *
1546     * <p>This method requires the caller to hold the permission
1547     * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1548     *
1549     * @param accountType The account type required
1550     *     (see {@link #getAccountsByType}), must not be null
1551     * @param authTokenType The desired auth token type
1552     *     (see {@link #getAuthToken}), must not be null
1553     * @param features Required features for the account
1554     *     (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1555     * @param activity The {@link Activity} context to use for launching new
1556     *     sub-Activities to prompt to add an account, select an account,
1557     *     and/or enter a password, as necessary; used only to call
1558     *     startActivity(); should not be null
1559     * @param addAccountOptions Authenticator-specific options to use for
1560     *     adding new accounts; may be null or empty
1561     * @param getAuthTokenOptions Authenticator-specific options to use for
1562     *     getting auth tokens; may be null or empty
1563     * @param callback Callback to invoke when the request completes,
1564     *     null for no callback
1565     * @param handler {@link Handler} identifying the callback thread,
1566     *     null for the main thread
1567     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1568     *     at least the following fields:
1569     * <ul>
1570     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1571     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1572     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1573     * </ul>
1574     *
1575     * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1576     * <ul>
1577     * <li> {@link AuthenticatorException} if no authenticator was registered for
1578     *      this account type or the authenticator failed to respond
1579     * <li> {@link OperationCanceledException} if the operation was canceled for
1580     *      any reason, including the user canceling any operation
1581     * <li> {@link IOException} if the authenticator experienced an I/O problem
1582     *      updating settings, usually because of network trouble
1583     * </ul>
1584     */
1585    public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
1586            final String accountType, final String authTokenType, final String[] features,
1587            final Activity activity, final Bundle addAccountOptions,
1588            final Bundle getAuthTokenOptions,
1589            final AccountManagerCallback<Bundle> callback, final Handler handler) {
1590        if (accountType == null) throw new IllegalArgumentException("account type is null");
1591        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1592        final GetAuthTokenByTypeAndFeaturesTask task =
1593                new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
1594                activity, addAccountOptions, getAuthTokenOptions, callback, handler);
1595        task.start();
1596        return task;
1597    }
1598
1599    private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
1600            Maps.newHashMap();
1601
1602    /**
1603     * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1604     * so that it can read the updated list of accounts and send them to the listener
1605     * in mAccountsUpdatedListeners.
1606     */
1607    private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1608        public void onReceive(final Context context, final Intent intent) {
1609            final Account[] accounts = getAccounts();
1610            // send the result to the listeners
1611            synchronized (mAccountsUpdatedListeners) {
1612                for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
1613                        mAccountsUpdatedListeners.entrySet()) {
1614                    postToHandler(entry.getValue(), entry.getKey(), accounts);
1615                }
1616            }
1617        }
1618    };
1619
1620    /**
1621     * Adds an {@link OnAccountsUpdateListener} to this instance of the
1622     * {@link AccountManager}.  This listener will be notified whenever the
1623     * list of accounts on the device changes.
1624     *
1625     * <p>As long as this listener is present, the AccountManager instance
1626     * will not be garbage-collected, and neither will the {@link Context}
1627     * used to retrieve it, which may be a large Activity instance.  To avoid
1628     * memory leaks, you must remove this listener before then.  Normally
1629     * listeners are added in an Activity or Service's {@link Activity#onCreate}
1630     * and removed in {@link Activity#onDestroy}.
1631     *
1632     * <p>It is safe to call this method from the main thread.
1633     *
1634     * <p>No permission is required to call this method.
1635     *
1636     * @param listener The listener to send notifications to
1637     * @param handler {@link Handler} identifying the thread to use
1638     *     for notifications, null for the main thread
1639     * @param updateImmediately If true, the listener will be invoked
1640     *     (on the handler thread) right away with the current account list
1641     * @throws IllegalArgumentException if listener is null
1642     * @throws IllegalStateException if listener was already added
1643     */
1644    public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
1645            Handler handler, boolean updateImmediately) {
1646        if (listener == null) {
1647            throw new IllegalArgumentException("the listener is null");
1648        }
1649        synchronized (mAccountsUpdatedListeners) {
1650            if (mAccountsUpdatedListeners.containsKey(listener)) {
1651                throw new IllegalStateException("this listener is already added");
1652            }
1653            final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
1654
1655            mAccountsUpdatedListeners.put(listener, handler);
1656
1657            if (wasEmpty) {
1658                // Register a broadcast receiver to monitor account changes
1659                IntentFilter intentFilter = new IntentFilter();
1660                intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
1661                // To recover from disk-full.
1662                intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1663                mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
1664            }
1665        }
1666
1667        if (updateImmediately) {
1668            postToHandler(handler, listener, getAccounts());
1669        }
1670    }
1671
1672    /**
1673     * Removes an {@link OnAccountsUpdateListener} previously registered with
1674     * {@link #addOnAccountsUpdatedListener}.  The listener will no longer
1675     * receive notifications of account changes.
1676     *
1677     * <p>It is safe to call this method from the main thread.
1678     *
1679     * <p>No permission is required to call this method.
1680     *
1681     * @param listener The previously added listener to remove
1682     * @throws IllegalArgumentException if listener is null
1683     * @throws IllegalStateException if listener was not already added
1684     */
1685    public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
1686        if (listener == null) {
1687            Log.e(TAG, "Missing listener");
1688            return;
1689        }
1690        synchronized (mAccountsUpdatedListeners) {
1691            if (!mAccountsUpdatedListeners.containsKey(listener)) {
1692                Log.e(TAG, "Listener was not previously added");
1693                return;
1694            }
1695            mAccountsUpdatedListeners.remove(listener);
1696            if (mAccountsUpdatedListeners.isEmpty()) {
1697                mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
1698            }
1699        }
1700    }
1701}
1702