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