OSDN Git Service

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