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