AccountManager.java revision 3cdbc806ff52d02bf215a5aa696b670434d9f401
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 static android.Manifest.permission.GET_ACCOUNTS;
20
21import android.annotation.NonNull;
22import android.annotation.RequiresPermission;
23import android.annotation.Size;
24import android.annotation.SystemApi;
25import android.app.Activity;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.res.Resources;
32import android.database.SQLException;
33import android.os.Build;
34import android.os.Bundle;
35import android.os.Handler;
36import android.os.Looper;
37import android.os.Parcelable;
38import android.os.Process;
39import android.os.RemoteException;
40import android.os.UserHandle;
41import android.text.TextUtils;
42import android.util.Log;
43
44import com.android.internal.R;
45import com.google.android.collect.Maps;
46
47import java.io.IOException;
48import java.util.ArrayList;
49import java.util.HashMap;
50import java.util.List;
51import java.util.Map;
52import java.util.concurrent.Callable;
53import java.util.concurrent.CancellationException;
54import java.util.concurrent.ExecutionException;
55import java.util.concurrent.FutureTask;
56import java.util.concurrent.TimeUnit;
57import java.util.concurrent.TimeoutException;
58
59/**
60 * This class provides access to a centralized registry of the user's
61 * online accounts.  The user enters credentials (username and password) once
62 * per account, granting applications access to online resources with
63 * "one-click" approval.
64 *
65 * <p>Different online services have different ways of handling accounts and
66 * authentication, so the account manager uses pluggable <em>authenticator</em>
67 * modules for different <em>account types</em>.  Authenticators (which may be
68 * written by third parties) handle the actual details of validating account
69 * credentials and storing account information.  For example, Google, Facebook,
70 * and Microsoft Exchange each have their own authenticator.
71 *
72 * <p>Many servers support some notion of an <em>authentication token</em>,
73 * which can be used to authenticate a request to the server without sending
74 * the user's actual password.  (Auth tokens are normally created with a
75 * separate request which does include the user's credentials.)  AccountManager
76 * can generate auth tokens for applications, so the application doesn't need to
77 * handle passwords directly.  Auth tokens are normally reusable and cached by
78 * AccountManager, but must be refreshed periodically.  It's the responsibility
79 * of applications to <em>invalidate</em> auth tokens when they stop working so
80 * the AccountManager knows it needs to regenerate them.
81 *
82 * <p>Applications accessing a server normally go through these steps:
83 *
84 * <ul>
85 * <li>Get an instance of AccountManager using {@link #get(Context)}.
86 *
87 * <li>List the available accounts using {@link #getAccountsByType} or
88 * {@link #getAccountsByTypeAndFeatures}.  Normally applications will only
89 * be interested in accounts with one particular <em>type</em>, which
90 * identifies the authenticator.  Account <em>features</em> are used to
91 * identify particular account subtypes and capabilities.  Both the account
92 * type and features are authenticator-specific strings, and must be known by
93 * the application in coordination with its preferred authenticators.
94 *
95 * <li>Select one or more of the available accounts, possibly by asking the
96 * user for their preference.  If no suitable accounts are available,
97 * {@link #addAccount} may be called to prompt the user to create an
98 * account of the appropriate type.
99 *
100 * <li><b>Important:</b> If the application is using a previously remembered
101 * account selection, it must make sure the account is still in the list
102 * of accounts returned by {@link #getAccountsByType}.  Requesting an auth token
103 * for an account no longer on the device results in an undefined failure.
104 *
105 * <li>Request an auth token for the selected account(s) using one of the
106 * {@link #getAuthToken} methods or related helpers.  Refer to the description
107 * of each method for exact usage and error handling details.
108 *
109 * <li>Make the request using the auth token.  The form of the auth token,
110 * the format of the request, and the protocol used are all specific to the
111 * service you are accessing.  The application may use whatever network and
112 * protocol libraries are useful.
113 *
114 * <li><b>Important:</b> If the request fails with an authentication error,
115 * it could be that a cached auth token is stale and no longer honored by
116 * the server.  The application must call {@link #invalidateAuthToken} to remove
117 * the token from the cache, otherwise requests will continue failing!  After
118 * invalidating the auth token, immediately go back to the "Request an auth
119 * token" step above.  If the process fails the second time, then it can be
120 * treated as a "genuine" authentication failure and the user notified or other
121 * appropriate actions taken.
122 * </ul>
123 *
124 * <p>Some AccountManager methods may need to interact with the user to
125 * prompt for credentials, present options, or ask the user to add an account.
126 * The caller may choose whether to allow AccountManager to directly launch the
127 * necessary user interface and wait for the user, or to return an Intent which
128 * the caller may use to launch the interface, or (in some cases) to install a
129 * notification which the user can select at any time to launch the interface.
130 * To have AccountManager launch the interface directly, the caller must supply
131 * the current foreground {@link Activity} context.
132 *
133 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
134 * {@link Handler} as parameters.  These methods return immediately and
135 * run asynchronously. If a callback is provided then
136 * {@link AccountManagerCallback#run} will be invoked on the Handler's
137 * thread when the request completes, successfully or not.
138 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
139 * on the {@link AccountManagerFuture} returned by the method (and also passed
140 * to the callback).  This method waits for the operation to complete (if
141 * necessary) and either returns the result or throws an exception if an error
142 * occurred during the operation.  To make the request synchronously, call
143 * {@link AccountManagerFuture#getResult()} immediately on receiving the
144 * future from the method; no callback need be supplied.
145 *
146 * <p>Requests which may block, including
147 * {@link AccountManagerFuture#getResult()}, must never be called on
148 * the application's main event thread.  These operations throw
149 * {@link IllegalStateException} if they are used on the main thread.
150 */
151public class AccountManager {
152    private static final String TAG = "AccountManager";
153
154    public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
155    public static final int ERROR_CODE_NETWORK_ERROR = 3;
156    public static final int ERROR_CODE_CANCELED = 4;
157    public static final int ERROR_CODE_INVALID_RESPONSE = 5;
158    public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
159    public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
160    public static final int ERROR_CODE_BAD_REQUEST = 8;
161    public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
162
163    /** @hide */
164    public static final int ERROR_CODE_USER_RESTRICTED = 100;
165    /** @hide */
166    public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
167
168    /**
169     * Bundle key used for the {@link String} account name in results
170     * from methods which return information about a particular account.
171     */
172    public static final String KEY_ACCOUNT_NAME = "authAccount";
173
174    /**
175     * Bundle key used for the {@link String} account type in results
176     * from methods which return information about a particular account.
177     */
178    public static final String KEY_ACCOUNT_TYPE = "accountType";
179
180    /**
181     * Bundle key used for the auth token value in results
182     * from {@link #getAuthToken} and friends.
183     */
184    public static final String KEY_AUTHTOKEN = "authtoken";
185
186    /**
187     * Bundle key used for an {@link Intent} in results from methods that
188     * may require the caller to interact with the user.  The Intent can
189     * be used to start the corresponding user interface activity.
190     */
191    public static final String KEY_INTENT = "intent";
192
193    /**
194     * Bundle key used to supply the password directly in options to
195     * {@link #confirmCredentials}, rather than prompting the user with
196     * the standard password prompt.
197     */
198    public static final String KEY_PASSWORD = "password";
199
200    public static final String KEY_ACCOUNTS = "accounts";
201
202    public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
203    public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
204    public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
205    public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
206    public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
207    public static final String KEY_BOOLEAN_RESULT = "booleanResult";
208    public static final String KEY_ERROR_CODE = "errorCode";
209    public static final String KEY_ERROR_MESSAGE = "errorMessage";
210    public static final String KEY_USERDATA = "userdata";
211
212    /**
213     * Bundle key used to supply the last time the credentials of the account
214     * were authenticated successfully. Time is specified in milliseconds since
215     * epoch. Associated time is updated on successful authentication of account
216     * on adding account, confirming credentials, or updating credentials.
217     */
218    public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
219
220    /**
221     * Authenticators using 'customTokens' option will also get the UID of the
222     * caller
223     */
224    public static final String KEY_CALLER_UID = "callerUid";
225    public static final String KEY_CALLER_PID = "callerPid";
226
227    /**
228     * The Android package of the caller will be set in the options bundle by the
229     * {@link AccountManager} and will be passed to the AccountManagerService and
230     * to the AccountAuthenticators. The uid of the caller will be known by the
231     * AccountManagerService as well as the AccountAuthenticators so they will be able to
232     * verify that the package is consistent with the uid (a uid might be shared by many
233     * packages).
234     */
235    public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
236
237    /**
238     * Boolean, if set and 'customTokens' the authenticator is responsible for
239     * notifications.
240     * @hide
241     */
242    public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
243
244    /**
245     * Bundle key used for a {@link Bundle} in result from
246     * {@link #startAddAccountSession} and friends which returns session data
247     * for installing an account later.
248     * @hide
249     */
250    @SystemApi
251    public static final String KEY_ACCOUNT_SESSION_BUNDLE = "accountSessionBundle";
252
253    /**
254     * Bundle key used for the {@link String} account status token in result
255     * from {@link #startAddAccountSession} and friends which returns
256     * information about a particular account.
257     * @hide
258     */
259    @SystemApi
260    public static final String KEY_ACCOUNT_STATUS_TOKEN = "accountStatusToken";
261
262    public static final String ACTION_AUTHENTICATOR_INTENT =
263            "android.accounts.AccountAuthenticator";
264    public static final String AUTHENTICATOR_META_DATA_NAME =
265            "android.accounts.AccountAuthenticator";
266    public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
267
268    private final Context mContext;
269    private final IAccountManager mService;
270    private final Handler mMainHandler;
271
272    /**
273     * Action sent as a broadcast Intent by the AccountsService
274     * when accounts are added, accounts are removed, or an
275     * account's credentials (saved password, etc) are changed.
276     *
277     * @see #addOnAccountsUpdatedListener
278     */
279    public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
280        "android.accounts.LOGIN_ACCOUNTS_CHANGED";
281
282    /**
283     * @hide
284     */
285    public AccountManager(Context context, IAccountManager service) {
286        mContext = context;
287        mService = service;
288        mMainHandler = new Handler(mContext.getMainLooper());
289    }
290
291    /**
292     * @hide used for testing only
293     */
294    public AccountManager(Context context, IAccountManager service, Handler handler) {
295        mContext = context;
296        mService = service;
297        mMainHandler = handler;
298    }
299
300    /**
301     * @hide for internal use only
302     */
303    public static Bundle sanitizeResult(Bundle result) {
304        if (result != null) {
305            if (result.containsKey(KEY_AUTHTOKEN)
306                    && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
307                final Bundle newResult = new Bundle(result);
308                newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
309                return newResult;
310            }
311        }
312        return result;
313    }
314
315    /**
316     * Gets an AccountManager instance associated with a Context.
317     * The {@link Context} will be used as long as the AccountManager is
318     * active, so make sure to use a {@link Context} whose lifetime is
319     * commensurate with any listeners registered to
320     * {@link #addOnAccountsUpdatedListener} or similar methods.
321     *
322     * <p>It is safe to call this method from the main thread.
323     *
324     * <p>No permission is required to call this method.
325     *
326     * @param context The {@link Context} to use when necessary
327     * @return An {@link AccountManager} instance
328     */
329    public static AccountManager get(Context context) {
330        if (context == null) throw new IllegalArgumentException("context is null");
331        return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
332    }
333
334    /**
335     * Gets the saved password associated with the account.
336     * This is intended for authenticators and related code; applications
337     * should get an auth token instead.
338     *
339     * <p>It is safe to call this method from the main thread.
340     *
341     * <p>This method requires the caller to have a signature match with the
342     * authenticator that owns the specified account.
343     *
344     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
345     * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs for
346     * this function in API level 22.
347     *
348     * @param account The account to query for a password. Must not be {@code null}.
349     * @return The account's password, null if none or if the account doesn't exist
350     */
351    public String getPassword(final Account account) {
352        if (account == null) throw new IllegalArgumentException("account is null");
353        try {
354            return mService.getPassword(account);
355        } catch (RemoteException e) {
356            // won't ever happen
357            throw new RuntimeException(e);
358        }
359    }
360
361    /**
362     * Gets the user data named by "key" associated with the account.
363     * This is intended for authenticators and related code to store
364     * arbitrary metadata along with accounts.  The meaning of the keys
365     * and values is up to the authenticator for the account.
366     *
367     * <p>It is safe to call this method from the main thread.
368     *
369     * <p>This method requires the caller to have a signature match with the
370     * authenticator that owns the specified account.
371     *
372     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
373     * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs
374     * for this function in API level 22.
375     *
376     * @param account The account to query for user data
377     * @return The user data, null if the account or key doesn't exist
378     */
379    public String getUserData(final Account account, final String key) {
380        if (account == null) throw new IllegalArgumentException("account is null");
381        if (key == null) throw new IllegalArgumentException("key is null");
382        try {
383            return mService.getUserData(account, key);
384        } catch (RemoteException e) {
385            // won't ever happen
386            throw new RuntimeException(e);
387        }
388    }
389
390    /**
391     * Lists the currently registered authenticators.
392     *
393     * <p>It is safe to call this method from the main thread.
394     *
395     * <p>No permission is required to call this method.
396     *
397     * @return An array of {@link AuthenticatorDescription} for every
398     *     authenticator known to the AccountManager service.  Empty (never
399     *     null) if no authenticators are known.
400     */
401    public AuthenticatorDescription[] getAuthenticatorTypes() {
402        try {
403            return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
404        } catch (RemoteException e) {
405            // will never happen
406            throw new RuntimeException(e);
407        }
408    }
409
410    /**
411     * @hide
412     * Lists the currently registered authenticators for a given user id.
413     *
414     * <p>It is safe to call this method from the main thread.
415     *
416     * <p>The caller has to be in the same user or have the permission
417     * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
418     *
419     * @return An array of {@link AuthenticatorDescription} for every
420     *     authenticator known to the AccountManager service.  Empty (never
421     *     null) if no authenticators are known.
422     */
423    public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
424        try {
425            return mService.getAuthenticatorTypes(userId);
426        } catch (RemoteException e) {
427            // will never happen
428            throw new RuntimeException(e);
429        }
430    }
431
432    /**
433     * List every {@link Account} registered on the device that are managed by
434     * applications whose signatures match the caller.
435     *
436     * <p>This method can be called safely from the main thread. It is
437     * equivalent to calling <code>getAccountsByType(null)</code>.
438     *
439     * <p><b>NOTE:</b> Apps declaring a {@code targetSdkVersion<=23} in their
440     * manifests will continue to behave as they did on devices that support
441     * API level 23. In particular the GET_ACCOUNTS permission is required to
442     * see all the Accounts registered with the AccountManager. See docs for
443     * this function in API level 23 for more information.
444     *
445     * @return Array of Accounts. The array may be empty if no accounts are
446     *     available to the caller.
447     */
448    @NonNull
449    public Account[] getAccounts() {
450        return getAccountsByType(null);
451    }
452
453    /**
454     * @hide
455     * List every {@link Account} registered on the device for a specific User
456     * that are managed by applications whose signatures match the caller.
457     *
458     * <p><b>NOTE:</b> Apps declaring a {@code targetSdkVersion<=23} in their
459     * manifests will continue to behave as they did on devices that support
460     * API level 23. In particular the GET_ACCOUNTS permission is required to
461     * see all the Accounts registered with the AccountManager for the
462     * specified userId. See docs for this function in API level 23 for more
463     * information.
464     *
465     * <p>This method can be called safely from the main thread.
466     *
467     * @param int userId associated with the User whose accounts should be
468     *     queried.
469     * @return Array of Accounts. The array may be empty if no accounts are
470     *     available to the caller.
471     */
472    @NonNull
473    public Account[] getAccountsAsUser(int userId) {
474        try {
475            return mService.getAccountsAsUser(null, userId, mContext.getOpPackageName());
476        } catch (RemoteException e) {
477            // won't ever happen
478            throw new RuntimeException(e);
479        }
480    }
481
482    /**
483     * @hide
484     * For use by internal activities. Returns the list of accounts that the calling package
485     * is authorized to use, particularly for shared accounts.
486     * @param packageName package name of the calling app.
487     * @param uid the uid of the calling app.
488     * @return the accounts that are available to this package and user.
489     */
490    @NonNull
491    public Account[] getAccountsForPackage(String packageName, int uid) {
492        try {
493            return mService.getAccountsForPackage(packageName, uid, mContext.getOpPackageName());
494        } catch (RemoteException re) {
495            // won't ever happen
496            throw new RuntimeException(re);
497        }
498    }
499
500    /**
501     * Returns the accounts visible to the specified package, in an environment where some apps
502     * are not authorized to view all accounts. This method can only be called by system apps.
503     *
504     * @param type The type of accounts to return, null to retrieve all accounts
505     * @param packageName The package name of the app for which the accounts are to be returned
506     * @return Array of Accounts. The array may be empty if no accounts of th
507     *     specified type are visible to the caller.
508     */
509    @NonNull
510    public Account[] getAccountsByTypeForPackage(String type, String packageName) {
511        try {
512            return mService.getAccountsByTypeForPackage(type, packageName,
513                    mContext.getOpPackageName());
514        } catch (RemoteException re) {
515            // won't ever happen
516            throw new RuntimeException(re);
517        }
518    }
519
520    /**
521     * List every {@link Account} of a specified type managed by applications
522     * whose signatures match the caller.
523     *
524     * <p><b>NOTE:</b> Apps declaring a {@code targetSdkVersion<=23} in their
525     * manifests will continue to behave as they did on devices that support
526     * API level 23. See docs for this function in API level 23 for more
527     * information.
528     *
529     * <p>This method can be called safely from the main thread.
530     *
531     * @param type String denoting the type of the accounts to return,
532     *        {@code null} to retrieve all accounts visible to the caller.
533     * @return An array of Accounts.  Empty (never null) if no accounts
534     *         are available to the caller.
535     */
536    @NonNull
537    public Account[] getAccountsByType(String type) {
538        return getAccountsByTypeAsUser(type, Process.myUserHandle());
539    }
540
541    /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
542    @NonNull
543    public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
544        try {
545            return mService.getAccountsAsUser(type, userHandle.getIdentifier(),
546                    mContext.getOpPackageName());
547        } catch (RemoteException e) {
548            // won't ever happen
549            throw new RuntimeException(e);
550        }
551    }
552
553    /**
554     * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
555     * for an account.
556     * <p>
557     * This is only meant to be used by system activities and is not in the SDK.
558     * @param account The account whose permissions are being modified
559     * @param authTokenType The type of token whose permissions are being modified
560     * @param uid The uid that identifies the app which is being granted or revoked permission.
561     * @param value true is permission is being granted, false for revoked
562     * @hide
563     */
564    public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
565        try {
566            mService.updateAppPermission(account, authTokenType, uid, value);
567        } catch (RemoteException e) {
568            // won't ever happen
569            throw new RuntimeException(e);
570        }
571    }
572
573    /**
574     * Get the user-friendly label associated with an authenticator's auth token.
575     * @param accountType the type of the authenticator. must not be null.
576     * @param authTokenType the token type. must not be null.
577     * @param callback callback to invoke when the result is available. may be null.
578     * @param handler the handler on which to invoke the callback, or null for the main thread
579     * @return a future containing the label string
580     * @hide
581     */
582    @NonNull
583    public AccountManagerFuture<String> getAuthTokenLabel(
584            final String accountType, final String authTokenType,
585            AccountManagerCallback<String> callback, Handler handler) {
586        if (accountType == null) throw new IllegalArgumentException("accountType is null");
587        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
588        return new Future2Task<String>(handler, callback) {
589            @Override
590            public void doWork() throws RemoteException {
591                mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
592            }
593
594            @Override
595            public String bundleToResult(Bundle bundle) throws AuthenticatorException {
596                if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
597                    throw new AuthenticatorException("no result in response");
598                }
599                return bundle.getString(KEY_AUTH_TOKEN_LABEL);
600            }
601        }.start();
602    }
603
604    /**
605     * Finds out whether a particular account has all the specified features.
606     * Account features are authenticator-specific string tokens identifying
607     * boolean account properties.  For example, features are used to tell
608     * whether Google accounts have a particular service (such as Google
609     * Calendar or Google Talk) enabled.  The feature names and their meanings
610     * are published somewhere associated with the authenticator in question.
611     *
612     * <p>This method may be called from any thread, but the returned
613     * {@link AccountManagerFuture} must not be used on the main thread.
614     *
615     * <p><b>Note:</b>The specified account must be managed by an application
616     * whose signature matches the caller.
617     *
618     * <p><b>Further note:</b>Apps targeting API level 23 or earlier will continue to
619     * behave as they did on devices that support API level 23. In particular
620     * they may still require the GET_ACCOUNTS permission. See docs for this
621     * function in API level 23.
622     *
623     * @param account The {@link Account} to test
624     * @param features An array of the account features to check
625     * @param callback Callback to invoke when the request completes,
626     *     null for no callback
627     * @param handler {@link Handler} identifying the callback thread,
628     *     null for the main thread
629     * @return An {@link AccountManagerFuture} which resolves to a Boolean,
630     *     true if the account exists and has all of the specified features.
631     * @throws SecurityException if the specified account is managed by an
632     *     application whose signature doesn't match the caller's signature.
633     */
634    @NonNull
635    public AccountManagerFuture<Boolean> hasFeatures(final Account account,
636            final String[] features,
637            AccountManagerCallback<Boolean> callback, Handler handler) {
638        if (account == null) throw new IllegalArgumentException("account is null");
639        if (features == null) throw new IllegalArgumentException("features is null");
640        return new Future2Task<Boolean>(handler, callback) {
641            @Override
642            public void doWork() throws RemoteException {
643                mService.hasFeatures(mResponse, account, features, mContext.getOpPackageName());
644            }
645            @Override
646            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
647                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
648                    throw new AuthenticatorException("no result in response");
649                }
650                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
651            }
652        }.start();
653    }
654
655    /**
656     * Lists all accounts of a type which have certain features.  The account
657     * type identifies the authenticator (see {@link #getAccountsByType}). Said
658     * authenticator must be in a package whose signature matches the callers
659     * package signature. Account features are authenticator-specific string tokens
660     * identifying boolean account properties (see {@link #hasFeatures}).
661     *
662     * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
663     * which may contact the server or do other work to check account features,
664     * so the method returns an {@link AccountManagerFuture}.
665     *
666     * <p>This method may be called from any thread, but the returned
667     * {@link AccountManagerFuture} must not be used on the main thread.
668     *
669     * <p><b>NOTE:</b> Apps targeting API level 23 or earlier will continue to
670     * behave as they did on devices that support API level 23. In particular
671     * they may still require the GET_ACCOUNTS permission. See docs for this
672     * function in API level 23.
673     *
674     * @param type The type of accounts to return, must not be null
675     * @param features An array of the account features to require,
676     *     may be null or empty
677     * @param callback Callback to invoke when the request completes,
678     *     null for no callback
679     * @param handler {@link Handler} identifying the callback thread,
680     *     null for the main thread
681     * @return An {@link AccountManagerFuture} which resolves to an array of
682     *     {@link Account}, one per account of the specified type which
683     *     matches the requested features.
684     */
685    @NonNull
686    public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
687            final String type, final String[] features,
688            AccountManagerCallback<Account[]> callback, Handler handler) {
689        if (type == null) throw new IllegalArgumentException("type is null");
690        return new Future2Task<Account[]>(handler, callback) {
691            @Override
692            public void doWork() throws RemoteException {
693                mService.getAccountsByFeatures(mResponse, type, features,
694                        mContext.getOpPackageName());
695            }
696            @Override
697            public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
698                if (!bundle.containsKey(KEY_ACCOUNTS)) {
699                    throw new AuthenticatorException("no result in response");
700                }
701                final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
702                Account[] descs = new Account[parcelables.length];
703                for (int i = 0; i < parcelables.length; i++) {
704                    descs[i] = (Account) parcelables[i];
705                }
706                return descs;
707            }
708        }.start();
709    }
710
711    /**
712     * Adds an account directly to the AccountManager. Normally used by sign-up
713     * wizards associated with authenticators, not directly by applications.
714     * <p>Calling this method does not update the last authenticated timestamp,
715     * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
716     * {@link #notifyAccountAuthenticated(Account)} after getting success.
717     * However, if this method is called when it is triggered by addAccount() or
718     * addAccountAsUser() or similar functions, then there is no need to update
719     * timestamp manually as it is updated automatically by framework on
720     * successful completion of the mentioned functions.
721     * <p>It is safe to call this method from the main thread.
722     * <p>This method requires the caller to have a signature match with the
723     * authenticator that owns the specified account.
724     *
725     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
726     * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs
727     * for this function in API level 22.
728     *
729     * @param account The {@link Account} to add
730     * @param password The password to associate with the account, null for none
731     * @param userdata String values to use for the account's userdata, null for
732     *            none
733     * @return True if the account was successfully added, false if the account
734     *         already exists, the account is null, or another error occurs.
735     */
736    public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
737        if (account == null) throw new IllegalArgumentException("account is null");
738        try {
739            return mService.addAccountExplicitly(account, password, userdata);
740        } catch (RemoteException e) {
741            // Can happen if there was a SecurityException was thrown.
742            throw new RuntimeException(e);
743        }
744    }
745
746    /**
747     * Notifies the system that the account has just been authenticated. This
748     * information may be used by other applications to verify the account. This
749     * should be called only when the user has entered correct credentials for
750     * the account.
751     * <p>
752     * It is not safe to call this method from the main thread. As such, call it
753     * from another thread.
754     * <p>This method requires the caller to have a signature match with the
755     * authenticator that owns the specified account.
756     *
757     * @param account The {@link Account} to be updated.
758     * @return boolean {@code true} if the authentication of the account has been successfully
759     *         acknowledged. Otherwise {@code false}.
760     */
761    public boolean notifyAccountAuthenticated(Account account) {
762        if (account == null)
763            throw new IllegalArgumentException("account is null");
764        try {
765            return mService.accountAuthenticated(account);
766        } catch (RemoteException e) {
767            throw new RuntimeException(e);
768        }
769    }
770
771    /**
772     * Rename the specified {@link Account}.  This is equivalent to removing
773     * the existing account and adding a new renamed account with the old
774     * account's user data.
775     *
776     * <p>It is safe to call this method from the main thread.
777     *
778     * <p>This method requires the caller to have a signature match with the
779     * authenticator that manages the specified account.
780     *
781     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
782     * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
783     * is needed for those platforms. See docs for this function in API level 22.
784     *
785     * @param account The {@link Account} to rename
786     * @param newName String name to be associated with the account.
787     * @param callback Callback to invoke when the request completes, null for
788     *     no callback
789     * @param handler {@link Handler} identifying the callback thread, null for
790     *     the main thread
791     * @return An {@link AccountManagerFuture} which resolves to the Account
792     *     after the name change. If successful the account's name will be the
793     *     specified new name.
794     */
795    public AccountManagerFuture<Account> renameAccount(
796            final Account account,
797            @Size(min = 1) final String newName,
798            AccountManagerCallback<Account> callback,
799            Handler handler) {
800        if (account == null) throw new IllegalArgumentException("account is null.");
801        if (TextUtils.isEmpty(newName)) {
802              throw new IllegalArgumentException("newName is empty or null.");
803        }
804        return new Future2Task<Account>(handler, callback) {
805            @Override
806            public void doWork() throws RemoteException {
807                mService.renameAccount(mResponse, account, newName);
808            }
809            @Override
810            public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
811                String name = bundle.getString(KEY_ACCOUNT_NAME);
812                String type = bundle.getString(KEY_ACCOUNT_TYPE);
813                return new Account(name, type);
814            }
815        }.start();
816    }
817
818    /**
819     * Gets the previous name associated with the account or {@code null}, if
820     * none. This is intended so that clients of {@link
821     * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
822     * authenticator has renamed an account.
823     *
824     * <p>It is safe to call this method from the main thread.
825     *
826     * @param account The account to query for a previous name.
827     * @return The account's previous name, null if the account has never been
828     *         renamed.
829     */
830    public String getPreviousName(final Account account) {
831        if (account == null) throw new IllegalArgumentException("account is null");
832        try {
833            return mService.getPreviousName(account);
834        } catch (RemoteException e) {
835            // will never happen
836            throw new RuntimeException(e);
837        }
838    }
839
840    /**
841     * Removes an account from the AccountManager.  Does nothing if the account
842     * does not exist.  Does not delete the account from the server.
843     * The authenticator may have its own policies preventing account
844     * deletion, in which case the account will not be deleted.
845     *
846     * <p>This method requires the caller to have a signature match with the
847     * authenticator that manages the specified account.
848     *
849     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
850     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
851     * this function in API level 22.
852     *
853     * @param account The {@link Account} to remove
854     * @param callback Callback to invoke when the request completes,
855     *     null for no callback
856     * @param handler {@link Handler} identifying the callback thread,
857     *     null for the main thread
858     * @return An {@link AccountManagerFuture} which resolves to a Boolean,
859     *     true if the account has been successfully removed
860     * @deprecated use
861     *     {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
862     *     instead
863     */
864    @Deprecated
865    public AccountManagerFuture<Boolean> removeAccount(final Account account,
866            AccountManagerCallback<Boolean> callback, Handler handler) {
867        if (account == null) throw new IllegalArgumentException("account is null");
868        return new Future2Task<Boolean>(handler, callback) {
869            @Override
870            public void doWork() throws RemoteException {
871                mService.removeAccount(mResponse, account, false);
872            }
873            @Override
874            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
875                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
876                    throw new AuthenticatorException("no result in response");
877                }
878                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
879            }
880        }.start();
881    }
882
883    /**
884     * Removes an account from the AccountManager. Does nothing if the account
885     * does not exist.  Does not delete the account from the server.
886     * The authenticator may have its own policies preventing account
887     * deletion, in which case the account will not be deleted.
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 have a signature match with the
893     * authenticator that manages the specified account.
894     *
895     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
896     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
897     * this function in API level 22.
898     *
899     * @param account The {@link Account} to remove
900     * @param activity The {@link Activity} context to use for launching a new
901     *     authenticator-defined sub-Activity to prompt the user to delete an
902     *     account; used only to call startActivity(); if null, the prompt
903     *     will not be launched directly, but the {@link Intent} may be
904     *     returned to the caller instead
905     * @param callback Callback to invoke when the request completes,
906     *     null for no callback
907     * @param handler {@link Handler} identifying the callback thread,
908     *     null for the main thread
909     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
910     *     {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
911     *     was removed or if active. If no activity was specified, the returned
912     *     Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
913     *     needed to launch the actual account removal process, if authenticator
914     *     needs the activity launch. If an error occurred,
915     *     {@link AccountManagerFuture#getResult()} throws:
916     * <ul>
917     * <li> {@link AuthenticatorException} if no authenticator was registered for
918     *      this account type or the authenticator failed to respond
919     * <li> {@link OperationCanceledException} if the operation was canceled for
920     *      any reason, including the user canceling the creation process or
921     *      adding accounts (of this type) has been disabled by policy
922     * </ul>
923     */
924    public AccountManagerFuture<Bundle> removeAccount(final Account account,
925            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
926        if (account == null) throw new IllegalArgumentException("account is null");
927        return new AmsTask(activity, handler, callback) {
928            @Override
929            public void doWork() throws RemoteException {
930                mService.removeAccount(mResponse, account, activity != null);
931            }
932        }.start();
933    }
934
935    /**
936     * @see #removeAccount(Account, AccountManagerCallback, Handler)
937     * @hide
938     * @deprecated use
939     *     {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
940     *     instead
941     */
942    @Deprecated
943    public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
944            AccountManagerCallback<Boolean> callback, Handler handler,
945            final UserHandle userHandle) {
946        if (account == null) throw new IllegalArgumentException("account is null");
947        if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
948        return new Future2Task<Boolean>(handler, callback) {
949            @Override
950            public void doWork() throws RemoteException {
951                mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
952            }
953            @Override
954            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
955                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
956                    throw new AuthenticatorException("no result in response");
957                }
958                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
959            }
960        }.start();
961    }
962
963    /**
964     * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
965     * @hide
966     */
967    public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
968            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
969            final UserHandle userHandle) {
970        if (account == null)
971            throw new IllegalArgumentException("account is null");
972        if (userHandle == null)
973            throw new IllegalArgumentException("userHandle is null");
974        return new AmsTask(activity, handler, callback) {
975            @Override
976            public void doWork() throws RemoteException {
977                mService.removeAccountAsUser(mResponse, account, activity != null,
978                        userHandle.getIdentifier());
979            }
980        }.start();
981    }
982
983    /**
984     * Removes an account directly. Normally used by authenticators, not
985     * directly by applications. Does not delete the account from the server.
986     * The authenticator may have its own policies preventing account deletion,
987     * in which case the account will not be deleted.
988     * <p>
989     * It is safe to call this method from the main thread.
990     * <p>This method requires the caller to have a signature match with the
991     * authenticator that manages the specified account.
992     *
993     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
994     * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
995     * is needed for those platforms. See docs for this function in API level 22.
996     *
997     * @param account The {@link Account} to delete.
998     * @return True if the account was successfully deleted, false if the
999     *         account did not exist, the account is null, or another error
1000     *         occurs.
1001     */
1002    public boolean removeAccountExplicitly(Account account) {
1003        if (account == null) throw new IllegalArgumentException("account is null");
1004        try {
1005            return mService.removeAccountExplicitly(account);
1006        } catch (RemoteException e) {
1007            // May happen if the caller doesn't match the signature of the authenticator.
1008            throw new RuntimeException(e);
1009        }
1010    }
1011
1012    /**
1013     * Removes an auth token from the AccountManager's cache.  Does nothing if
1014     * the auth token is not currently in the cache.  Applications must call this
1015     * method when the auth token is found to have expired or otherwise become
1016     * invalid for authenticating requests.  The AccountManager does not validate
1017     * or expire cached auth tokens otherwise.
1018     *
1019     * <p>It is safe to call this method from the main thread.
1020     *
1021     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1022     * MANAGE_ACCOUNTS or USE_CREDENTIALS permission is needed for those
1023     * platforms. See docs for this function in API level 22.
1024     *
1025     * @param accountType The account type of the auth token to invalidate, must not be null
1026     * @param authToken The auth token to invalidate, may be null
1027     */
1028    public void invalidateAuthToken(final String accountType, final String authToken) {
1029        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1030        try {
1031            if (authToken != null) {
1032                mService.invalidateAuthToken(accountType, authToken);
1033            }
1034        } catch (RemoteException e) {
1035            // won't ever happen
1036            throw new RuntimeException(e);
1037        }
1038    }
1039
1040    /**
1041     * Gets an auth token from the AccountManager's cache.  If no auth
1042     * token is cached for this account, null will be returned -- a new
1043     * auth token will not be generated, and the server will not be contacted.
1044     * Intended for use by the authenticator, not directly by applications.
1045     *
1046     * <p>It is safe to call this method from the main thread.
1047     *
1048     * <p>This method requires the caller to have a signature match with the
1049     * authenticator that manages the specified account.
1050     *
1051     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1052     * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1053     * is needed for those platforms. See docs for this function in API level 22.
1054     *
1055     * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
1056     * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
1057     * @return The cached auth token for this account and type, or null if
1058     *     no auth token is cached or the account does not exist.
1059     * @see #getAuthToken
1060     */
1061    public String peekAuthToken(final Account account, final String authTokenType) {
1062        if (account == null) throw new IllegalArgumentException("account is null");
1063        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1064        try {
1065            return mService.peekAuthToken(account, authTokenType);
1066        } catch (RemoteException e) {
1067            // won't ever happen
1068            throw new RuntimeException(e);
1069        }
1070    }
1071
1072    /**
1073     * Sets or forgets a saved password. This modifies the local copy of the
1074     * password used to automatically authenticate the user; it does not change
1075     * the user's account password on the server. Intended for use by the
1076     * authenticator, not directly by applications.
1077     * <p>Calling this method does not update the last authenticated timestamp,
1078     * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
1079     * {@link #notifyAccountAuthenticated(Account)} after getting success.
1080     * <p>It is safe to call this method from the main thread.
1081     * <p>This method requires the caller to have a signature match with the
1082     * authenticator that manages the specified account.
1083     *
1084     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1085     * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1086     * is needed for those platforms. See docs for this function in API level 22.
1087     *
1088     * @param account The account whose password is to be set. Cannot be
1089     *            {@code null}.
1090     * @param password The password to set, null to clear the password
1091     */
1092    public void setPassword(final Account account, final String password) {
1093        if (account == null) throw new IllegalArgumentException("account is null");
1094        try {
1095            mService.setPassword(account, password);
1096        } catch (RemoteException e) {
1097            // won't ever happen
1098            throw new RuntimeException(e);
1099        }
1100    }
1101
1102    /**
1103     * Forgets a saved password.  This erases the local copy of the password;
1104     * it does not change the user's account password on the server.
1105     * Has the same effect as setPassword(account, null) but requires fewer
1106     * permissions, and may be used by applications or management interfaces
1107     * to "sign out" from an account.
1108     *
1109     * <p>This method only successfully clear the account's password when the
1110     * caller has the same signature as the authenticator that owns the
1111     * specified account. Otherwise, this method will silently fail.
1112     *
1113     * <p>It is safe to call this method from the main thread.
1114     *
1115     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1116     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1117     * this function in API level 22.
1118     *
1119     * @param account The account whose password to clear
1120     */
1121    public void clearPassword(final Account account) {
1122        if (account == null) throw new IllegalArgumentException("account is null");
1123        try {
1124            mService.clearPassword(account);
1125        } catch (RemoteException e) {
1126            // won't ever happen
1127            throw new RuntimeException(e);
1128        }
1129    }
1130
1131    /**
1132     * Sets one userdata key for an account.  Intended by use for the
1133     * authenticator to stash state for itself, not directly by applications.
1134     * The meaning of the keys and values is up to the authenticator.
1135     *
1136     * <p>It is safe to call this method from the main thread.
1137     *
1138     * <p>This method requires the caller to have a signature match with the
1139     * authenticator that manages the specified account.
1140     *
1141     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1142     * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1143     * is needed for those platforms. See docs for this function in API level 22.
1144     *
1145     * @param account Account whose user data is to be set. Must not be {@code null}.
1146     * @param key String user data key to set.  Must not be null
1147     * @param value String value to set, {@code null} to clear this user data key
1148     */
1149    public void setUserData(final Account account, final String key, final String value) {
1150        if (account == null) throw new IllegalArgumentException("account is null");
1151        if (key == null) throw new IllegalArgumentException("key is null");
1152        try {
1153            mService.setUserData(account, key, value);
1154        } catch (RemoteException e) {
1155            // Will happen if there is not signature match.
1156            throw new RuntimeException(e);
1157        }
1158    }
1159
1160    /**
1161     * Adds an auth token to the AccountManager cache for an account.
1162     * If the account does not exist then this call has no effect.
1163     * Replaces any previous auth token for this account and auth token type.
1164     * Intended for use by the authenticator, not directly by applications.
1165     *
1166     * <p>It is safe to call this method from the main thread.
1167     *
1168     * <p>This method requires the caller to have a signature match with the
1169     * authenticator that manages the specified account.
1170     *
1171     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1172     * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1173     * is needed for those platforms. See docs for this function in API level 22.
1174     *
1175     * @param account The account to set an auth token for
1176     * @param authTokenType The type of the auth token, see {#getAuthToken}
1177     * @param authToken The auth token to add to the cache
1178     */
1179    public void setAuthToken(Account account, final String authTokenType, final String authToken) {
1180        if (account == null) throw new IllegalArgumentException("account is null");
1181        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1182        try {
1183            mService.setAuthToken(account, authTokenType, authToken);
1184        } catch (RemoteException e) {
1185            // won't ever happen
1186            throw new RuntimeException(e);
1187        }
1188    }
1189
1190    /**
1191     * This convenience helper synchronously gets an auth token with
1192     * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1193     *
1194     * <p>This method may block while a network request completes, and must
1195     * never be made from the main thread.
1196     *
1197     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1198     * USE_CREDENTIALS permission is needed for those platforms. See docs for
1199     * this function in API level 22.
1200     *
1201     * @param account The account to fetch an auth token for
1202     * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
1203     * @param notifyAuthFailure If true, display a notification and return null
1204     *     if authentication fails; if false, prompt and wait for the user to
1205     *     re-enter correct credentials before returning
1206     * @return An auth token of the specified type for this account, or null
1207     *     if authentication fails or none can be fetched.
1208     * @throws AuthenticatorException if the authenticator failed to respond
1209     * @throws OperationCanceledException if the request was canceled for any
1210     *     reason, including the user canceling a credential request
1211     * @throws java.io.IOException if the authenticator experienced an I/O problem
1212     *     creating a new auth token, usually because of network trouble
1213     */
1214    public String blockingGetAuthToken(Account account, String authTokenType,
1215            boolean notifyAuthFailure)
1216            throws OperationCanceledException, IOException, AuthenticatorException {
1217        if (account == null) throw new IllegalArgumentException("account is null");
1218        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1219        Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1220                null /* handler */).getResult();
1221        if (bundle == null) {
1222            // This should never happen, but it does, occasionally. If it does return null to
1223            // signify that we were not able to get the authtoken.
1224            // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1225            // returned
1226            Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1227                    + account + ", authTokenType " + authTokenType);
1228            return null;
1229        }
1230        return bundle.getString(KEY_AUTHTOKEN);
1231    }
1232
1233    /**
1234     * Gets an auth token of the specified type for a particular account,
1235     * prompting the user for credentials if necessary.  This method is
1236     * intended for applications running in the foreground where it makes
1237     * sense to ask the user directly for a password.
1238     *
1239     * <p>If a previously generated auth token is cached for this account and
1240     * type, then it is returned.  Otherwise, if a saved password is
1241     * available, it is sent to the server to generate a new auth token.
1242     * Otherwise, the user is prompted to enter a password.
1243     *
1244     * <p>Some authenticators have auth token <em>types</em>, whose value
1245     * is authenticator-dependent.  Some services use different token types to
1246     * access different functionality -- for example, Google uses different auth
1247     * tokens to access Gmail and Google Calendar for the same account.
1248     *
1249     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1250     * USE_CREDENTIALS permission is needed for those platforms. See docs for
1251     * this function in API level 22.
1252     *
1253     * <p>This method may be called from any thread, but the returned
1254     * {@link AccountManagerFuture} must not be used on the main thread.
1255     *
1256     * @param account The account to fetch an auth token for
1257     * @param authTokenType The auth token type, an authenticator-dependent
1258     *     string token, must not be null
1259     * @param options Authenticator-specific options for the request,
1260     *     may be null or empty
1261     * @param activity The {@link Activity} context to use for launching a new
1262     *     authenticator-defined sub-Activity to prompt the user for a password
1263     *     if necessary; used only to call startActivity(); must not be null.
1264     * @param callback Callback to invoke when the request completes,
1265     *     null for no callback
1266     * @param handler {@link Handler} identifying the callback thread,
1267     *     null for the main thread
1268     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1269     *     at least the following fields:
1270     * <ul>
1271     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1272     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1273     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1274     * </ul>
1275     *
1276     * (Other authenticator-specific values may be returned.)  If an auth token
1277     * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1278     * <ul>
1279     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1280     * <li> {@link OperationCanceledException} if the operation is canceled for
1281     *      any reason, incluidng the user canceling a credential request
1282     * <li> {@link IOException} if the authenticator experienced an I/O problem
1283     *      creating a new auth token, usually because of network trouble
1284     * </ul>
1285     * If the account is no longer present on the device, the return value is
1286     * authenticator-dependent.  The caller should verify the validity of the
1287     * account before requesting an auth token.
1288     */
1289    public AccountManagerFuture<Bundle> getAuthToken(
1290            final Account account, final String authTokenType, final Bundle options,
1291            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
1292        if (account == null) throw new IllegalArgumentException("account is null");
1293        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1294        final Bundle optionsIn = new Bundle();
1295        if (options != null) {
1296            optionsIn.putAll(options);
1297        }
1298        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1299        return new AmsTask(activity, handler, callback) {
1300            @Override
1301            public void doWork() throws RemoteException {
1302                mService.getAuthToken(mResponse, account, authTokenType,
1303                        false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
1304                        optionsIn);
1305            }
1306        }.start();
1307    }
1308
1309    /**
1310     * Gets an auth token of the specified type for a particular account,
1311     * optionally raising a notification if the user must enter credentials.
1312     * This method is intended for background tasks and services where the
1313     * user should not be immediately interrupted with a password prompt.
1314     *
1315     * <p>If a previously generated auth token is cached for this account and
1316     * type, then it is returned.  Otherwise, if a saved password is
1317     * available, it is sent to the server to generate a new auth token.
1318     * Otherwise, an {@link Intent} is returned which, when started, will
1319     * prompt the user for a password.  If the notifyAuthFailure parameter is
1320     * set, a status bar notification is also created with the same Intent,
1321     * alerting the user that they need to enter a password at some point.
1322     *
1323     * <p>In that case, you may need to wait until the user responds, which
1324     * could take hours or days or forever.  When the user does respond and
1325     * supply a new password, the account manager will broadcast the
1326     * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1327     * use to try again.
1328     *
1329     * <p>If notifyAuthFailure is not set, it is the application's
1330     * responsibility to launch the returned Intent at some point.
1331     * Either way, the result from this call will not wait for user action.
1332     *
1333     * <p>Some authenticators have auth token <em>types</em>, whose value
1334     * is authenticator-dependent.  Some services use different token types to
1335     * access different functionality -- for example, Google uses different auth
1336     * tokens to access Gmail and Google Calendar for the same account.
1337     *
1338     * <p>This method may be called from any thread, but the returned
1339     * {@link AccountManagerFuture} must not be used on the main thread.
1340     *
1341     * @param account The account to fetch an auth token for
1342     * @param authTokenType The auth token type, an authenticator-dependent
1343     *     string token, must not be null
1344     * @param notifyAuthFailure True to add a notification to prompt the
1345     *     user for a password if necessary, false to leave that to the caller
1346     * @param callback Callback to invoke when the request completes,
1347     *     null for no callback
1348     * @param handler {@link Handler} identifying the callback thread,
1349     *     null for the main thread
1350     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1351     *     at least the following fields on success:
1352     * <ul>
1353     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1354     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1355     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1356     * </ul>
1357     *
1358     * (Other authenticator-specific values may be returned.)  If the user
1359     * must enter credentials, the returned Bundle contains only
1360     * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1361     *
1362     * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1363     * <ul>
1364     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1365     * <li> {@link OperationCanceledException} if the operation is canceled for
1366     *      any reason, incluidng the user canceling a credential request
1367     * <li> {@link IOException} if the authenticator experienced an I/O problem
1368     *      creating a new auth token, usually because of network trouble
1369     * </ul>
1370     * If the account is no longer present on the device, the return value is
1371     * authenticator-dependent.  The caller should verify the validity of the
1372     * account before requesting an auth token.
1373     * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1374     * boolean, AccountManagerCallback, android.os.Handler)} instead
1375     */
1376    @Deprecated
1377    public AccountManagerFuture<Bundle> getAuthToken(
1378            final Account account, final String authTokenType,
1379            final boolean notifyAuthFailure,
1380            AccountManagerCallback<Bundle> callback, Handler handler) {
1381        return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
1382                handler);
1383    }
1384
1385    /**
1386     * Gets an auth token of the specified type for a particular account,
1387     * optionally raising a notification if the user must enter credentials.
1388     * This method is intended for background tasks and services where the
1389     * user should not be immediately interrupted with a password prompt.
1390     *
1391     * <p>If a previously generated auth token is cached for this account and
1392     * type, then it is returned.  Otherwise, if a saved password is
1393     * available, it is sent to the server to generate a new auth token.
1394     * Otherwise, an {@link Intent} is returned which, when started, will
1395     * prompt the user for a password.  If the notifyAuthFailure parameter is
1396     * set, a status bar notification is also created with the same Intent,
1397     * alerting the user that they need to enter a password at some point.
1398     *
1399     * <p>In that case, you may need to wait until the user responds, which
1400     * could take hours or days or forever.  When the user does respond and
1401     * supply a new password, the account manager will broadcast the
1402     * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1403     * use to try again.
1404     *
1405     * <p>If notifyAuthFailure is not set, it is the application's
1406     * responsibility to launch the returned Intent at some point.
1407     * Either way, the result from this call will not wait for user action.
1408     *
1409     * <p>Some authenticators have auth token <em>types</em>, whose value
1410     * is authenticator-dependent.  Some services use different token types to
1411     * access different functionality -- for example, Google uses different auth
1412     * tokens to access Gmail and Google Calendar for the same account.
1413     *
1414     * <p>This method may be called from any thread, but the returned
1415     * {@link AccountManagerFuture} must not be used on the main thread.
1416     *
1417     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1418     * USE_CREDENTIALS permission is needed for those platforms. See docs for
1419     * this function in API level 22.
1420     *
1421     * @param account The account to fetch an auth token for
1422     * @param authTokenType The auth token type, an authenticator-dependent
1423     *     string token, must not be null
1424     * @param options Authenticator-specific options for the request,
1425     *     may be null or empty
1426     * @param notifyAuthFailure True to add a notification to prompt the
1427     *     user for a password if necessary, false to leave that to the caller
1428     * @param callback Callback to invoke when the request completes,
1429     *     null for no callback
1430     * @param handler {@link Handler} identifying the callback thread,
1431     *     null for the main thread
1432     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1433     *     at least the following fields on success:
1434     * <ul>
1435     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1436     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1437     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1438     * </ul>
1439     *
1440     * (Other authenticator-specific values may be returned.)  If the user
1441     * must enter credentials, the returned Bundle contains only
1442     * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1443     *
1444     * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1445     * <ul>
1446     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1447     * <li> {@link OperationCanceledException} if the operation is canceled for
1448     *      any reason, incluidng the user canceling a credential request
1449     * <li> {@link IOException} if the authenticator experienced an I/O problem
1450     *      creating a new auth token, usually because of network trouble
1451     * </ul>
1452     * If the account is no longer present on the device, the return value is
1453     * authenticator-dependent.  The caller should verify the validity of the
1454     * account before requesting an auth token.
1455     */
1456    public AccountManagerFuture<Bundle> getAuthToken(
1457            final Account account, final String authTokenType, final Bundle options,
1458            final boolean notifyAuthFailure,
1459            AccountManagerCallback<Bundle> callback, Handler handler) {
1460
1461        if (account == null) throw new IllegalArgumentException("account is null");
1462        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1463        final Bundle optionsIn = new Bundle();
1464        if (options != null) {
1465            optionsIn.putAll(options);
1466        }
1467        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1468        return new AmsTask(null, handler, callback) {
1469            @Override
1470            public void doWork() throws RemoteException {
1471                mService.getAuthToken(mResponse, account, authTokenType,
1472                        notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
1473            }
1474        }.start();
1475    }
1476
1477    /**
1478     * Asks the user to add an account of a specified type.  The authenticator
1479     * for this account type processes this request with the appropriate user
1480     * interface.  If the user does elect to create a new account, the account
1481     * name is returned.
1482     *
1483     * <p>This method may be called from any thread, but the returned
1484     * {@link AccountManagerFuture} must not be used on the main thread.
1485     *
1486     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1487     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1488     * this function in API level 22.
1489     *
1490     * @param accountType The type of account to add; must not be null
1491     * @param authTokenType The type of auth token (see {@link #getAuthToken})
1492     *     this account will need to be able to generate, null for none
1493     * @param requiredFeatures The features (see {@link #hasFeatures}) this
1494     *     account must have, null for none
1495     * @param addAccountOptions Authenticator-specific options for the request,
1496     *     may be null or empty
1497     * @param activity The {@link Activity} context to use for launching a new
1498     *     authenticator-defined sub-Activity to prompt the user to create an
1499     *     account; used only to call startActivity(); if null, the prompt
1500     *     will not be launched directly, but the necessary {@link Intent}
1501     *     will be returned to the caller instead
1502     * @param callback Callback to invoke when the request completes,
1503     *     null for no callback
1504     * @param handler {@link Handler} identifying the callback thread,
1505     *     null for the main thread
1506     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1507     *     these fields if activity was specified and an account was created:
1508     * <ul>
1509     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1510     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1511     * </ul>
1512     *
1513     * If no activity was specified, the returned Bundle contains only
1514     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1515     * actual account creation process.  If an error occurred,
1516     * {@link AccountManagerFuture#getResult()} throws:
1517     * <ul>
1518     * <li> {@link AuthenticatorException} if no authenticator was registered for
1519     *      this account type or the authenticator failed to respond
1520     * <li> {@link OperationCanceledException} if the operation was canceled for
1521     *      any reason, including the user canceling the creation process or adding accounts
1522     *      (of this type) has been disabled by policy
1523     * <li> {@link IOException} if the authenticator experienced an I/O problem
1524     *      creating a new account, usually because of network trouble
1525     * </ul>
1526     */
1527    public AccountManagerFuture<Bundle> addAccount(final String accountType,
1528            final String authTokenType, final String[] requiredFeatures,
1529            final Bundle addAccountOptions,
1530            final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
1531        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1532        final Bundle optionsIn = new Bundle();
1533        if (addAccountOptions != null) {
1534            optionsIn.putAll(addAccountOptions);
1535        }
1536        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1537
1538        return new AmsTask(activity, handler, callback) {
1539            @Override
1540            public void doWork() throws RemoteException {
1541                mService.addAccount(mResponse, accountType, authTokenType,
1542                        requiredFeatures, activity != null, optionsIn);
1543            }
1544        }.start();
1545    }
1546
1547    /**
1548     * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1549     * @hide
1550     */
1551    public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1552            final String authTokenType, final String[] requiredFeatures,
1553            final Bundle addAccountOptions, final Activity activity,
1554            AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1555        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1556        if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1557        final Bundle optionsIn = new Bundle();
1558        if (addAccountOptions != null) {
1559            optionsIn.putAll(addAccountOptions);
1560        }
1561        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1562
1563        return new AmsTask(activity, handler, callback) {
1564            @Override
1565            public void doWork() throws RemoteException {
1566                mService.addAccountAsUser(mResponse, accountType, authTokenType,
1567                        requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1568            }
1569        }.start();
1570    }
1571
1572
1573    /**
1574     * Adds shared accounts from a parent user to a secondary user. Adding the shared account
1575     * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1576     * are attempted to be copied to the target user from the primary via calls to the
1577     * authenticator.
1578     * @param parentUser parent user
1579     * @param user target user
1580     * @hide
1581     */
1582    public void addSharedAccountsFromParentUser(UserHandle parentUser, UserHandle user) {
1583        try {
1584            mService.addSharedAccountsFromParentUser(parentUser.getIdentifier(),
1585                    user.getIdentifier());
1586        } catch (RemoteException re) {
1587            throw new IllegalStateException(re);
1588        }
1589    }
1590
1591    /**
1592     * Copies an account from one user to another user.
1593     * @param account the account to copy
1594     * @param fromUser the user to copy the account from
1595     * @param toUser the target user
1596     * @param callback Callback to invoke when the request completes,
1597     *     null for no callback
1598     * @param handler {@link Handler} identifying the callback thread,
1599     *     null for the main thread
1600     * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1601     * succeeded.
1602     * @hide
1603     */
1604    public AccountManagerFuture<Boolean> copyAccountToUser(
1605            final Account account, final UserHandle fromUser, final UserHandle toUser,
1606            AccountManagerCallback<Boolean> callback, Handler handler) {
1607        if (account == null) throw new IllegalArgumentException("account is null");
1608        if (toUser == null || fromUser == null) {
1609            throw new IllegalArgumentException("fromUser and toUser cannot be null");
1610        }
1611
1612        return new Future2Task<Boolean>(handler, callback) {
1613            @Override
1614            public void doWork() throws RemoteException {
1615                mService.copyAccountToUser(
1616                        mResponse, account, fromUser.getIdentifier(), toUser.getIdentifier());
1617            }
1618            @Override
1619            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1620                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1621                    throw new AuthenticatorException("no result in response");
1622                }
1623                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1624            }
1625        }.start();
1626    }
1627
1628    /**
1629     * @hide
1630     * Removes the shared account.
1631     * @param account the account to remove
1632     * @param user the user to remove the account from
1633     * @return
1634     */
1635    public boolean removeSharedAccount(final Account account, UserHandle user) {
1636        try {
1637            boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1638            return val;
1639        } catch (RemoteException re) {
1640            // won't ever happen
1641            throw new RuntimeException(re);
1642        }
1643    }
1644
1645    /**
1646     * @hide
1647     * @param user
1648     * @return
1649     */
1650    public Account[] getSharedAccounts(UserHandle user) {
1651        try {
1652            return mService.getSharedAccountsAsUser(user.getIdentifier());
1653        } catch (RemoteException re) {
1654            // won't ever happen
1655            throw new RuntimeException(re);
1656        }
1657    }
1658
1659    /**
1660     * Confirms that the user knows the password for an account to make extra
1661     * sure they are the owner of the account.  The user-entered password can
1662     * be supplied directly, otherwise the authenticator for this account type
1663     * prompts the user with the appropriate interface.  This method is
1664     * intended for applications which want extra assurance; for example, the
1665     * phone lock screen uses this to let the user unlock the phone with an
1666     * account password if they forget the lock pattern.
1667     *
1668     * <p>If the user-entered password matches a saved password for this
1669     * account, the request is considered valid; otherwise the authenticator
1670     * verifies the password (usually by contacting the server).
1671     *
1672     * <p>This method may be called from any thread, but the returned
1673     * {@link AccountManagerFuture} must not be used on the main thread.
1674     *
1675     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1676     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
1677     * for this function in API level 22.
1678     *
1679     * @param account The account to confirm password knowledge for
1680     * @param options Authenticator-specific options for the request;
1681     *     if the {@link #KEY_PASSWORD} string field is present, the
1682     *     authenticator may use it directly rather than prompting the user;
1683     *     may be null or empty
1684     * @param activity The {@link Activity} context to use for launching a new
1685     *     authenticator-defined sub-Activity to prompt the user to enter a
1686     *     password; used only to call startActivity(); if null, the prompt
1687     *     will not be launched directly, but the necessary {@link Intent}
1688     *     will be returned to the caller instead
1689     * @param callback Callback to invoke when the request completes,
1690     *     null for no callback
1691     * @param handler {@link Handler} identifying the callback thread,
1692     *     null for the main thread
1693     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1694     *     with these fields if activity or password was supplied and
1695     *     the account was successfully verified:
1696     * <ul>
1697     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
1698     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1699     * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1700     * </ul>
1701     *
1702     * If no activity or password was specified, the returned Bundle contains
1703     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1704     * password prompt.
1705     *
1706     * <p>Also the returning Bundle may contain {@link
1707     * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
1708     * credential was validated/created.
1709     *
1710     * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
1711     * <ul>
1712     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1713     * <li> {@link OperationCanceledException} if the operation was canceled for
1714     *      any reason, including the user canceling the password prompt
1715     * <li> {@link IOException} if the authenticator experienced an I/O problem
1716     *      verifying the password, usually because of network trouble
1717     * </ul>
1718     */
1719    public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1720            final Bundle options,
1721            final Activity activity,
1722            final AccountManagerCallback<Bundle> callback,
1723            final Handler handler) {
1724        return confirmCredentialsAsUser(account, options, activity, callback, handler,
1725                Process.myUserHandle());
1726    }
1727
1728    /**
1729     * @hide
1730     * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1731     * but for the specified user.
1732     */
1733    public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1734            final Bundle options,
1735            final Activity activity,
1736            final AccountManagerCallback<Bundle> callback,
1737            final Handler handler, UserHandle userHandle) {
1738        if (account == null) throw new IllegalArgumentException("account is null");
1739        final int userId = userHandle.getIdentifier();
1740        return new AmsTask(activity, handler, callback) {
1741            @Override
1742            public void doWork() throws RemoteException {
1743                mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1744                        userId);
1745            }
1746        }.start();
1747    }
1748
1749    /**
1750     * Asks the user to enter a new password for an account, updating the
1751     * saved credentials for the account.  Normally this happens automatically
1752     * when the server rejects credentials during an auth token fetch, but this
1753     * can be invoked directly to ensure we have the correct credentials stored.
1754     *
1755     * <p>This method may be called from any thread, but the returned
1756     * {@link AccountManagerFuture} must not be used on the main thread.
1757     *
1758     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1759     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1760     * this function in API level 22.
1761     *
1762     * @param account The account to update credentials for
1763     * @param authTokenType The credentials entered must allow an auth token
1764     *     of this type to be created (but no actual auth token is returned);
1765     *     may be null
1766     * @param options Authenticator-specific options for the request;
1767     *     may be null or empty
1768     * @param activity The {@link Activity} context to use for launching a new
1769     *     authenticator-defined sub-Activity to prompt the user to enter a
1770     *     password; used only to call startActivity(); if null, the prompt
1771     *     will not be launched directly, but the necessary {@link Intent}
1772     *     will be returned to the caller instead
1773     * @param callback Callback to invoke when the request completes,
1774     *     null for no callback
1775     * @param handler {@link Handler} identifying the callback thread,
1776     *     null for the main thread
1777     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1778     *     with these fields if an activity was supplied and the account
1779     *     credentials were successfully updated:
1780     * <ul>
1781     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1782     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1783     * </ul>
1784     *
1785     * If no activity was specified, the returned Bundle contains
1786     * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1787     * password prompt. If an error occurred,
1788     * {@link AccountManagerFuture#getResult()} throws:
1789     * <ul>
1790     * <li> {@link AuthenticatorException} if the authenticator failed to respond
1791     * <li> {@link OperationCanceledException} if the operation was canceled for
1792     *      any reason, including the user canceling the password prompt
1793     * <li> {@link IOException} if the authenticator experienced an I/O problem
1794     *      verifying the password, usually because of network trouble
1795     * </ul>
1796     */
1797    public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1798            final String authTokenType,
1799            final Bundle options, final Activity activity,
1800            final AccountManagerCallback<Bundle> callback,
1801            final Handler handler) {
1802        if (account == null) throw new IllegalArgumentException("account is null");
1803        return new AmsTask(activity, handler, callback) {
1804            @Override
1805            public void doWork() throws RemoteException {
1806                mService.updateCredentials(mResponse, account, authTokenType, activity != null,
1807                        options);
1808            }
1809        }.start();
1810    }
1811
1812    /**
1813     * Offers the user an opportunity to change an authenticator's settings.
1814     * These properties are for the authenticator in general, not a particular
1815     * account.  Not all authenticators support this method.
1816     *
1817     * <p>This method may be called from any thread, but the returned
1818     * {@link AccountManagerFuture} must not be used on the main thread.
1819     *
1820     * <p>This method requires the caller to have the same signature as the
1821     * authenticator associated with the specified account type.
1822     *
1823     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1824     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
1825     * for this function in API level 22.
1826     *
1827     * @param accountType The account type associated with the authenticator
1828     *     to adjust
1829     * @param activity The {@link Activity} context to use for launching a new
1830     *     authenticator-defined sub-Activity to adjust authenticator settings;
1831     *     used only to call startActivity(); if null, the settings dialog will
1832     *     not be launched directly, but the necessary {@link Intent} will be
1833     *     returned to the caller instead
1834     * @param callback Callback to invoke when the request completes,
1835     *     null for no callback
1836     * @param handler {@link Handler} identifying the callback thread,
1837     *     null for the main thread
1838     * @return An {@link AccountManagerFuture} which resolves to a Bundle
1839     *     which is empty if properties were edited successfully, or
1840     *     if no activity was specified, contains only {@link #KEY_INTENT}
1841     *     needed to launch the authenticator's settings dialog.
1842     *     If an error occurred, {@link AccountManagerFuture#getResult()}
1843     *     throws:
1844     * <ul>
1845     * <li> {@link AuthenticatorException} if no authenticator was registered for
1846     *      this account type or the authenticator failed to respond
1847     * <li> {@link OperationCanceledException} if the operation was canceled for
1848     *      any reason, including the user canceling the settings dialog
1849     * <li> {@link IOException} if the authenticator experienced an I/O problem
1850     *      updating settings, usually because of network trouble
1851     * </ul>
1852     */
1853    public AccountManagerFuture<Bundle> editProperties(final String accountType,
1854            final Activity activity, final AccountManagerCallback<Bundle> callback,
1855            final Handler handler) {
1856        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1857        return new AmsTask(activity, handler, callback) {
1858            @Override
1859            public void doWork() throws RemoteException {
1860                mService.editProperties(mResponse, accountType, activity != null);
1861            }
1862        }.start();
1863    }
1864
1865    /**
1866     * @hide
1867     * Checks if the given account exists on any of the users on the device.
1868     * Only the system process can call this method.
1869     *
1870     * @param account The account to check for existence.
1871     * @return whether any user has this account
1872     */
1873    public boolean someUserHasAccount(@NonNull final Account account) {
1874        try {
1875            return mService.someUserHasAccount(account);
1876        } catch (RemoteException re) {
1877            throw new RuntimeException(re);
1878        }
1879    }
1880
1881    private void ensureNotOnMainThread() {
1882        final Looper looper = Looper.myLooper();
1883        if (looper != null && looper == mContext.getMainLooper()) {
1884            final IllegalStateException exception = new IllegalStateException(
1885                    "calling this from your main thread can lead to deadlock");
1886            Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1887                    exception);
1888            if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1889                throw exception;
1890            }
1891        }
1892    }
1893
1894    private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1895            final AccountManagerFuture<Bundle> future) {
1896        handler = handler == null ? mMainHandler : handler;
1897        handler.post(new Runnable() {
1898            @Override
1899            public void run() {
1900                callback.run(future);
1901            }
1902        });
1903    }
1904
1905    private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
1906            final Account[] accounts) {
1907        final Account[] accountsCopy = new Account[accounts.length];
1908        // send a copy to make sure that one doesn't
1909        // change what another sees
1910        System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1911        handler = (handler == null) ? mMainHandler : handler;
1912        handler.post(new Runnable() {
1913            @Override
1914            public void run() {
1915                try {
1916                    listener.onAccountsUpdated(accountsCopy);
1917                } catch (SQLException e) {
1918                    // Better luck next time.  If the problem was disk-full,
1919                    // the STORAGE_OK intent will re-trigger the update.
1920                    Log.e(TAG, "Can't update accounts", e);
1921                }
1922            }
1923        });
1924    }
1925
1926    private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
1927        final IAccountManagerResponse mResponse;
1928        final Handler mHandler;
1929        final AccountManagerCallback<Bundle> mCallback;
1930        final Activity mActivity;
1931        public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
1932            super(new Callable<Bundle>() {
1933                @Override
1934                public Bundle call() throws Exception {
1935                    throw new IllegalStateException("this should never be called");
1936                }
1937            });
1938
1939            mHandler = handler;
1940            mCallback = callback;
1941            mActivity = activity;
1942            mResponse = new Response();
1943        }
1944
1945        public final AccountManagerFuture<Bundle> start() {
1946            try {
1947                doWork();
1948            } catch (RemoteException e) {
1949                setException(e);
1950            }
1951            return this;
1952        }
1953
1954        @Override
1955        protected void set(Bundle bundle) {
1956            // TODO: somehow a null is being set as the result of the Future. Log this
1957            // case to help debug where this is occurring. When this bug is fixed this
1958            // condition statement should be removed.
1959            if (bundle == null) {
1960                Log.e(TAG, "the bundle must not be null", new Exception());
1961            }
1962            super.set(bundle);
1963        }
1964
1965        public abstract void doWork() throws RemoteException;
1966
1967        private Bundle internalGetResult(Long timeout, TimeUnit unit)
1968                throws OperationCanceledException, IOException, AuthenticatorException {
1969            if (!isDone()) {
1970                ensureNotOnMainThread();
1971            }
1972            try {
1973                if (timeout == null) {
1974                    return get();
1975                } else {
1976                    return get(timeout, unit);
1977                }
1978            } catch (CancellationException e) {
1979                throw new OperationCanceledException();
1980            } catch (TimeoutException e) {
1981                // fall through and cancel
1982            } catch (InterruptedException e) {
1983                // fall through and cancel
1984            } catch (ExecutionException e) {
1985                final Throwable cause = e.getCause();
1986                if (cause instanceof IOException) {
1987                    throw (IOException) cause;
1988                } else if (cause instanceof UnsupportedOperationException) {
1989                    throw new AuthenticatorException(cause);
1990                } else if (cause instanceof AuthenticatorException) {
1991                    throw (AuthenticatorException) cause;
1992                } else if (cause instanceof RuntimeException) {
1993                    throw (RuntimeException) cause;
1994                } else if (cause instanceof Error) {
1995                    throw (Error) cause;
1996                } else {
1997                    throw new IllegalStateException(cause);
1998                }
1999            } finally {
2000                cancel(true /* interrupt if running */);
2001            }
2002            throw new OperationCanceledException();
2003        }
2004
2005        @Override
2006        public Bundle getResult()
2007                throws OperationCanceledException, IOException, AuthenticatorException {
2008            return internalGetResult(null, null);
2009        }
2010
2011        @Override
2012        public Bundle getResult(long timeout, TimeUnit unit)
2013                throws OperationCanceledException, IOException, AuthenticatorException {
2014            return internalGetResult(timeout, unit);
2015        }
2016
2017        @Override
2018        protected void done() {
2019            if (mCallback != null) {
2020                postToHandler(mHandler, mCallback, this);
2021            }
2022        }
2023
2024        /** Handles the responses from the AccountManager */
2025        private class Response extends IAccountManagerResponse.Stub {
2026            @Override
2027            public void onResult(Bundle bundle) {
2028                Intent intent = bundle.getParcelable(KEY_INTENT);
2029                if (intent != null && mActivity != null) {
2030                    // since the user provided an Activity we will silently start intents
2031                    // that we see
2032                    mActivity.startActivity(intent);
2033                    // leave the Future running to wait for the real response to this request
2034                } else if (bundle.getBoolean("retry")) {
2035                    try {
2036                        doWork();
2037                    } catch (RemoteException e) {
2038                        // this will only happen if the system process is dead, which means
2039                        // we will be dying ourselves
2040                    }
2041                } else {
2042                    set(bundle);
2043                }
2044            }
2045
2046            @Override
2047            public void onError(int code, String message) {
2048                if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2049                        || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2050                    // the authenticator indicated that this request was canceled or we were
2051                    // forbidden to fulfill; cancel now
2052                    cancel(true /* mayInterruptIfRunning */);
2053                    return;
2054                }
2055                setException(convertErrorToException(code, message));
2056            }
2057        }
2058
2059    }
2060
2061    private abstract class BaseFutureTask<T> extends FutureTask<T> {
2062        final public IAccountManagerResponse mResponse;
2063        final Handler mHandler;
2064
2065        public BaseFutureTask(Handler handler) {
2066            super(new Callable<T>() {
2067                @Override
2068                public T call() throws Exception {
2069                    throw new IllegalStateException("this should never be called");
2070                }
2071            });
2072            mHandler = handler;
2073            mResponse = new Response();
2074        }
2075
2076        public abstract void doWork() throws RemoteException;
2077
2078        public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
2079
2080        protected void postRunnableToHandler(Runnable runnable) {
2081            Handler handler = (mHandler == null) ? mMainHandler : mHandler;
2082            handler.post(runnable);
2083        }
2084
2085        protected void startTask() {
2086            try {
2087                doWork();
2088            } catch (RemoteException e) {
2089                setException(e);
2090            }
2091        }
2092
2093        protected class Response extends IAccountManagerResponse.Stub {
2094            @Override
2095            public void onResult(Bundle bundle) {
2096                try {
2097                    T result = bundleToResult(bundle);
2098                    if (result == null) {
2099                        return;
2100                    }
2101                    set(result);
2102                    return;
2103                } catch (ClassCastException e) {
2104                    // we will set the exception below
2105                } catch (AuthenticatorException e) {
2106                    // we will set the exception below
2107                }
2108                onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
2109            }
2110
2111            @Override
2112            public void onError(int code, String message) {
2113                if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2114                        || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2115                    // the authenticator indicated that this request was canceled or we were
2116                    // forbidden to fulfill; cancel now
2117                    cancel(true /* mayInterruptIfRunning */);
2118                    return;
2119                }
2120                setException(convertErrorToException(code, message));
2121            }
2122        }
2123    }
2124
2125    private abstract class Future2Task<T>
2126            extends BaseFutureTask<T> implements AccountManagerFuture<T> {
2127        final AccountManagerCallback<T> mCallback;
2128        public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
2129            super(handler);
2130            mCallback = callback;
2131        }
2132
2133        @Override
2134        protected void done() {
2135            if (mCallback != null) {
2136                postRunnableToHandler(new Runnable() {
2137                    @Override
2138                    public void run() {
2139                        mCallback.run(Future2Task.this);
2140                    }
2141                });
2142            }
2143        }
2144
2145        public Future2Task<T> start() {
2146            startTask();
2147            return this;
2148        }
2149
2150        private T internalGetResult(Long timeout, TimeUnit unit)
2151                throws OperationCanceledException, IOException, AuthenticatorException {
2152            if (!isDone()) {
2153                ensureNotOnMainThread();
2154            }
2155            try {
2156                if (timeout == null) {
2157                    return get();
2158                } else {
2159                    return get(timeout, unit);
2160                }
2161            } catch (InterruptedException e) {
2162                // fall through and cancel
2163            } catch (TimeoutException e) {
2164                // fall through and cancel
2165            } catch (CancellationException e) {
2166                // fall through and cancel
2167            } catch (ExecutionException e) {
2168                final Throwable cause = e.getCause();
2169                if (cause instanceof IOException) {
2170                    throw (IOException) cause;
2171                } else if (cause instanceof UnsupportedOperationException) {
2172                    throw new AuthenticatorException(cause);
2173                } else if (cause instanceof AuthenticatorException) {
2174                    throw (AuthenticatorException) cause;
2175                } else if (cause instanceof RuntimeException) {
2176                    throw (RuntimeException) cause;
2177                } else if (cause instanceof Error) {
2178                    throw (Error) cause;
2179                } else {
2180                    throw new IllegalStateException(cause);
2181                }
2182            } finally {
2183                cancel(true /* interrupt if running */);
2184            }
2185            throw new OperationCanceledException();
2186        }
2187
2188        @Override
2189        public T getResult()
2190                throws OperationCanceledException, IOException, AuthenticatorException {
2191            return internalGetResult(null, null);
2192        }
2193
2194        @Override
2195        public T getResult(long timeout, TimeUnit unit)
2196                throws OperationCanceledException, IOException, AuthenticatorException {
2197            return internalGetResult(timeout, unit);
2198        }
2199
2200    }
2201
2202    private Exception convertErrorToException(int code, String message) {
2203        if (code == ERROR_CODE_NETWORK_ERROR) {
2204            return new IOException(message);
2205        }
2206
2207        if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
2208            return new UnsupportedOperationException(message);
2209        }
2210
2211        if (code == ERROR_CODE_INVALID_RESPONSE) {
2212            return new AuthenticatorException(message);
2213        }
2214
2215        if (code == ERROR_CODE_BAD_ARGUMENTS) {
2216            return new IllegalArgumentException(message);
2217        }
2218
2219        return new AuthenticatorException(message);
2220    }
2221
2222    private class GetAuthTokenByTypeAndFeaturesTask
2223            extends AmsTask implements AccountManagerCallback<Bundle> {
2224        GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2225                final String[] features, Activity activityForPrompting,
2226                final Bundle addAccountOptions, final Bundle loginOptions,
2227                AccountManagerCallback<Bundle> callback, Handler handler) {
2228            super(activityForPrompting, handler, callback);
2229            if (accountType == null) throw new IllegalArgumentException("account type is null");
2230            mAccountType = accountType;
2231            mAuthTokenType = authTokenType;
2232            mFeatures = features;
2233            mAddAccountOptions = addAccountOptions;
2234            mLoginOptions = loginOptions;
2235            mMyCallback = this;
2236        }
2237        volatile AccountManagerFuture<Bundle> mFuture = null;
2238        final String mAccountType;
2239        final String mAuthTokenType;
2240        final String[] mFeatures;
2241        final Bundle mAddAccountOptions;
2242        final Bundle mLoginOptions;
2243        final AccountManagerCallback<Bundle> mMyCallback;
2244        private volatile int mNumAccounts = 0;
2245
2246        @Override
2247        public void doWork() throws RemoteException {
2248            getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2249                    new AccountManagerCallback<Account[]>() {
2250                        @Override
2251                        public void run(AccountManagerFuture<Account[]> future) {
2252                            Account[] accounts;
2253                            try {
2254                                accounts = future.getResult();
2255                            } catch (OperationCanceledException e) {
2256                                setException(e);
2257                                return;
2258                            } catch (IOException e) {
2259                                setException(e);
2260                                return;
2261                            } catch (AuthenticatorException e) {
2262                                setException(e);
2263                                return;
2264                            }
2265
2266                            mNumAccounts = accounts.length;
2267
2268                            if (accounts.length == 0) {
2269                                if (mActivity != null) {
2270                                    // no accounts, add one now. pretend that the user directly
2271                                    // made this request
2272                                    mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2273                                            mAddAccountOptions, mActivity, mMyCallback, mHandler);
2274                                } else {
2275                                    // send result since we can't prompt to add an account
2276                                    Bundle result = new Bundle();
2277                                    result.putString(KEY_ACCOUNT_NAME, null);
2278                                    result.putString(KEY_ACCOUNT_TYPE, null);
2279                                    result.putString(KEY_AUTHTOKEN, null);
2280                                    try {
2281                                        mResponse.onResult(result);
2282                                    } catch (RemoteException e) {
2283                                        // this will never happen
2284                                    }
2285                                    // we are done
2286                                }
2287                            } else if (accounts.length == 1) {
2288                                // have a single account, return an authtoken for it
2289                                if (mActivity == null) {
2290                                    mFuture = getAuthToken(accounts[0], mAuthTokenType,
2291                                            false /* notifyAuthFailure */, mMyCallback, mHandler);
2292                                } else {
2293                                    mFuture = getAuthToken(accounts[0],
2294                                            mAuthTokenType, mLoginOptions,
2295                                            mActivity, mMyCallback, mHandler);
2296                                }
2297                            } else {
2298                                if (mActivity != null) {
2299                                    IAccountManagerResponse chooseResponse =
2300                                            new IAccountManagerResponse.Stub() {
2301                                        @Override
2302                                        public void onResult(Bundle value) throws RemoteException {
2303                                            Account account = new Account(
2304                                                    value.getString(KEY_ACCOUNT_NAME),
2305                                                    value.getString(KEY_ACCOUNT_TYPE));
2306                                            mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2307                                                    mActivity, mMyCallback, mHandler);
2308                                        }
2309
2310                                        @Override
2311                                        public void onError(int errorCode, String errorMessage)
2312                                                throws RemoteException {
2313                                            mResponse.onError(errorCode, errorMessage);
2314                                        }
2315                                    };
2316                                    // have many accounts, launch the chooser
2317                                    Intent intent = new Intent();
2318                                    ComponentName componentName = ComponentName.unflattenFromString(
2319                                            Resources.getSystem().getString(
2320                                                    R.string.config_chooseAccountActivity));
2321                                    intent.setClassName(componentName.getPackageName(),
2322                                            componentName.getClassName());
2323                                    intent.putExtra(KEY_ACCOUNTS, accounts);
2324                                    intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
2325                                            new AccountManagerResponse(chooseResponse));
2326                                    mActivity.startActivity(intent);
2327                                    // the result will arrive via the IAccountManagerResponse
2328                                } else {
2329                                    // send result since we can't prompt to select an account
2330                                    Bundle result = new Bundle();
2331                                    result.putString(KEY_ACCOUNTS, null);
2332                                    try {
2333                                        mResponse.onResult(result);
2334                                    } catch (RemoteException e) {
2335                                        // this will never happen
2336                                    }
2337                                    // we are done
2338                                }
2339                            }
2340                        }}, mHandler);
2341        }
2342
2343        @Override
2344        public void run(AccountManagerFuture<Bundle> future) {
2345            try {
2346                final Bundle result = future.getResult();
2347                if (mNumAccounts == 0) {
2348                    final String accountName = result.getString(KEY_ACCOUNT_NAME);
2349                    final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2350                    if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2351                        setException(new AuthenticatorException("account not in result"));
2352                        return;
2353                    }
2354                    final Account account = new Account(accountName, accountType);
2355                    mNumAccounts = 1;
2356                    getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2357                            mMyCallback, mHandler);
2358                    return;
2359                }
2360                set(result);
2361            } catch (OperationCanceledException e) {
2362                cancel(true /* mayInterruptIfRUnning */);
2363            } catch (IOException e) {
2364                setException(e);
2365            } catch (AuthenticatorException e) {
2366                setException(e);
2367            }
2368        }
2369    }
2370
2371    /**
2372     * This convenience helper combines the functionality of
2373     * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2374     * {@link #addAccount}.
2375     *
2376     * <p>This method gets a list of the accounts matching the
2377     * specified type and feature set; if there is exactly one, it is
2378     * used; if there are more than one, the user is prompted to pick one;
2379     * if there are none, the user is prompted to add one.  Finally,
2380     * an auth token is acquired for the chosen account.
2381     *
2382     * <p>This method may be called from any thread, but the returned
2383     * {@link AccountManagerFuture} must not be used on the main thread.
2384     *
2385     * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
2386     * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
2387     * this function in API level 22.
2388     *
2389     * @param accountType The account type required
2390     *     (see {@link #getAccountsByType}), must not be null
2391     * @param authTokenType The desired auth token type
2392     *     (see {@link #getAuthToken}), must not be null
2393     * @param features Required features for the account
2394     *     (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2395     * @param activity The {@link Activity} context to use for launching new
2396     *     sub-Activities to prompt to add an account, select an account,
2397     *     and/or enter a password, as necessary; used only to call
2398     *     startActivity(); should not be null
2399     * @param addAccountOptions Authenticator-specific options to use for
2400     *     adding new accounts; may be null or empty
2401     * @param getAuthTokenOptions Authenticator-specific options to use for
2402     *     getting auth tokens; may be null or empty
2403     * @param callback Callback to invoke when the request completes,
2404     *     null for no callback
2405     * @param handler {@link Handler} identifying the callback thread,
2406     *     null for the main thread
2407     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2408     *     at least the following fields:
2409     * <ul>
2410     * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2411     * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2412     * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
2413     * </ul>
2414     *
2415     * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
2416     * <ul>
2417     * <li> {@link AuthenticatorException} if no authenticator was registered for
2418     *      this account type or the authenticator failed to respond
2419     * <li> {@link OperationCanceledException} if the operation was canceled for
2420     *      any reason, including the user canceling any operation
2421     * <li> {@link IOException} if the authenticator experienced an I/O problem
2422     *      updating settings, usually because of network trouble
2423     * </ul>
2424     */
2425    public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
2426            final String accountType, final String authTokenType, final String[] features,
2427            final Activity activity, final Bundle addAccountOptions,
2428            final Bundle getAuthTokenOptions,
2429            final AccountManagerCallback<Bundle> callback, final Handler handler) {
2430        if (accountType == null) throw new IllegalArgumentException("account type is null");
2431        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2432        final GetAuthTokenByTypeAndFeaturesTask task =
2433                new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
2434                activity, addAccountOptions, getAuthTokenOptions, callback, handler);
2435        task.start();
2436        return task;
2437    }
2438
2439    /**
2440     * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
2441     * String, String[], Bundle)}.
2442     *
2443     * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2444     * accounts.
2445     * The caller will then typically start the activity by calling
2446     * <code>startActivityForResult(intent, ...);</code>.
2447     * <p>
2448     * On success the activity returns a Bundle with the account name and type specified using
2449     * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2450     * <p>
2451     * The most common case is to call this with one account type, e.g.:
2452     * <p>
2453     * <pre>  newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
2454     * null, null, null);</pre>
2455     * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2456     * selected one, according to the caller's definition of selected.
2457     * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
2458     * shown. If not specified then this field will not limit the displayed accounts.
2459     * @param allowableAccountTypes an optional string array of account types. These are used
2460     * both to filter the shown accounts and to filter the list of account types that are shown
2461     * when adding an account. If not specified then this field will not limit the displayed
2462     * account types when adding an account.
2463     * @param alwaysPromptForAccount boolean that is ignored.
2464     * @param descriptionOverrideText if non-null this string is used as the description in the
2465     * accounts chooser screen rather than the default
2466     * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2467     * authTokenType parameter
2468     * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2469     * requiredFeatures parameter
2470     * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2471     * parameter
2472     * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2473     */
2474    @Deprecated
2475    static public Intent newChooseAccountIntent(
2476            Account selectedAccount,
2477            ArrayList<Account> allowableAccounts,
2478            String[] allowableAccountTypes,
2479            boolean alwaysPromptForAccount,
2480            String descriptionOverrideText,
2481            String addAccountAuthTokenType,
2482            String[] addAccountRequiredFeatures,
2483            Bundle addAccountOptions) {
2484        return newChooseAccountIntent(
2485                selectedAccount,
2486                allowableAccounts,
2487                allowableAccountTypes,
2488                descriptionOverrideText,
2489                addAccountAuthTokenType,
2490                addAccountRequiredFeatures,
2491                addAccountOptions);
2492    }
2493
2494    /**
2495     * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2496     * accounts.
2497     * The caller will then typically start the activity by calling
2498     * <code>startActivityForResult(intent, ...);</code>.
2499     * <p>
2500     * On success the activity returns a Bundle with the account name and type specified using
2501     * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2502     * <p>
2503     * The most common case is to call this with one account type, e.g.:
2504     * <p>
2505     * <pre>  newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null,
2506     * null);</pre>
2507     * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2508     * selected one, according to the caller's definition of selected.
2509     * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
2510     * shown. If not specified then this field will not limit the displayed accounts.
2511     * @param allowableAccountTypes an optional string array of account types. These are used
2512     * both to filter the shown accounts and to filter the list of account types that are shown
2513     * when adding an account. If not specified then this field will not limit the displayed
2514     * account types when adding an account.
2515     * @param descriptionOverrideText if non-null this string is used as the description in the
2516     * accounts chooser screen rather than the default
2517     * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2518     * authTokenType parameter
2519     * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2520     * requiredFeatures parameter
2521     * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2522     * parameter
2523     * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2524     */
2525    static public Intent newChooseAccountIntent(
2526            Account selectedAccount,
2527            List<Account> allowableAccounts,
2528            String[] allowableAccountTypes,
2529            String descriptionOverrideText,
2530            String addAccountAuthTokenType,
2531            String[] addAccountRequiredFeatures,
2532            Bundle addAccountOptions) {
2533        Intent intent = new Intent();
2534        ComponentName componentName = ComponentName.unflattenFromString(
2535                Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2536        intent.setClassName(componentName.getPackageName(),
2537                componentName.getClassName());
2538        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
2539                allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts));
2540        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2541                allowableAccountTypes);
2542        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2543                addAccountOptions);
2544        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
2545        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2546                descriptionOverrideText);
2547        intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2548                addAccountAuthTokenType);
2549        intent.putExtra(
2550                ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2551                addAccountRequiredFeatures);
2552        return intent;
2553    }
2554
2555    private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
2556            Maps.newHashMap();
2557
2558    /**
2559     * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2560     * so that it can read the updated list of accounts and send them to the listener
2561     * in mAccountsUpdatedListeners.
2562     */
2563    private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
2564        @Override
2565        public void onReceive(final Context context, final Intent intent) {
2566            final Account[] accounts = getAccounts();
2567            // send the result to the listeners
2568            synchronized (mAccountsUpdatedListeners) {
2569                for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
2570                        mAccountsUpdatedListeners.entrySet()) {
2571                    postToHandler(entry.getValue(), entry.getKey(), accounts);
2572                }
2573            }
2574        }
2575    };
2576
2577    /**
2578     * Adds an {@link OnAccountsUpdateListener} to this instance of the
2579     * {@link AccountManager}.  This listener will be notified whenever the
2580     * list of accounts on the device changes.
2581     *
2582     * <p>As long as this listener is present, the AccountManager instance
2583     * will not be garbage-collected, and neither will the {@link Context}
2584     * used to retrieve it, which may be a large Activity instance.  To avoid
2585     * memory leaks, you must remove this listener before then.  Normally
2586     * listeners are added in an Activity or Service's {@link Activity#onCreate}
2587     * and removed in {@link Activity#onDestroy}.
2588     *
2589     * <p>The listener will only be informed of accounts that would be returned
2590     * to the caller via {@link #getAccounts()}. Typically this means that to
2591     * get any accounts, the caller will need to be grated the GET_ACCOUNTS
2592     * permission.
2593     *
2594     * <p>It is safe to call this method from the main thread.
2595     *
2596     * @param listener The listener to send notifications to
2597     * @param handler {@link Handler} identifying the thread to use
2598     *     for notifications, null for the main thread
2599     * @param updateImmediately If true, the listener will be invoked
2600     *     (on the handler thread) right away with the current account list
2601     * @throws IllegalArgumentException if listener is null
2602     * @throws IllegalStateException if listener was already added
2603     */
2604    @RequiresPermission(GET_ACCOUNTS)
2605    public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
2606            Handler handler, boolean updateImmediately) {
2607        if (listener == null) {
2608            throw new IllegalArgumentException("the listener is null");
2609        }
2610        synchronized (mAccountsUpdatedListeners) {
2611            if (mAccountsUpdatedListeners.containsKey(listener)) {
2612                throw new IllegalStateException("this listener is already added");
2613            }
2614            final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2615
2616            mAccountsUpdatedListeners.put(listener, handler);
2617
2618            if (wasEmpty) {
2619                // Register a broadcast receiver to monitor account changes
2620                IntentFilter intentFilter = new IntentFilter();
2621                intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
2622                // To recover from disk-full.
2623                intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
2624                mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2625            }
2626        }
2627
2628        if (updateImmediately) {
2629            postToHandler(handler, listener, getAccounts());
2630        }
2631    }
2632
2633    /**
2634     * Removes an {@link OnAccountsUpdateListener} previously registered with
2635     * {@link #addOnAccountsUpdatedListener}.  The listener will no longer
2636     * receive notifications of account changes.
2637     *
2638     * <p>It is safe to call this method from the main thread.
2639     *
2640     * <p>No permission is required to call this method.
2641     *
2642     * @param listener The previously added listener to remove
2643     * @throws IllegalArgumentException if listener is null
2644     * @throws IllegalStateException if listener was not already added
2645     */
2646    public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
2647        if (listener == null) throw new IllegalArgumentException("listener is null");
2648        synchronized (mAccountsUpdatedListeners) {
2649            if (!mAccountsUpdatedListeners.containsKey(listener)) {
2650                Log.e(TAG, "Listener was not previously added");
2651                return;
2652            }
2653            mAccountsUpdatedListeners.remove(listener);
2654            if (mAccountsUpdatedListeners.isEmpty()) {
2655                mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2656            }
2657        }
2658    }
2659
2660    /**
2661     * Asks the user to authenticate with an account of a specified type. The
2662     * authenticator for this account type processes this request with the
2663     * appropriate user interface. If the user does elect to authenticate with a
2664     * new account, a bundle of session data for installing the account later is
2665     * returned with optional account password and account status token.
2666     * <p>
2667     * This method may be called from any thread, but the returned
2668     * {@link AccountManagerFuture} must not be used on the main thread.
2669     * <p>
2670     * <p>
2671     * <b>NOTE:</b> The account will not be installed to the device by calling
2672     * this api alone. #finishSession should be called after this to install the
2673     * account on device.
2674     *
2675     * @param accountType The type of account to add; must not be null
2676     * @param authTokenType The type of auth token (see {@link #getAuthToken})
2677     *            this account will need to be able to generate, null for none
2678     * @param requiredFeatures The features (see {@link #hasFeatures}) this
2679     *            account must have, null for none
2680     * @param options Authenticator-specific options for the request, may be
2681     *            null or empty
2682     * @param activity The {@link Activity} context to use for launching a new
2683     *            authenticator-defined sub-Activity to prompt the user to
2684     *            create an account; used only to call startActivity(); if null,
2685     *            the prompt will not be launched directly, but the necessary
2686     *            {@link Intent} will be returned to the caller instead
2687     * @param callback Callback to invoke when the request completes, null for
2688     *            no callback
2689     * @param handler {@link Handler} identifying the callback thread, null for
2690     *            the main thread
2691     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2692     *         these fields if activity was specified and user was authenticated
2693     *         with an account:
2694     *         <ul>
2695     *         <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
2696     *         adding the the to the device later.
2697     *         <li>{@link #KEY_PASSWORD} - optional, the password or password
2698     *         hash of the account.
2699     *         <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
2700     *         status of the account
2701     *         </ul>
2702     *         If no activity was specified, the returned Bundle contains only
2703     *         {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2704     *         actual account creation process. If authenticator doesn't support
2705     *         this method, the returned Bundle contains only
2706     *         {@link #KEY_ACCOUNT_SESSION_BUNDLE} with encrypted
2707     *         {@code options} needed to add account later. If an error
2708     *         occurred, {@link AccountManagerFuture#getResult()} throws:
2709     *         <ul>
2710     *         <li>{@link AuthenticatorException} if no authenticator was
2711     *         registered for this account type or the authenticator failed to
2712     *         respond
2713     *         <li>{@link OperationCanceledException} if the operation was
2714     *         canceled for any reason, including the user canceling the
2715     *         creation process or adding accounts (of this type) has been
2716     *         disabled by policy
2717     *         <li>{@link IOException} if the authenticator experienced an I/O
2718     *         problem creating a new account, usually because of network
2719     *         trouble
2720     *         </ul>
2721     * @see #finishSession
2722     * @hide
2723     */
2724    @SystemApi
2725    public AccountManagerFuture<Bundle> startAddAccountSession(
2726            final String accountType,
2727            final String authTokenType,
2728            final String[] requiredFeatures,
2729            final Bundle options,
2730            final Activity activity,
2731            AccountManagerCallback<Bundle> callback,
2732            Handler handler) {
2733        if (accountType == null) throw new IllegalArgumentException("accountType is null");
2734        final Bundle optionsIn = new Bundle();
2735        if (options != null) {
2736            optionsIn.putAll(options);
2737        }
2738        optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
2739
2740        return new AmsTask(activity, handler, callback) {
2741            @Override
2742            public void doWork() throws RemoteException {
2743                mService.startAddAccountSession(
2744                        mResponse,
2745                        accountType,
2746                        authTokenType,
2747                        requiredFeatures,
2748                        activity != null,
2749                        optionsIn);
2750            }
2751        }.start();
2752    }
2753
2754    /**
2755     * Asks the user to enter a new password for an account but not updating the
2756     * saved credentials for the account until {@link #finishSession} is called.
2757     * <p>
2758     * This method may be called from any thread, but the returned
2759     * {@link AccountManagerFuture} must not be used on the main thread.
2760     * <p>
2761     * <b>NOTE:</b> The saved credentials for the account alone will not be
2762     * updated by calling this API alone. #finishSession should be called after
2763     * this to update local credentials
2764     *
2765     * @param account The account to update credentials for
2766     * @param authTokenType The credentials entered must allow an auth token of
2767     *            this type to be created (but no actual auth token is
2768     *            returned); may be null
2769     * @param options Authenticator-specific options for the request; may be
2770     *            null or empty
2771     * @param activity The {@link Activity} context to use for launching a new
2772     *            authenticator-defined sub-Activity to prompt the user to enter
2773     *            a password; used only to call startActivity(); if null, the
2774     *            prompt will not be launched directly, but the necessary
2775     *            {@link Intent} will be returned to the caller instead
2776     * @param callback Callback to invoke when the request completes, null for
2777     *            no callback
2778     * @param handler {@link Handler} identifying the callback thread, null for
2779     *            the main thread
2780     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2781     *         these fields if an activity was supplied and user was
2782     *         successfully re-authenticated to the account:
2783     *         <ul>
2784     *         <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
2785     *         updating the local credentials on device later.
2786     *         <li>{@link #KEY_PASSWORD} - optional, the password or password
2787     *         hash of the account
2788     *         <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
2789     *         status of the account
2790     *         </ul>
2791     *         If no activity was specified, the returned Bundle contains
2792     *         {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2793     *         password prompt. If an error occurred,
2794     *         {@link AccountManagerFuture#getResult()} throws:
2795     *         <ul>
2796     *         <li>{@link AuthenticatorException} if the authenticator failed to
2797     *         respond
2798     *         <li>{@link OperationCanceledException} if the operation was
2799     *         canceled for any reason, including the user canceling the
2800     *         password prompt
2801     *         <li>{@link IOException} if the authenticator experienced an I/O
2802     *         problem verifying the password, usually because of network
2803     *         trouble
2804     *         </ul>
2805     * @see #finishSession
2806     * @hide
2807     */
2808    @SystemApi
2809    public AccountManagerFuture<Bundle> startUpdateCredentialsSession(
2810            final Account account,
2811            final String authTokenType,
2812            final Bundle options,
2813            final Activity activity,
2814            final AccountManagerCallback<Bundle> callback,
2815            final Handler handler) {
2816        if (account == null) {
2817            throw new IllegalArgumentException("account is null");
2818        }
2819        return new AmsTask(activity, handler, callback) {
2820            @Override
2821            public void doWork() throws RemoteException {
2822                mService.startUpdateCredentialsSession(
2823                        mResponse,
2824                        account,
2825                        authTokenType,
2826                        activity != null,
2827                        options);
2828            }
2829        }.start();
2830    }
2831
2832    /**
2833     * Finishes the session started by {@link #startAddAccountSession} or
2834     * {@link #startUpdateCredentialsSession}. This will either add the account
2835     * to AccountManager or update the local credentials stored.
2836     * <p>
2837     * This method may be called from any thread, but the returned
2838     * {@link AccountManagerFuture} must not be used on the main thread.
2839     *
2840     * @param sessionBundle a {@link Bundle} created by {@link #startAddAccountSession} or
2841     *            {@link #startUpdateCredentialsSession}
2842     * @param activity The {@link Activity} context to use for launching a new
2843     *            authenticator-defined sub-Activity to prompt the user to
2844     *            create an account or reauthenticate existing account; used
2845     *            only to call startActivity(); if null, the prompt will not
2846     *            be launched directly, but the necessary {@link Intent} will
2847     *            be returned to the caller instead
2848     * @param callback Callback to invoke when the request completes, null for
2849     *            no callback
2850     * @param handler {@link Handler} identifying the callback thread, null for
2851     *            the main thread
2852     * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2853     *         these fields if an activity was supplied and an account was added
2854     *         to device or local credentials were updated::
2855     *         <ul>
2856     *         <li>{@link #KEY_ACCOUNT_NAME} - the name of the account created
2857     *         <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account
2858     *         </ul>
2859     *         If no activity was specified and additional information is needed
2860     *         from user, the returned Bundle may contains only
2861     *         {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2862     *         actual account creation process. If an error occurred,
2863     *         {@link AccountManagerFuture#getResult()} throws:
2864     *         <ul>
2865     *         <li>{@link AuthenticatorException} if no authenticator was
2866     *         registered for this account type or the authenticator failed to
2867     *         respond
2868     *         <li>{@link OperationCanceledException} if the operation was
2869     *         canceled for any reason, including the user canceling the
2870     *         creation process or adding accounts (of this type) has been
2871     *         disabled by policy
2872     *         <li>{@link IOException} if the authenticator experienced an I/O
2873     *         problem creating a new account, usually because of network
2874     *         trouble
2875     *         </ul>
2876     * @see #startAddAccountSession and #startUpdateCredentialsSession
2877     * @hide
2878     */
2879    @SystemApi
2880    public AccountManagerFuture<Bundle> finishSession(
2881            final Bundle sessionBundle,
2882            final Activity activity,
2883            AccountManagerCallback<Bundle> callback,
2884            Handler handler) {
2885        return finishSessionAsUser(
2886                sessionBundle,
2887                activity,
2888                Process.myUserHandle(),
2889                callback,
2890                handler);
2891    }
2892
2893    /**
2894     * @see #finishSession
2895     * @hide
2896     */
2897    @SystemApi
2898    public AccountManagerFuture<Bundle> finishSessionAsUser(
2899            final Bundle sessionBundle,
2900            final Activity activity,
2901            final UserHandle userHandle,
2902            AccountManagerCallback<Bundle> callback,
2903            Handler handler) {
2904        if (sessionBundle == null) {
2905            throw new IllegalArgumentException("sessionBundle is null");
2906        }
2907
2908        /* Add information required by add account flow */
2909        final Bundle appInfo = new Bundle();
2910        appInfo.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
2911
2912        return new AmsTask(activity, handler, callback) {
2913            @Override
2914            public void doWork() throws RemoteException {
2915                mService.finishSessionAsUser(
2916                        mResponse,
2917                        sessionBundle,
2918                        activity != null,
2919                        appInfo,
2920                        userHandle.getIdentifier());
2921            }
2922        }.start();
2923    }
2924
2925    /**
2926     * Checks whether {@link #updateCredentials} or {@link #startUpdateCredentialsSession} should be
2927     * called with respect to the specified account.
2928     * <p>
2929     * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
2930     * not be used on the main thread.
2931     *
2932     * @param account The {@link Account} to be checked whether {@link #updateCredentials} or
2933     * {@link #startUpdateCredentialsSession} should be called
2934     * @param statusToken a String of token to check account staus
2935     * @param callback Callback to invoke when the request completes, null for no callback
2936     * @param handler {@link Handler} identifying the callback thread, null for the main thread
2937     * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the credentials
2938     *         of the account should be updated.
2939     * @hide
2940     */
2941    @SystemApi
2942    public AccountManagerFuture<Boolean> isCredentialsUpdateSuggested(
2943            final Account account,
2944            final String statusToken,
2945            AccountManagerCallback<Boolean> callback,
2946            Handler handler) {
2947        if (account == null) {
2948            throw new IllegalArgumentException("account is null");
2949        }
2950
2951        if (TextUtils.isEmpty(statusToken)) {
2952            throw new IllegalArgumentException("status token is empty");
2953        }
2954
2955        return new Future2Task<Boolean>(handler, callback) {
2956            @Override
2957            public void doWork() throws RemoteException {
2958                mService.isCredentialsUpdateSuggested(
2959                        mResponse,
2960                        account,
2961                        statusToken);
2962            }
2963            @Override
2964            public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
2965                if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
2966                    throw new AuthenticatorException("no result in response");
2967                }
2968                return bundle.getBoolean(KEY_BOOLEAN_RESULT);
2969            }
2970        }.start();
2971    }
2972}
2973