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