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