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