blob: def0ff9878995fb240dbe574cad30a141f07541c [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
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
Sandra Kwan390c9d22016-01-12 14:13:37 -080019import static android.Manifest.permission.GET_ACCOUNTS;
20
Dmitry Dementyev52745472016-12-02 10:27:45 -080021import android.annotation.IntDef;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070022import android.annotation.NonNull;
Tor Norbye80b530a2015-04-23 16:36:09 -070023import android.annotation.RequiresPermission;
24import android.annotation.Size;
Sandra Kwana578d112015-12-16 16:01:43 -080025import android.annotation.SystemApi;
Fred Quintana60307342009-03-24 22:48:12 -070026import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080027import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070028import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070029import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080030import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070031import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070032import android.content.IntentSender;
Amith Yamasani12b8e132013-03-14 10:48:07 -070033import android.content.res.Resources;
Dmitry Dementyev52745472016-12-02 10:27:45 -080034import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageManager;
Costin Manolacheb6437242009-09-10 16:14:12 -070036import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080037import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070038import android.os.Bundle;
39import android.os.Handler;
40import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070041import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080042import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080043import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080044import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080045import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080046import android.util.Log;
47
48import com.android.internal.R;
49import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070050
Fred Quintanaa698f422009-04-08 19:14:54 -070051import java.io.IOException;
Dmitry Dementyev52745472016-12-02 10:27:45 -080052import java.lang.annotation.Retention;
53import java.lang.annotation.RetentionPolicy;
54import java.lang.SuppressWarnings;
Fred Quintana1121bb52011-09-14 23:19:35 -070055import java.util.ArrayList;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080056import java.util.Arrays;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080057import java.util.HashMap;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080058import java.util.HashSet;
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -070059import java.util.List;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080060import java.util.Map;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080061import java.util.Set;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import java.util.concurrent.Callable;
63import java.util.concurrent.CancellationException;
64import java.util.concurrent.ExecutionException;
65import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080067import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070068
69/**
Dan Egnor661f0132010-02-19 11:23:00 -080070 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070071 * online accounts. The user enters credentials (username and password) once
72 * per account, granting applications access to online resources with
73 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070074 *
Dan Egnor661f0132010-02-19 11:23:00 -080075 * <p>Different online services have different ways of handling accounts and
76 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070077 * modules for different <em>account types</em>. Authenticators (which may be
78 * written by third parties) handle the actual details of validating account
79 * credentials and storing account information. For example, Google, Facebook,
80 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080081 *
82 * <p>Many servers support some notion of an <em>authentication token</em>,
83 * which can be used to authenticate a request to the server without sending
84 * the user's actual password. (Auth tokens are normally created with a
85 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070086 * can generate auth tokens for applications, so the application doesn't need to
87 * handle passwords directly. Auth tokens are normally reusable and cached by
88 * AccountManager, but must be refreshed periodically. It's the responsibility
89 * of applications to <em>invalidate</em> auth tokens when they stop working so
90 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080091 *
92 * <p>Applications accessing a server normally go through these steps:
93 *
94 * <ul>
95 * <li>Get an instance of AccountManager using {@link #get(Context)}.
96 *
97 * <li>List the available accounts using {@link #getAccountsByType} or
98 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
99 * be interested in accounts with one particular <em>type</em>, which
100 * identifies the authenticator. Account <em>features</em> are used to
101 * identify particular account subtypes and capabilities. Both the account
102 * type and features are authenticator-specific strings, and must be known by
103 * the application in coordination with its preferred authenticators.
104 *
105 * <li>Select one or more of the available accounts, possibly by asking the
106 * user for their preference. If no suitable accounts are available,
107 * {@link #addAccount} may be called to prompt the user to create an
108 * account of the appropriate type.
109 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700110 * <li><b>Important:</b> If the application is using a previously remembered
111 * account selection, it must make sure the account is still in the list
112 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
113 * for an account no longer on the device results in an undefined failure.
114 *
Dan Egnor661f0132010-02-19 11:23:00 -0800115 * <li>Request an auth token for the selected account(s) using one of the
116 * {@link #getAuthToken} methods or related helpers. Refer to the description
117 * of each method for exact usage and error handling details.
118 *
119 * <li>Make the request using the auth token. The form of the auth token,
120 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700121 * service you are accessing. The application may use whatever network and
122 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800123 *
124 * <li><b>Important:</b> If the request fails with an authentication error,
125 * it could be that a cached auth token is stale and no longer honored by
126 * the server. The application must call {@link #invalidateAuthToken} to remove
127 * the token from the cache, otherwise requests will continue failing! After
128 * invalidating the auth token, immediately go back to the "Request an auth
129 * token" step above. If the process fails the second time, then it can be
130 * treated as a "genuine" authentication failure and the user notified or other
131 * appropriate actions taken.
132 * </ul>
133 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700134 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800135 * prompt for credentials, present options, or ask the user to add an account.
136 * The caller may choose whether to allow AccountManager to directly launch the
137 * necessary user interface and wait for the user, or to return an Intent which
138 * the caller may use to launch the interface, or (in some cases) to install a
139 * notification which the user can select at any time to launch the interface.
140 * To have AccountManager launch the interface directly, the caller must supply
141 * the current foreground {@link Activity} context.
142 *
143 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700144 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800145 * run asynchronously. If a callback is provided then
146 * {@link AccountManagerCallback#run} will be invoked on the Handler's
147 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700148 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
149 * on the {@link AccountManagerFuture} returned by the method (and also passed
150 * to the callback). This method waits for the operation to complete (if
151 * necessary) and either returns the result or throws an exception if an error
152 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800153 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700154 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800155 *
156 * <p>Requests which may block, including
157 * {@link AccountManagerFuture#getResult()}, must never be called on
158 * the application's main event thread. These operations throw
159 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700160 */
161public class AccountManager {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800162
Fred Quintana60307342009-03-24 22:48:12 -0700163 private static final String TAG = "AccountManager";
164
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700165 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
166 public static final int ERROR_CODE_NETWORK_ERROR = 3;
167 public static final int ERROR_CODE_CANCELED = 4;
168 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
169 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
170 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
171 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700172 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700173
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800174 /** @hide */
175 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100176 /** @hide */
177 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800178
Dan Egnor661f0132010-02-19 11:23:00 -0800179 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700180 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800181 * from methods which return information about a particular account.
182 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700183 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800184
185 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700186 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800187 * from methods which return information about a particular account.
188 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700189 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800190
191 /**
Svet Ganovd4696122016-09-24 13:57:45 -0700192 * Bundle key used for the account access id used for noting the
193 * account was accessed when unmarshaled from a parcel.
Svet Ganovf6d424f12016-09-20 20:18:53 -0700194 *
195 * @hide
196 */
Svet Ganovd4696122016-09-24 13:57:45 -0700197 public static final String KEY_ACCOUNT_ACCESS_ID = "accountAccessId";
Svet Ganovf6d424f12016-09-20 20:18:53 -0700198
199 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700200 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800201 * from {@link #getAuthToken} and friends.
202 */
203 public static final String KEY_AUTHTOKEN = "authtoken";
204
205 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700206 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800207 * may require the caller to interact with the user. The Intent can
208 * be used to start the corresponding user interface activity.
209 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700210 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800211
212 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700213 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800214 * {@link #confirmCredentials}, rather than prompting the user with
215 * the standard password prompt.
216 */
217 public static final String KEY_PASSWORD = "password";
218
219 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700220
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700221 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
222 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800223 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700224 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
225 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800226 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
227 public static final String KEY_ERROR_CODE = "errorCode";
228 public static final String KEY_ERROR_MESSAGE = "errorMessage";
229 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700230
Costin Manolachea40c6302010-12-13 14:50:45 -0800231 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800232 * Bundle key used to supply the last time the credentials of the account
233 * were authenticated successfully. Time is specified in milliseconds since
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700234 * epoch. Associated time is updated on successful authentication of account
235 * on adding account, confirming credentials, or updating credentials.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800236 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700237 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800238
239 /**
Costin Manolachea40c6302010-12-13 14:50:45 -0800240 * Authenticators using 'customTokens' option will also get the UID of the
241 * caller
242 */
243 public static final String KEY_CALLER_UID = "callerUid";
244 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800245
Costin Manolached6060452011-01-24 16:11:36 -0800246 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700247 * The Android package of the caller will be set in the options bundle by the
248 * {@link AccountManager} and will be passed to the AccountManagerService and
249 * to the AccountAuthenticators. The uid of the caller will be known by the
250 * AccountManagerService as well as the AccountAuthenticators so they will be able to
251 * verify that the package is consistent with the uid (a uid might be shared by many
252 * packages).
253 */
254 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
255
256 /**
Costin Manolached6060452011-01-24 16:11:36 -0800257 * Boolean, if set and 'customTokens' the authenticator is responsible for
258 * notifications.
259 * @hide
260 */
261 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
262
Sandra Kwan78812282015-11-04 11:19:47 -0800263 /**
264 * Bundle key used for a {@link Bundle} in result from
265 * {@link #startAddAccountSession} and friends which returns session data
266 * for installing an account later.
267 */
268 public static final String KEY_ACCOUNT_SESSION_BUNDLE = "accountSessionBundle";
269
270 /**
271 * Bundle key used for the {@link String} account status token in result
272 * from {@link #startAddAccountSession} and friends which returns
273 * information about a particular account.
274 */
275 public static final String KEY_ACCOUNT_STATUS_TOKEN = "accountStatusToken";
276
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700277 public static final String ACTION_AUTHENTICATOR_INTENT =
278 "android.accounts.AccountAuthenticator";
279 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800280 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700281 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
282
Dmitry Dementyev52745472016-12-02 10:27:45 -0800283 /** @hide */
284 @Retention(RetentionPolicy.SOURCE)
285 @IntDef({VISIBILITY_UNDEFINED, VISIBILITY_VISIBLE, VISIBILITY_USER_MANAGED_VISIBLE,
286 VISIBILITY_NOT_VISIBLE, VISIBILITY_USER_MANAGED_NOT_VISIBLE})
287 public @interface AccountVisibility {
288 }
289
290 /**
291 * Account visibility was not set.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800292 */
293 public static final int VISIBILITY_UNDEFINED = 0;
294
295 /**
296 * Account is always visible to given application and only authenticator can revoke visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800297 */
298 public static final int VISIBILITY_VISIBLE = 1;
299
300 /**
301 * Account is visible to given application, but user can revoke visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800302 */
303 public static final int VISIBILITY_USER_MANAGED_VISIBLE = 2;
304
305 /**
306 * Account is not visible to given application and only authenticator can grant visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800307 */
308 public static final int VISIBILITY_NOT_VISIBLE = 3;
309
310 /**
311 * Account is not visible to given application, but user can reveal it, for example, using
312 * {@link #newChooseAccountIntent(Account, List, String[], String, String, String[], Bundle)}
Dmitry Dementyev52745472016-12-02 10:27:45 -0800313 */
314 public static final int VISIBILITY_USER_MANAGED_NOT_VISIBLE = 4;
315
316 /**
Svet Ganovf6d424f12016-09-20 20:18:53 -0700317 * Token type for the special case where a UID has access only to an account
318 * but no authenticator specific auth token types.
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +0000319 *
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700320 * @hide
321 */
Svet Ganovf6d424f12016-09-20 20:18:53 -0700322 public static final String ACCOUNT_ACCESS_TOKEN_TYPE =
323 "com.android.AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE";
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700324
Fred Quintana60307342009-03-24 22:48:12 -0700325 private final Context mContext;
326 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700327 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800328
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700329 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800330 * Action sent as a broadcast Intent by the AccountsService when accounts are added, accounts
331 * are removed, or an account's credentials (saved password, etc) are changed.
Dan Egnor661f0132010-02-19 11:23:00 -0800332 *
333 * @see #addOnAccountsUpdatedListener
Dmitry Dementyev52745472016-12-02 10:27:45 -0800334 *
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800335 * @deprecated use #addOnAccountsUpdatedListener to get account updates in runtime.
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700336 */
337 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
338 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700339
Fred Quintana33269202009-04-20 16:05:10 -0700340 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800341 * Uid key to set default visibility for applications targeting API level
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800342 * {@link android.os.Build.VERSION_CODES#O} or above and don't have the same signature as
343 * authenticator See {@link #getAccountVisibility}. If the value was not set by authenticator
344 * USER_MANAGED_NOT_VISIBLE is used.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800345 */
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800346 public static final int UID_KEY_DEFAULT_VISIBILITY = -2;
Dmitry Dementyev52745472016-12-02 10:27:45 -0800347
348 /**
349 * Uid key to set visibility for applications targeting API level below
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800350 * {@link android.os.Build.VERSION_CODES#O} with GET_ACCOUNS permission, or applications with
351 * any targeting API level with the same signature as authenticator. See
352 * {@link #getAccountVisibility}. If the value was not set by authenticator USER_MANAGED_VISIBLE
353 * is used.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800354 */
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800355 public static final int UID_KEY_DEFAULT_LEGACY_VISIBILITY = -3;
Dmitry Dementyev52745472016-12-02 10:27:45 -0800356
357 /**
Fred Quintana33269202009-04-20 16:05:10 -0700358 * @hide
359 */
Fred Quintana60307342009-03-24 22:48:12 -0700360 public AccountManager(Context context, IAccountManager service) {
361 mContext = context;
362 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700363 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700364 }
365
Fred Quintana0eabf022009-04-27 15:08:17 -0700366 /**
367 * @hide used for testing only
368 */
369 public AccountManager(Context context, IAccountManager service, Handler handler) {
370 mContext = context;
371 mService = service;
372 mMainHandler = handler;
373 }
374
Fred Quintana756b7352009-10-21 13:43:10 -0700375 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800376 * @hide for internal use only
377 */
378 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700379 if (result != null) {
380 if (result.containsKey(KEY_AUTHTOKEN)
381 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
382 final Bundle newResult = new Bundle(result);
383 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
384 return newResult;
385 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800386 }
387 return result;
388 }
389
390 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800391 * Gets an AccountManager instance associated with a Context.
392 * The {@link Context} will be used as long as the AccountManager is
393 * active, so make sure to use a {@link Context} whose lifetime is
394 * commensurate with any listeners registered to
395 * {@link #addOnAccountsUpdatedListener} or similar methods.
396 *
397 * <p>It is safe to call this method from the main thread.
398 *
399 * <p>No permission is required to call this method.
400 *
Fred Quintana756b7352009-10-21 13:43:10 -0700401 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800402 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700403 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700404 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700405 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700406 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
407 }
408
Fred Quintana756b7352009-10-21 13:43:10 -0700409 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800410 * Gets the saved password associated with the account. This is intended for authenticators and
411 * related code; applications should get an auth token instead.
Dan Egnor661f0132010-02-19 11:23:00 -0800412 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800413 * <p>
414 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800415 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800416 * <p>
417 * This method requires the caller to have a signature match with the authenticator that owns
418 * the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800419 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800420 * <p>
421 * <b>NOTE:</b> If targeting your app to work on API level
422 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before, AUTHENTICATE_ACCOUNTS
423 * permission is needed for those platforms. See docs for this function in API level
424 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700425 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700426 * @param account The account to query for a password. Must not be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800427 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700428 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700429 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700430 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700431 try {
432 return mService.getPassword(account);
433 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700434 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700435 }
436 }
437
Fred Quintana756b7352009-10-21 13:43:10 -0700438 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800439 * Gets the user data named by "key" associated with the account. This is intended for
440 * authenticators and related code to store arbitrary metadata along with accounts. The meaning
441 * of the keys and values is up to the authenticator for the account.
Dan Egnor661f0132010-02-19 11:23:00 -0800442 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800443 * <p>
444 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800445 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800446 * <p>
447 * This method requires the caller to have a signature match with the authenticator that owns
448 * the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800449 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800450 * <p>
451 * <b>NOTE:</b> If targeting your app to work on API level
452 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before, AUTHENTICATE_ACCOUNTS
453 * permission is needed for those platforms. See docs for this function in API level
454 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700455 *
Dan Egnor661f0132010-02-19 11:23:00 -0800456 * @param account The account to query for user data
457 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700458 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700459 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700460 if (account == null) throw new IllegalArgumentException("account is null");
461 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700462 try {
463 return mService.getUserData(account, key);
464 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700465 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700466 }
467 }
468
Fred Quintana756b7352009-10-21 13:43:10 -0700469 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800470 * Lists the currently registered authenticators.
471 *
472 * <p>It is safe to call this method from the main thread.
473 *
474 * <p>No permission is required to call this method.
475 *
476 * @return An array of {@link AuthenticatorDescription} for every
477 * authenticator known to the AccountManager service. Empty (never
478 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700479 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700480 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700481 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100482 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
483 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700484 throw e.rethrowFromSystemServer();
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100485 }
486 }
487
488 /**
489 * @hide
490 * Lists the currently registered authenticators for a given user id.
491 *
492 * <p>It is safe to call this method from the main thread.
493 *
494 * <p>The caller has to be in the same user or have the permission
495 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
496 *
497 * @return An array of {@link AuthenticatorDescription} for every
498 * authenticator known to the AccountManager service. Empty (never
499 * null) if no authenticators are known.
500 */
501 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
502 try {
503 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700504 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700505 throw e.rethrowFromSystemServer();
Fred Quintanaa698f422009-04-08 19:14:54 -0700506 }
507 }
508
Fred Quintana756b7352009-10-21 13:43:10 -0700509 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800510 * Lists all accounts visible to the caller regardless of type. Equivalent to
511 * getAccountsByType(null). These accounts may be visible because the user granted access to the
512 * account, or the AbstractAcccountAuthenticator managing the account did so or because the
513 * client shares a signature with the managing AbstractAccountAuthenticator.
Dan Egnor661f0132010-02-19 11:23:00 -0800514 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800515 * <p>
516 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800517 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800518 * @return An array of {@link Account}, one for each account. Empty (never null) if no accounts
519 * have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700520 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700521 @NonNull
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700522 public Account[] getAccounts() {
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000523 try {
524 return mService.getAccounts(null, mContext.getOpPackageName());
525 } catch (RemoteException e) {
526 throw e.rethrowFromSystemServer();
527 }
Fred Quintana60307342009-03-24 22:48:12 -0700528 }
529
Fred Quintana756b7352009-10-21 13:43:10 -0700530 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700531 * @hide
Dmitry Dementyev52745472016-12-02 10:27:45 -0800532 * Lists all accounts visible to caller regardless of type for a given user id. Equivalent to
533 * getAccountsByType(null).
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100534 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800535 * <p>
536 * It is safe to call this method from the main thread.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100537 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800538 * @return An array of {@link Account}, one for each account. Empty (never null) if no accounts
539 * have been added.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100540 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700541 @NonNull
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100542 public Account[] getAccountsAsUser(int userId) {
543 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700544 return mService.getAccountsAsUser(null, userId, mContext.getOpPackageName());
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100545 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700546 throw e.rethrowFromSystemServer();
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100547 }
548 }
549
550 /**
551 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700552 * For use by internal activities. Returns the list of accounts that the calling package
553 * is authorized to use, particularly for shared accounts.
554 * @param packageName package name of the calling app.
555 * @param uid the uid of the calling app.
556 * @return the accounts that are available to this package and user.
557 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700558 @NonNull
Amith Yamasani27db4682013-03-30 17:07:47 -0700559 public Account[] getAccountsForPackage(String packageName, int uid) {
560 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700561 return mService.getAccountsForPackage(packageName, uid, mContext.getOpPackageName());
Amith Yamasani27db4682013-03-30 17:07:47 -0700562 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700563 throw re.rethrowFromSystemServer();
Amith Yamasani27db4682013-03-30 17:07:47 -0700564 }
565 }
566
567 /**
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700568 * Returns the accounts visible to the specified package, in an environment where some apps
569 * are not authorized to view all accounts. This method can only be called by system apps.
570 * @param type The type of accounts to return, null to retrieve all accounts
571 * @param packageName The package name of the app for which the accounts are to be returned
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000572 * @return An array of {@link Account}, one per matching account. Empty
573 * (never null) if no accounts of the specified type have been added.
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700574 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700575 @NonNull
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700576 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
577 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700578 return mService.getAccountsByTypeForPackage(type, packageName,
579 mContext.getOpPackageName());
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700580 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700581 throw re.rethrowFromSystemServer();
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700582 }
583 }
584
585 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800586 * Lists all accounts of particular type visible to the caller. These accounts may be visible
587 * because the user granted access to the account, or the AbstractAcccountAuthenticator managing
588 * the account did so or because the client shares a signature with the managing
589 * AbstractAccountAuthenticator.
Dan Egnor661f0132010-02-19 11:23:00 -0800590 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800591 * <p>
592 * The account type is a string token corresponding to the authenticator and useful domain of
593 * the account. For example, there are types corresponding to Google and Facebook. The exact
594 * string token to use will be published somewhere associated with the authenticator in
595 * question.
Dan Egnor661f0132010-02-19 11:23:00 -0800596 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800597 * <p>
598 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800599 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800600 * <p>
601 * Caller targeting API level {@link android.os.Build.VERSION_CODES#O} and above, will get list
602 * of accounts made visible to it by user or AbstractAcccountAuthenticator and
603 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is not used.
604 *
605 * <p>
606 * Caller targeting API level below {@link android.os.Build.VERSION_CODES#O} that have not been
607 * granted the {@link android.Manifest.permission#GET_ACCOUNTS} permission, will only see those
608 * accounts managed by AbstractAccountAuthenticators whose signature matches the client.
609 *
610 * <p>
611 * <b>NOTE:</b> If targeting your app to work on API level
612 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before, GET_ACCOUNTS permission is
613 * needed for those platforms, irrespective of uid or signature match. See docs for this
614 * function in API level {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000615 *
616 * @param type The type of accounts to return, null to retrieve all accounts
Dmitry Dementyev52745472016-12-02 10:27:45 -0800617 * @return An array of {@link Account}, one per matching account. Empty (never null) if no
618 * accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700619 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700620 @NonNull
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700621 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800622 return getAccountsByTypeAsUser(type, Process.myUserHandle());
623 }
624
625 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700626 @NonNull
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800627 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700628 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700629 return mService.getAccountsAsUser(type, userHandle.getIdentifier(),
630 mContext.getOpPackageName());
Fred Quintana60307342009-03-24 22:48:12 -0700631 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700632 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700633 }
634 }
635
Fred Quintana756b7352009-10-21 13:43:10 -0700636 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700637 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
638 * for an account.
639 * <p>
640 * This is only meant to be used by system activities and is not in the SDK.
641 * @param account The account whose permissions are being modified
642 * @param authTokenType The type of token whose permissions are being modified
643 * @param uid The uid that identifies the app which is being granted or revoked permission.
644 * @param value true is permission is being granted, false for revoked
645 * @hide
646 */
647 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
648 try {
649 mService.updateAppPermission(account, authTokenType, uid, value);
650 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700651 throw e.rethrowFromSystemServer();
Fred Quintanad9640ec2012-05-23 12:37:00 -0700652 }
653 }
654
655 /**
656 * Get the user-friendly label associated with an authenticator's auth token.
657 * @param accountType the type of the authenticator. must not be null.
658 * @param authTokenType the token type. must not be null.
659 * @param callback callback to invoke when the result is available. may be null.
660 * @param handler the handler on which to invoke the callback, or null for the main thread
661 * @return a future containing the label string
662 * @hide
663 */
664 public AccountManagerFuture<String> getAuthTokenLabel(
665 final String accountType, final String authTokenType,
666 AccountManagerCallback<String> callback, Handler handler) {
667 if (accountType == null) throw new IllegalArgumentException("accountType is null");
668 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
669 return new Future2Task<String>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800670 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -0700671 public void doWork() throws RemoteException {
672 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
673 }
674
675 @Override
676 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
677 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
678 throw new AuthenticatorException("no result in response");
679 }
680 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
681 }
682 }.start();
683 }
684
685 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800686 * Finds out whether a particular account has all the specified features. Account features are
687 * authenticator-specific string tokens identifying boolean account properties. For example,
688 * features are used to tell whether Google accounts have a particular service (such as Google
689 * Calendar or Google Talk) enabled. The feature names and their meanings are published
690 * somewhere associated with the authenticator in question.
Dan Egnor661f0132010-02-19 11:23:00 -0800691 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800692 * <p>
693 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
694 * not be used on the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800695 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800696 * <p>
697 * If caller target API level is below {@link android.os.Build.VERSION_CODES#O}, it is
698 * required to hold the permission {@link android.Manifest.permission#GET_ACCOUNTS} or have a
699 * signature match with the AbstractAccountAuthenticator that manages the account.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800700 *
701 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800702 * @param features An array of the account features to check
Dmitry Dementyev52745472016-12-02 10:27:45 -0800703 * @param callback Callback to invoke when the request completes, null for no callback
704 * @param handler {@link Handler} identifying the callback thread, null for the main thread
705 * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the account
706 * exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800707 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800708 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800709 final String[] features,
710 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700711 if (account == null) throw new IllegalArgumentException("account is null");
712 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800713 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800714 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800715 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700716 mService.hasFeatures(mResponse, account, features, mContext.getOpPackageName());
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800717 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800718 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800719 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
720 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
721 throw new AuthenticatorException("no result in response");
722 }
723 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
724 }
725 }.start();
726 }
727
728 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800729 * Lists all accounts of a type which have certain features. The account type identifies the
730 * authenticator (see {@link #getAccountsByType}). Account features are authenticator-specific
731 * string tokens identifying boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700732 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800733 * <p>
734 * Unlike {@link #getAccountsByType}, this method calls the authenticator, which may contact the
735 * server or do other work to check account features, so the method returns an
736 * {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700737 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800738 * <p>
739 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
740 * not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700741 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800742 * <p>
743 * Caller targeting API level {@link android.os.Build.VERSION_CODES#O} and above, will get list
744 * of accounts made visible to it by user or AbstractAcccountAuthenticator and
745 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is not used.
746 *
747 * <p>
748 * Caller targeting API level below {@link android.os.Build.VERSION_CODES#O} that have not been
749 * granted the {@link android.Manifest.permission#GET_ACCOUNTS} permission, will only see those
750 * accounts managed by AbstractAccountAuthenticators whose signature matches the client.
751 * <p>
752 * <b>NOTE:</b> If targeting your app to work on API level
753 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before, GET_ACCOUNTS permission is
754 * needed for those platforms, irrespective of uid or signature match. See docs for this
755 * function in API level {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
756 *
Fred Quintana756b7352009-10-21 13:43:10 -0700757 *
Dan Egnor661f0132010-02-19 11:23:00 -0800758 * @param type The type of accounts to return, must not be null
Dmitry Dementyev52745472016-12-02 10:27:45 -0800759 * @param features An array of the account features to require, may be null or empty *
760 * @param callback Callback to invoke when the request completes, null for no callback
761 * @param handler {@link Handler} identifying the callback thread, null for the main thread
762 * @return An {@link AccountManagerFuture} which resolves to an array of {@link Account}, one
763 * per account of the specified type which matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800764 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700765 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
766 final String type, final String[] features,
767 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700768 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700769 return new Future2Task<Account[]>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800770 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700771 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700772 mService.getAccountsByFeatures(mResponse, type, features,
773 mContext.getOpPackageName());
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700774 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800775 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700776 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700777 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700778 throw new AuthenticatorException("no result in response");
779 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700780 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700781 Account[] descs = new Account[parcelables.length];
782 for (int i = 0; i < parcelables.length; i++) {
783 descs[i] = (Account) parcelables[i];
784 }
785 return descs;
786 }
787 }.start();
788 }
789
Fred Quintana756b7352009-10-21 13:43:10 -0700790 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700791 * Adds an account directly to the AccountManager. Normally used by sign-up
Dan Egnor661f0132010-02-19 11:23:00 -0800792 * wizards associated with authenticators, not directly by applications.
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700793 * <p>Calling this method does not update the last authenticated timestamp,
794 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
795 * {@link #notifyAccountAuthenticated(Account)} after getting success.
796 * However, if this method is called when it is triggered by addAccount() or
797 * addAccountAsUser() or similar functions, then there is no need to update
798 * timestamp manually as it is updated automatically by framework on
799 * successful completion of the mentioned functions.
Dan Egnor661f0132010-02-19 11:23:00 -0800800 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700801 * <p>This method requires the caller to have a signature match with the
802 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800803 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700804 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
805 * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs
806 * for this function in API level 22.
807 *
Dan Egnor661f0132010-02-19 11:23:00 -0800808 * @param account The {@link Account} to add
809 * @param password The password to associate with the account, null for none
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700810 * @param userdata String values to use for the account's userdata, null for
811 * none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700812 * @return True if the account was successfully added, false if the account
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700813 * already exists, the account is null, or another error occurs.
Dan Egnor661f0132010-02-19 11:23:00 -0800814 */
815 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700816 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800817 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700818 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800819 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700820 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -0800821 }
822 }
823
824 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800825 * Adds an account directly to the AccountManager. Additionally this makes the Account visible
826 * to desired UIDs of applications on the device, and sends directed broadcasts to these
827 * individual applications.
828 * <p>
829 * Normally used by sign-up wizards associated with authenticators, not directly by
830 * applications.
831 * <p>
832 * Calling this method does not update the last authenticated timestamp, referred by
833 * {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700834 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800835 * <p>
836 * It is safe to call this method from the main thread.
837 * <p>
838 * This method requires the caller to have a signature match with the authenticator that owns
839 * the specified account.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700840 *
841 * @param account The {@link Account} to add
842 * @param password The password to associate with the account, null for none
Dmitry Dementyev52745472016-12-02 10:27:45 -0800843 * @param extras String values to use for the account's userdata, null for none
Dmitry Dementyev52745472016-12-02 10:27:45 -0800844 * @param visibility Map from uid to visibility values which will be set before account is
845 * added. See getAccountVisibility for possilbe values.
846 *
847 * @return True if the account was successfully added, false if the account already exists, the
848 * account is null, or another error occurs.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800849 */
850 public boolean addAccountExplicitly(Account account, String password, Bundle extras,
851 Map<Integer, Integer> visibility) {
852 if (account == null)
853 throw new IllegalArgumentException("account is null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700854 try {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800855 return mService.addAccountExplicitlyWithVisibility(account, password, extras,
856 visibility);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700857 } catch (RemoteException e) {
858 throw e.rethrowFromSystemServer();
859 }
860 }
861
862 /**
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800863 * Returns UIDs of applications for which visibility of given account was explicitly set.
864 * <p>
865 * This method requires the caller to have a signature match with the authenticator that owns
866 * the specified account.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700867 *
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800868 * @param account The account for which visibility data should be returned.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700869 *
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800870 * @return Map from uid to visibility for given account.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700871 */
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800872 public Map<Integer, Integer> getUidsAndVisibilityForAccount(Account account) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800873 try {
874 @SuppressWarnings("unchecked")
875 Map<Integer, Integer> result = (Map<Integer, Integer>) mService
876 .getUidsAndVisibilityForAccount(account);
877 return result;
878 } catch (RemoteException re) {
879 throw re.rethrowFromSystemServer();
880 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700881 }
882
883 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800884 * Gets all accounts of given type and their visibility for specific package. This method
885 * requires the caller to have a signature match with the authenticator that manages
886 * accountType. It is a helper method which combines calls to {@link #getAccountsByType} by
887 * authenticator and {@link #getAccountVisibility} for every returned account.
888 *
889 * <p>
890 *
891 * @param packageName Package name.
892 * @param accountType Account type.
893 *
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800894 * @return Map with visibility for all accounts of given type.
895 * See {@link #getAccountVisibility} for possilbe values.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800896 */
897 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
898 String accountType) {
899 try {
900 @SuppressWarnings("unchecked")
901 Map<Account, Integer> result = (Map<Account, Integer>) mService
902 .getAccountsAndVisibilityForPackage(packageName, accountType);
903 return result;
904 } catch (RemoteException re) {
905 throw re.rethrowFromSystemServer();
906 }
907 }
908
909 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800910 * Set visibility value of given account to certain UID.
911 * <p>
912 * See {@link #getAccountVisibility} for possible values.
913 * <p>
914 * This method requires the caller to have a signature match with the authenticator that owns
915 * the specified account.
916 *
917 * @param account Account to make visible.
918 * @param uid The UID of the application to modify account visibility.
919 * @param visibility - new visibility value.
920 *
921 * @return True if visibility value was succesfully updated.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800922 */
923 public boolean setAccountVisibility(Account account, int uid,
924 @AccountVisibility int visibility) {
925 try {
926 return mService.setAccountVisibility(account, uid, visibility);
927 } catch (RemoteException re) {
928 throw re.rethrowFromSystemServer();
929 }
930 }
931
932 /**
933 * Gets visibility of certain account for given UID. Possible returned values are:
934 * <ul>
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800935 * <li>{@link #VISIBILITY_UNDEFINED}</li>
Dmitry Dementyev52745472016-12-02 10:27:45 -0800936 * <li>{@link #VISIBILITY_VISIBLE}</li>
937 * <li>{@link #VISIBILITY_USER_MANAGED_VISIBLE}</li>
938 * <li>{@link #VISIBILITY_NOT_VISIBLE}
939 * <li>{@link #VISIBILITY_USER_MANAGED_NOT_VISIBLE}</li>
940 * </ul>
941 *
942 * <p>
943 * This method requires the caller to have a signature match with the authenticator that owns
944 * the specified account.
945 *
946 * @param account Account to get visibility.
947 * @param uid The UID of the application to get account visibility.
948 *
949 * @return int Visibility for given account and uid.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800950 */
951 public @AccountVisibility int getAccountVisibility(Account account, int uid) {
952 try {
953 return mService.getAccountVisibility(account, uid);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700954 } catch (RemoteException re) {
955 throw re.rethrowFromSystemServer();
956 }
957 }
958
959 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700960 * Notifies the system that the account has just been authenticated. This
961 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800962 * should be called only when the user has entered correct credentials for
963 * the account.
964 * <p>
965 * It is not safe to call this method from the main thread. As such, call it
966 * from another thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700967 * <p>This method requires the caller to have a signature match with the
968 * authenticator that owns the specified account.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800969 *
970 * @param account The {@link Account} to be updated.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700971 * @return boolean {@code true} if the authentication of the account has been successfully
972 * acknowledged. Otherwise {@code false}.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800973 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700974 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800975 if (account == null)
976 throw new IllegalArgumentException("account is null");
977 try {
978 return mService.accountAuthenticated(account);
979 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700980 throw e.rethrowFromSystemServer();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800981 }
982 }
983
984 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700985 * Rename the specified {@link Account}. This is equivalent to removing
986 * the existing account and adding a new renamed account with the old
987 * account's user data.
988 *
989 * <p>It is safe to call this method from the main thread.
990 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700991 * <p>This method requires the caller to have a signature match with the
992 * authenticator that manages the specified account.
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700993 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700994 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
995 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
996 * is needed for those platforms. See docs for this function in API level 22.
997 *
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700998 * @param account The {@link Account} to rename
999 * @param newName String name to be associated with the account.
1000 * @param callback Callback to invoke when the request completes, null for
1001 * no callback
1002 * @param handler {@link Handler} identifying the callback thread, null for
1003 * the main thread
1004 * @return An {@link AccountManagerFuture} which resolves to the Account
1005 * after the name change. If successful the account's name will be the
1006 * specified new name.
1007 */
1008 public AccountManagerFuture<Account> renameAccount(
1009 final Account account,
Tor Norbye80b530a2015-04-23 16:36:09 -07001010 @Size(min = 1) final String newName,
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001011 AccountManagerCallback<Account> callback,
1012 Handler handler) {
1013 if (account == null) throw new IllegalArgumentException("account is null.");
1014 if (TextUtils.isEmpty(newName)) {
1015 throw new IllegalArgumentException("newName is empty or null.");
1016 }
1017 return new Future2Task<Account>(handler, callback) {
1018 @Override
1019 public void doWork() throws RemoteException {
1020 mService.renameAccount(mResponse, account, newName);
1021 }
1022 @Override
1023 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
1024 String name = bundle.getString(KEY_ACCOUNT_NAME);
1025 String type = bundle.getString(KEY_ACCOUNT_TYPE);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001026 String accessId = bundle.getString(KEY_ACCOUNT_ACCESS_ID);
1027 return new Account(name, type, accessId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001028 }
1029 }.start();
1030 }
1031
1032 /**
1033 * Gets the previous name associated with the account or {@code null}, if
1034 * none. This is intended so that clients of {@link
1035 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
1036 * authenticator has renamed an account.
1037 *
1038 * <p>It is safe to call this method from the main thread.
1039 *
1040 * @param account The account to query for a previous name.
1041 * @return The account's previous name, null if the account has never been
1042 * renamed.
1043 */
1044 public String getPreviousName(final Account account) {
1045 if (account == null) throw new IllegalArgumentException("account is null");
1046 try {
1047 return mService.getPreviousName(account);
1048 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001049 throw e.rethrowFromSystemServer();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001050 }
1051 }
1052
1053 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001054 * Removes an account from the AccountManager. Does nothing if the account
1055 * does not exist. Does not delete the account from the server.
1056 * The authenticator may have its own policies preventing account
1057 * deletion, in which case the account will not be deleted.
1058 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001059 * <p>This method requires the caller to have a signature match with the
1060 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001061 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001062 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1063 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1064 * this function in API level 22.
1065 *
Dan Egnor661f0132010-02-19 11:23:00 -08001066 * @param account The {@link Account} to remove
1067 * @param callback Callback to invoke when the request completes,
1068 * null for no callback
1069 * @param handler {@link Handler} identifying the callback thread,
1070 * null for the main thread
1071 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001072 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001073 * @deprecated use
1074 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
1075 * instead
Dan Egnor661f0132010-02-19 11:23:00 -08001076 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001077 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001078 public AccountManagerFuture<Boolean> removeAccount(final Account account,
1079 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001080 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001081 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001082 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001083 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001084 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -08001085 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001086 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001087 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1088 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1089 throw new AuthenticatorException("no result in response");
1090 }
1091 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1092 }
1093 }.start();
1094 }
1095
1096 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001097 * Removes an account from the AccountManager. Does nothing if the account
1098 * does not exist. Does not delete the account from the server.
1099 * The authenticator may have its own policies preventing account
1100 * deletion, in which case the account will not be deleted.
1101 *
1102 * <p>This method may be called from any thread, but the returned
1103 * {@link AccountManagerFuture} must not be used on the main thread.
1104 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001105 * <p>This method requires the caller to have a signature match with the
1106 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001107 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001108 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1109 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1110 * this function in API level 22.
1111 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001112 * @param account The {@link Account} to remove
1113 * @param activity The {@link Activity} context to use for launching a new
1114 * authenticator-defined sub-Activity to prompt the user to delete an
1115 * account; used only to call startActivity(); if null, the prompt
1116 * will not be launched directly, but the {@link Intent} may be
1117 * returned to the caller instead
1118 * @param callback Callback to invoke when the request completes,
1119 * null for no callback
1120 * @param handler {@link Handler} identifying the callback thread,
1121 * null for the main thread
1122 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1123 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
1124 * was removed or if active. If no activity was specified, the returned
1125 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
1126 * needed to launch the actual account removal process, if authenticator
1127 * needs the activity launch. If an error occurred,
1128 * {@link AccountManagerFuture#getResult()} throws:
1129 * <ul>
1130 * <li> {@link AuthenticatorException} if no authenticator was registered for
1131 * this account type or the authenticator failed to respond
1132 * <li> {@link OperationCanceledException} if the operation was canceled for
1133 * any reason, including the user canceling the creation process or
1134 * adding accounts (of this type) has been disabled by policy
1135 * </ul>
1136 */
1137 public AccountManagerFuture<Bundle> removeAccount(final Account account,
1138 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
1139 if (account == null) throw new IllegalArgumentException("account is null");
1140 return new AmsTask(activity, handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001141 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001142 public void doWork() throws RemoteException {
1143 mService.removeAccount(mResponse, account, activity != null);
1144 }
1145 }.start();
1146 }
1147
1148 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001149 * @see #removeAccount(Account, AccountManagerCallback, Handler)
1150 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001151 * @deprecated use
1152 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
1153 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001154 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001155 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001156 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
1157 AccountManagerCallback<Boolean> callback, Handler handler,
1158 final UserHandle userHandle) {
1159 if (account == null) throw new IllegalArgumentException("account is null");
1160 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1161 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001162 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001163 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001164 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001165 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001166 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001167 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1168 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1169 throw new AuthenticatorException("no result in response");
1170 }
1171 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1172 }
1173 }.start();
1174 }
1175
1176 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001177 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
1178 * @hide
1179 */
1180 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
1181 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
1182 final UserHandle userHandle) {
1183 if (account == null)
1184 throw new IllegalArgumentException("account is null");
1185 if (userHandle == null)
1186 throw new IllegalArgumentException("userHandle is null");
1187 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001188 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001189 public void doWork() throws RemoteException {
1190 mService.removeAccountAsUser(mResponse, account, activity != null,
1191 userHandle.getIdentifier());
1192 }
1193 }.start();
1194 }
1195
1196 /**
1197 * Removes an account directly. Normally used by authenticators, not
1198 * directly by applications. Does not delete the account from the server.
1199 * The authenticator may have its own policies preventing account deletion,
1200 * in which case the account will not be deleted.
1201 * <p>
1202 * It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001203 * <p>This method requires the caller to have a signature match with the
1204 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001205 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001206 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1207 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1208 * is needed for those platforms. See docs for this function in API level 22.
1209 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001210 * @param account The {@link Account} to delete.
1211 * @return True if the account was successfully deleted, false if the
1212 * account did not exist, the account is null, or another error
1213 * occurs.
1214 */
1215 public boolean removeAccountExplicitly(Account account) {
1216 if (account == null) throw new IllegalArgumentException("account is null");
1217 try {
1218 return mService.removeAccountExplicitly(account);
1219 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001220 throw e.rethrowFromSystemServer();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001221 }
1222 }
1223
1224 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001225 * Removes an auth token from the AccountManager's cache. Does nothing if
1226 * the auth token is not currently in the cache. Applications must call this
1227 * method when the auth token is found to have expired or otherwise become
1228 * invalid for authenticating requests. The AccountManager does not validate
1229 * or expire cached auth tokens otherwise.
1230 *
1231 * <p>It is safe to call this method from the main thread.
1232 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001233 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1234 * MANAGE_ACCOUNTS or USE_CREDENTIALS permission is needed for those
1235 * platforms. See docs for this function in API level 22.
1236 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001237 * @param accountType The account type of the auth token to invalidate, must not be null
1238 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -08001239 */
1240 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001241 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001242 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001243 if (authToken != null) {
1244 mService.invalidateAuthToken(accountType, authToken);
1245 }
Dan Egnor661f0132010-02-19 11:23:00 -08001246 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001247 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001248 }
1249 }
1250
1251 /**
1252 * Gets an auth token from the AccountManager's cache. If no auth
1253 * token is cached for this account, null will be returned -- a new
1254 * auth token will not be generated, and the server will not be contacted.
1255 * Intended for use by the authenticator, not directly by applications.
1256 *
1257 * <p>It is safe to call this method from the main thread.
1258 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001259 * <p>This method requires the caller to have a signature match with the
1260 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001261 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001262 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1263 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1264 * is needed for those platforms. See docs for this function in API level 22.
1265 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001266 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001267 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001268 * @return The cached auth token for this account and type, or null if
1269 * no auth token is cached or the account does not exist.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001270 * @see #getAuthToken
Dan Egnor661f0132010-02-19 11:23:00 -08001271 */
1272 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -07001273 if (account == null) throw new IllegalArgumentException("account is null");
1274 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001275 try {
1276 return mService.peekAuthToken(account, authTokenType);
1277 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001278 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001279 }
1280 }
1281
1282 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001283 * Sets or forgets a saved password. This modifies the local copy of the
1284 * password used to automatically authenticate the user; it does not change
1285 * the user's account password on the server. Intended for use by the
1286 * authenticator, not directly by applications.
1287 * <p>Calling this method does not update the last authenticated timestamp,
1288 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
1289 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dan Egnor661f0132010-02-19 11:23:00 -08001290 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001291 * <p>This method requires the caller to have a signature match with the
1292 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001293 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001294 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1295 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1296 * is needed for those platforms. See docs for this function in API level 22.
1297 *
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001298 * @param account The account whose password is to be set. Cannot be
1299 * {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001300 * @param password The password to set, null to clear the password
1301 */
1302 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -07001303 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001304 try {
1305 mService.setPassword(account, password);
1306 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001307 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001308 }
1309 }
1310
1311 /**
1312 * Forgets a saved password. This erases the local copy of the password;
1313 * it does not change the user's account password on the server.
1314 * Has the same effect as setPassword(account, null) but requires fewer
1315 * permissions, and may be used by applications or management interfaces
1316 * to "sign out" from an account.
1317 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001318 * <p>This method only successfully clear the account's password when the
1319 * caller has the same signature as the authenticator that owns the
1320 * specified account. Otherwise, this method will silently fail.
Dan Egnor661f0132010-02-19 11:23:00 -08001321 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001322 * <p>It is safe to call this method from the main thread.
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001323 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001324 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1325 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1326 * this function in API level 22.
1327 *
Dan Egnor661f0132010-02-19 11:23:00 -08001328 * @param account The account whose password to clear
1329 */
1330 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001331 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001332 try {
1333 mService.clearPassword(account);
1334 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001335 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001336 }
1337 }
1338
1339 /**
1340 * Sets one userdata key for an account. Intended by use for the
1341 * authenticator to stash state for itself, not directly by applications.
1342 * The meaning of the keys and values is up to the authenticator.
1343 *
1344 * <p>It is safe to call this method from the main thread.
1345 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001346 * <p>This method requires the caller to have a signature match with the
1347 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001348 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001349 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1350 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1351 * is needed for those platforms. See docs for this function in API level 22.
1352 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001353 * @param account Account whose user data is to be set. Must not be {@code null}.
1354 * @param key String user data key to set. Must not be null
1355 * @param value String value to set, {@code null} to clear this user data key
Dan Egnor661f0132010-02-19 11:23:00 -08001356 */
1357 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001358 if (account == null) throw new IllegalArgumentException("account is null");
1359 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001360 try {
1361 mService.setUserData(account, key, value);
1362 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001363 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001364 }
1365 }
1366
1367 /**
1368 * Adds an auth token to the AccountManager cache for an account.
1369 * If the account does not exist then this call has no effect.
1370 * Replaces any previous auth token for this account and auth token type.
1371 * Intended for use by the authenticator, not directly by applications.
1372 *
1373 * <p>It is safe to call this method from the main thread.
1374 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001375 * <p>This method requires the caller to have a signature match with the
1376 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001377 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001378 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1379 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1380 * is needed for those platforms. See docs for this function in API level 22.
1381 *
Dan Egnor661f0132010-02-19 11:23:00 -08001382 * @param account The account to set an auth token for
1383 * @param authTokenType The type of the auth token, see {#getAuthToken}
1384 * @param authToken The auth token to add to the cache
1385 */
1386 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001387 if (account == null) throw new IllegalArgumentException("account is null");
1388 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001389 try {
1390 mService.setAuthToken(account, authTokenType, authToken);
1391 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001392 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001393 }
1394 }
1395
1396 /**
1397 * This convenience helper synchronously gets an auth token with
1398 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1399 *
1400 * <p>This method may block while a network request completes, and must
1401 * never be made from the main thread.
1402 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001403 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1404 * USE_CREDENTIALS permission is needed for those platforms. See docs for
1405 * this function in API level 22.
1406 *
Dan Egnor661f0132010-02-19 11:23:00 -08001407 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001408 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001409 * @param notifyAuthFailure If true, display a notification and return null
1410 * if authentication fails; if false, prompt and wait for the user to
1411 * re-enter correct credentials before returning
1412 * @return An auth token of the specified type for this account, or null
1413 * if authentication fails or none can be fetched.
1414 * @throws AuthenticatorException if the authenticator failed to respond
1415 * @throws OperationCanceledException if the request was canceled for any
1416 * reason, including the user canceling a credential request
1417 * @throws java.io.IOException if the authenticator experienced an I/O problem
1418 * creating a new auth token, usually because of network trouble
1419 */
1420 public String blockingGetAuthToken(Account account, String authTokenType,
1421 boolean notifyAuthFailure)
1422 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001423 if (account == null) throw new IllegalArgumentException("account is null");
1424 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001425 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1426 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001427 if (bundle == null) {
1428 // This should never happen, but it does, occasionally. If it does return null to
1429 // signify that we were not able to get the authtoken.
1430 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1431 // returned
1432 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1433 + account + ", authTokenType " + authTokenType);
1434 return null;
1435 }
Dan Egnor661f0132010-02-19 11:23:00 -08001436 return bundle.getString(KEY_AUTHTOKEN);
1437 }
1438
1439 /**
1440 * Gets an auth token of the specified type for a particular account,
1441 * prompting the user for credentials if necessary. This method is
1442 * intended for applications running in the foreground where it makes
1443 * sense to ask the user directly for a password.
1444 *
1445 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001446 * type, then it is returned. Otherwise, if a saved password is
1447 * available, it is sent to the server to generate a new auth token.
1448 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001449 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001450 * <p>Some authenticators have auth token <em>types</em>, whose value
1451 * is authenticator-dependent. Some services use different token types to
1452 * access different functionality -- for example, Google uses different auth
1453 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001454 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001455 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001456 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001457 * this function in API level 22.
1458 *
Dan Egnor661f0132010-02-19 11:23:00 -08001459 * <p>This method may be called from any thread, but the returned
1460 * {@link AccountManagerFuture} must not be used on the main thread.
1461 *
Dan Egnor661f0132010-02-19 11:23:00 -08001462 * @param account The account to fetch an auth token for
1463 * @param authTokenType The auth token type, an authenticator-dependent
1464 * string token, must not be null
1465 * @param options Authenticator-specific options for the request,
1466 * may be null or empty
1467 * @param activity The {@link Activity} context to use for launching a new
1468 * authenticator-defined sub-Activity to prompt the user for a password
1469 * if necessary; used only to call startActivity(); must not be null.
1470 * @param callback Callback to invoke when the request completes,
1471 * null for no callback
1472 * @param handler {@link Handler} identifying the callback thread,
1473 * null for the main thread
1474 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1475 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001476 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001477 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1478 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1479 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001480 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001481 *
1482 * (Other authenticator-specific values may be returned.) If an auth token
1483 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1484 * <ul>
1485 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1486 * <li> {@link OperationCanceledException} if the operation is canceled for
1487 * any reason, incluidng the user canceling a credential request
1488 * <li> {@link IOException} if the authenticator experienced an I/O problem
1489 * creating a new auth token, usually because of network trouble
1490 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001491 * If the account is no longer present on the device, the return value is
1492 * authenticator-dependent. The caller should verify the validity of the
1493 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001494 */
1495 public AccountManagerFuture<Bundle> getAuthToken(
1496 final Account account, final String authTokenType, final Bundle options,
1497 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001498 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001499 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001500 final Bundle optionsIn = new Bundle();
1501 if (options != null) {
1502 optionsIn.putAll(options);
1503 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001504 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001505 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001506 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001507 public void doWork() throws RemoteException {
1508 mService.getAuthToken(mResponse, account, authTokenType,
1509 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001510 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001511 }
1512 }.start();
1513 }
1514
1515 /**
1516 * Gets an auth token of the specified type for a particular account,
1517 * optionally raising a notification if the user must enter credentials.
1518 * This method is intended for background tasks and services where the
1519 * user should not be immediately interrupted with a password prompt.
1520 *
1521 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001522 * type, then it is returned. Otherwise, if a saved password is
1523 * available, it is sent to the server to generate a new auth token.
1524 * Otherwise, an {@link Intent} is returned which, when started, will
1525 * prompt the user for a password. If the notifyAuthFailure parameter is
1526 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001527 * alerting the user that they need to enter a password at some point.
1528 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001529 * <p>In that case, you may need to wait until the user responds, which
1530 * could take hours or days or forever. When the user does respond and
1531 * supply a new password, the account manager will broadcast the
1532 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1533 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001534 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001535 * <p>If notifyAuthFailure is not set, it is the application's
1536 * responsibility to launch the returned Intent at some point.
1537 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001538 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001539 * <p>Some authenticators have auth token <em>types</em>, whose value
1540 * is authenticator-dependent. Some services use different token types to
1541 * access different functionality -- for example, Google uses different auth
1542 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001543 *
1544 * <p>This method may be called from any thread, but the returned
1545 * {@link AccountManagerFuture} must not be used on the main thread.
1546 *
Dan Egnor661f0132010-02-19 11:23:00 -08001547 * @param account The account to fetch an auth token for
1548 * @param authTokenType The auth token type, an authenticator-dependent
1549 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001550 * @param notifyAuthFailure True to add a notification to prompt the
1551 * user for a password if necessary, false to leave that to the caller
1552 * @param callback Callback to invoke when the request completes,
1553 * null for no callback
1554 * @param handler {@link Handler} identifying the callback thread,
1555 * null for the main thread
1556 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1557 * at least the following fields on success:
1558 * <ul>
1559 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1560 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1561 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1562 * </ul>
1563 *
1564 * (Other authenticator-specific values may be returned.) If the user
1565 * must enter credentials, the returned Bundle contains only
1566 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1567 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001568 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001569 * <ul>
1570 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1571 * <li> {@link OperationCanceledException} if the operation is canceled for
1572 * any reason, incluidng the user canceling a credential request
1573 * <li> {@link IOException} if the authenticator experienced an I/O problem
1574 * creating a new auth token, usually because of network trouble
1575 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001576 * If the account is no longer present on the device, the return value is
1577 * authenticator-dependent. The caller should verify the validity of the
1578 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001579 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1580 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001581 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001582 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001583 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001584 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001585 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001586 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001587 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001588 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001589 }
1590
1591 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001592 * Gets an auth token of the specified type for a particular account,
1593 * optionally raising a notification if the user must enter credentials.
1594 * This method is intended for background tasks and services where the
1595 * user should not be immediately interrupted with a password prompt.
1596 *
1597 * <p>If a previously generated auth token is cached for this account and
1598 * type, then it is returned. Otherwise, if a saved password is
1599 * available, it is sent to the server to generate a new auth token.
1600 * Otherwise, an {@link Intent} is returned which, when started, will
1601 * prompt the user for a password. If the notifyAuthFailure parameter is
1602 * set, a status bar notification is also created with the same Intent,
1603 * alerting the user that they need to enter a password at some point.
1604 *
1605 * <p>In that case, you may need to wait until the user responds, which
1606 * could take hours or days or forever. When the user does respond and
1607 * supply a new password, the account manager will broadcast the
1608 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1609 * use to try again.
1610 *
1611 * <p>If notifyAuthFailure is not set, it is the application's
1612 * responsibility to launch the returned Intent at some point.
1613 * Either way, the result from this call will not wait for user action.
1614 *
1615 * <p>Some authenticators have auth token <em>types</em>, whose value
1616 * is authenticator-dependent. Some services use different token types to
1617 * access different functionality -- for example, Google uses different auth
1618 * tokens to access Gmail and Google Calendar for the same account.
1619 *
1620 * <p>This method may be called from any thread, but the returned
1621 * {@link AccountManagerFuture} must not be used on the main thread.
1622 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001623 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001624 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001625 * this function in API level 22.
1626 *
Fred Quintanaad93a322011-09-08 13:21:01 -07001627 * @param account The account to fetch an auth token for
1628 * @param authTokenType The auth token type, an authenticator-dependent
1629 * string token, must not be null
1630 * @param options Authenticator-specific options for the request,
1631 * may be null or empty
1632 * @param notifyAuthFailure True to add a notification to prompt the
1633 * user for a password if necessary, false to leave that to the caller
1634 * @param callback Callback to invoke when the request completes,
1635 * null for no callback
1636 * @param handler {@link Handler} identifying the callback thread,
1637 * null for the main thread
1638 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1639 * at least the following fields on success:
1640 * <ul>
1641 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1642 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1643 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1644 * </ul>
1645 *
1646 * (Other authenticator-specific values may be returned.) If the user
1647 * must enter credentials, the returned Bundle contains only
1648 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1649 *
1650 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1651 * <ul>
1652 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1653 * <li> {@link OperationCanceledException} if the operation is canceled for
1654 * any reason, incluidng the user canceling a credential request
1655 * <li> {@link IOException} if the authenticator experienced an I/O problem
1656 * creating a new auth token, usually because of network trouble
1657 * </ul>
1658 * If the account is no longer present on the device, the return value is
1659 * authenticator-dependent. The caller should verify the validity of the
1660 * account before requesting an auth token.
1661 */
1662 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001663 final Account account, final String authTokenType, final Bundle options,
1664 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001665 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001666
Fred Quintanaad93a322011-09-08 13:21:01 -07001667 if (account == null) throw new IllegalArgumentException("account is null");
1668 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001669 final Bundle optionsIn = new Bundle();
1670 if (options != null) {
1671 optionsIn.putAll(options);
1672 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001673 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001674 return new AmsTask(null, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001675 @Override
Fred Quintanaad93a322011-09-08 13:21:01 -07001676 public void doWork() throws RemoteException {
1677 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001678 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001679 }
1680 }.start();
1681 }
1682
1683 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001684 * Asks the user to add an account of a specified type. The authenticator
1685 * for this account type processes this request with the appropriate user
1686 * interface. If the user does elect to create a new account, the account
1687 * name is returned.
1688 *
1689 * <p>This method may be called from any thread, but the returned
1690 * {@link AccountManagerFuture} must not be used on the main thread.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001691 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001692 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1693 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1694 * this function in API level 22.
Dan Egnor661f0132010-02-19 11:23:00 -08001695 *
Dan Egnor661f0132010-02-19 11:23:00 -08001696 * @param accountType The type of account to add; must not be null
1697 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1698 * this account will need to be able to generate, null for none
1699 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1700 * account must have, null for none
1701 * @param addAccountOptions Authenticator-specific options for the request,
1702 * may be null or empty
1703 * @param activity The {@link Activity} context to use for launching a new
1704 * authenticator-defined sub-Activity to prompt the user to create an
1705 * account; used only to call startActivity(); if null, the prompt
1706 * will not be launched directly, but the necessary {@link Intent}
1707 * will be returned to the caller instead
1708 * @param callback Callback to invoke when the request completes,
1709 * null for no callback
1710 * @param handler {@link Handler} identifying the callback thread,
1711 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001712 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001713 * these fields if activity was specified and an account was created:
1714 * <ul>
1715 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1716 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1717 * </ul>
1718 *
1719 * If no activity was specified, the returned Bundle contains only
1720 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001721 * actual account creation process. If an error occurred,
1722 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001723 * <ul>
1724 * <li> {@link AuthenticatorException} if no authenticator was registered for
1725 * this account type or the authenticator failed to respond
1726 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001727 * any reason, including the user canceling the creation process or adding accounts
1728 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001729 * <li> {@link IOException} if the authenticator experienced an I/O problem
1730 * creating a new account, usually because of network trouble
1731 * </ul>
1732 */
1733 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1734 final String authTokenType, final String[] requiredFeatures,
1735 final Bundle addAccountOptions,
1736 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001737 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001738 final Bundle optionsIn = new Bundle();
1739 if (addAccountOptions != null) {
1740 optionsIn.putAll(addAccountOptions);
1741 }
1742 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001743
Dan Egnor661f0132010-02-19 11:23:00 -08001744 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001745 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001746 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001747 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001748 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001749 }
1750 }.start();
1751 }
1752
1753 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001754 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1755 * @hide
1756 */
1757 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1758 final String authTokenType, final String[] requiredFeatures,
1759 final Bundle addAccountOptions, final Activity activity,
1760 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1761 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1762 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1763 final Bundle optionsIn = new Bundle();
1764 if (addAccountOptions != null) {
1765 optionsIn.putAll(addAccountOptions);
1766 }
1767 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1768
1769 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001770 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001771 public void doWork() throws RemoteException {
1772 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1773 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1774 }
1775 }.start();
1776 }
1777
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001778
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001779 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001780 * Adds shared accounts from a parent user to a secondary user. Adding the shared account
Amith Yamasani67df64b2012-12-14 12:09:36 -08001781 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1782 * are attempted to be copied to the target user from the primary via calls to the
1783 * authenticator.
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001784 * @param parentUser parent user
1785 * @param user target user
Amith Yamasani67df64b2012-12-14 12:09:36 -08001786 * @hide
1787 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001788 public void addSharedAccountsFromParentUser(UserHandle parentUser, UserHandle user) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001789 try {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001790 mService.addSharedAccountsFromParentUser(parentUser.getIdentifier(),
1791 user.getIdentifier());
Amith Yamasani67df64b2012-12-14 12:09:36 -08001792 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001793 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001794 }
1795 }
1796
1797 /**
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001798 * Copies an account from one user to another user.
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001799 * @param account the account to copy
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001800 * @param fromUser the user to copy the account from
1801 * @param toUser the target user
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001802 * @param callback Callback to invoke when the request completes,
1803 * null for no callback
1804 * @param handler {@link Handler} identifying the callback thread,
1805 * null for the main thread
1806 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1807 * succeeded.
1808 * @hide
1809 */
1810 public AccountManagerFuture<Boolean> copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001811 final Account account, final UserHandle fromUser, final UserHandle toUser,
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001812 AccountManagerCallback<Boolean> callback, Handler handler) {
1813 if (account == null) throw new IllegalArgumentException("account is null");
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001814 if (toUser == null || fromUser == null) {
1815 throw new IllegalArgumentException("fromUser and toUser cannot be null");
1816 }
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001817
1818 return new Future2Task<Boolean>(handler, callback) {
1819 @Override
1820 public void doWork() throws RemoteException {
1821 mService.copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001822 mResponse, account, fromUser.getIdentifier(), toUser.getIdentifier());
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001823 }
1824 @Override
1825 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1826 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1827 throw new AuthenticatorException("no result in response");
1828 }
1829 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1830 }
1831 }.start();
1832 }
1833
1834 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001835 * @hide
1836 * Removes the shared account.
1837 * @param account the account to remove
1838 * @param user the user to remove the account from
1839 * @return
1840 */
1841 public boolean removeSharedAccount(final Account account, UserHandle user) {
1842 try {
1843 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1844 return val;
1845 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001846 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001847 }
1848 }
1849
1850 /**
1851 * @hide
1852 * @param user
1853 * @return
1854 */
1855 public Account[] getSharedAccounts(UserHandle user) {
1856 try {
1857 return mService.getSharedAccountsAsUser(user.getIdentifier());
1858 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001859 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001860 }
1861 }
1862
1863 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001864 * Confirms that the user knows the password for an account to make extra
1865 * sure they are the owner of the account. The user-entered password can
1866 * be supplied directly, otherwise the authenticator for this account type
1867 * prompts the user with the appropriate interface. This method is
1868 * intended for applications which want extra assurance; for example, the
1869 * phone lock screen uses this to let the user unlock the phone with an
1870 * account password if they forget the lock pattern.
1871 *
1872 * <p>If the user-entered password matches a saved password for this
1873 * account, the request is considered valid; otherwise the authenticator
1874 * verifies the password (usually by contacting the server).
1875 *
1876 * <p>This method may be called from any thread, but the returned
1877 * {@link AccountManagerFuture} must not be used on the main thread.
1878 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001879 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1880 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
1881 * for this function in API level 22.
1882 *
Dan Egnor661f0132010-02-19 11:23:00 -08001883 * @param account The account to confirm password knowledge for
1884 * @param options Authenticator-specific options for the request;
1885 * if the {@link #KEY_PASSWORD} string field is present, the
1886 * authenticator may use it directly rather than prompting the user;
1887 * may be null or empty
1888 * @param activity The {@link Activity} context to use for launching a new
1889 * authenticator-defined sub-Activity to prompt the user to enter a
1890 * password; used only to call startActivity(); if null, the prompt
1891 * will not be launched directly, but the necessary {@link Intent}
1892 * will be returned to the caller instead
1893 * @param callback Callback to invoke when the request completes,
1894 * null for no callback
1895 * @param handler {@link Handler} identifying the callback thread,
1896 * null for the main thread
1897 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1898 * with these fields if activity or password was supplied and
1899 * the account was successfully verified:
1900 * <ul>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001901 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001902 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1903 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1904 * </ul>
1905 *
1906 * If no activity or password was specified, the returned Bundle contains
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001907 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1908 * password prompt.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001909 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001910 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001911 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001912 * credential was validated/created.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001913 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001914 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001915 * <ul>
1916 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1917 * <li> {@link OperationCanceledException} if the operation was canceled for
1918 * any reason, including the user canceling the password prompt
1919 * <li> {@link IOException} if the authenticator experienced an I/O problem
1920 * verifying the password, usually because of network trouble
1921 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001922 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001923 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1924 final Bundle options,
1925 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001926 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001927 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001928 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1929 Process.myUserHandle());
1930 }
1931
1932 /**
1933 * @hide
1934 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1935 * but for the specified user.
1936 */
1937 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1938 final Bundle options,
1939 final Activity activity,
1940 final AccountManagerCallback<Bundle> callback,
1941 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001942 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001943 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001944 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001945 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001946 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001947 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1948 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001949 }
Fred Quintana33269202009-04-20 16:05:10 -07001950 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001951 }
1952
Fred Quintana756b7352009-10-21 13:43:10 -07001953 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001954 * Asks the user to enter a new password for an account, updating the
1955 * saved credentials for the account. Normally this happens automatically
1956 * when the server rejects credentials during an auth token fetch, but this
1957 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001958 *
Dan Egnor661f0132010-02-19 11:23:00 -08001959 * <p>This method may be called from any thread, but the returned
1960 * {@link AccountManagerFuture} must not be used on the main thread.
1961 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001962 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1963 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1964 * this function in API level 22.
1965 *
Dan Egnor661f0132010-02-19 11:23:00 -08001966 * @param account The account to update credentials for
1967 * @param authTokenType The credentials entered must allow an auth token
1968 * of this type to be created (but no actual auth token is returned);
1969 * may be null
1970 * @param options Authenticator-specific options for the request;
1971 * may be null or empty
1972 * @param activity The {@link Activity} context to use for launching a new
1973 * authenticator-defined sub-Activity to prompt the user to enter a
1974 * password; used only to call startActivity(); if null, the prompt
1975 * will not be launched directly, but the necessary {@link Intent}
1976 * will be returned to the caller instead
1977 * @param callback Callback to invoke when the request completes,
1978 * null for no callback
1979 * @param handler {@link Handler} identifying the callback thread,
1980 * null for the main thread
1981 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1982 * with these fields if an activity was supplied and the account
1983 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001984 * <ul>
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001985 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
Dan Egnor661f0132010-02-19 11:23:00 -08001986 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001987 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001988 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001989 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08001990 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001991 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07001992 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001993 * <ul>
1994 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1995 * <li> {@link OperationCanceledException} if the operation was canceled for
1996 * any reason, including the user canceling the password prompt
1997 * <li> {@link IOException} if the authenticator experienced an I/O problem
1998 * verifying the password, usually because of network trouble
1999 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002000 */
2001 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
2002 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07002003 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002004 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002005 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07002006 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07002007 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002008 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002009 public void doWork() throws RemoteException {
2010 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07002011 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07002012 }
Fred Quintana33269202009-04-20 16:05:10 -07002013 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002014 }
2015
Fred Quintana756b7352009-10-21 13:43:10 -07002016 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002017 * Offers the user an opportunity to change an authenticator's settings.
2018 * These properties are for the authenticator in general, not a particular
2019 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07002020 *
Dan Egnor661f0132010-02-19 11:23:00 -08002021 * <p>This method may be called from any thread, but the returned
2022 * {@link AccountManagerFuture} must not be used on the main thread.
2023 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002024 * <p>This method requires the caller to have the same signature as the
2025 * authenticator associated with the specified account type.
Dan Egnor661f0132010-02-19 11:23:00 -08002026 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002027 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
2028 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
2029 * for this function in API level 22.
2030 *
Dan Egnor661f0132010-02-19 11:23:00 -08002031 * @param accountType The account type associated with the authenticator
2032 * to adjust
2033 * @param activity The {@link Activity} context to use for launching a new
2034 * authenticator-defined sub-Activity to adjust authenticator settings;
2035 * used only to call startActivity(); if null, the settings dialog will
2036 * not be launched directly, but the necessary {@link Intent} will be
2037 * returned to the caller instead
2038 * @param callback Callback to invoke when the request completes,
2039 * null for no callback
2040 * @param handler {@link Handler} identifying the callback thread,
2041 * null for the main thread
2042 * @return An {@link AccountManagerFuture} which resolves to a Bundle
2043 * which is empty if properties were edited successfully, or
2044 * if no activity was specified, contains only {@link #KEY_INTENT}
2045 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07002046 * If an error occurred, {@link AccountManagerFuture#getResult()}
2047 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07002048 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002049 * <li> {@link AuthenticatorException} if no authenticator was registered for
2050 * this account type or the authenticator failed to respond
2051 * <li> {@link OperationCanceledException} if the operation was canceled for
2052 * any reason, including the user canceling the settings dialog
2053 * <li> {@link IOException} if the authenticator experienced an I/O problem
2054 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07002055 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002056 */
2057 public AccountManagerFuture<Bundle> editProperties(final String accountType,
2058 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002059 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07002060 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07002061 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002062 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002063 public void doWork() throws RemoteException {
2064 mService.editProperties(mResponse, accountType, activity != null);
2065 }
Fred Quintana33269202009-04-20 16:05:10 -07002066 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002067 }
2068
Amith Yamasani12747872015-12-07 14:19:49 -08002069 /**
2070 * @hide
2071 * Checks if the given account exists on any of the users on the device.
2072 * Only the system process can call this method.
2073 *
2074 * @param account The account to check for existence.
2075 * @return whether any user has this account
2076 */
2077 public boolean someUserHasAccount(@NonNull final Account account) {
2078 try {
2079 return mService.someUserHasAccount(account);
2080 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002081 throw re.rethrowFromSystemServer();
Amith Yamasani12747872015-12-07 14:19:49 -08002082 }
2083 }
2084
Fred Quintanaa698f422009-04-08 19:14:54 -07002085 private void ensureNotOnMainThread() {
2086 final Looper looper = Looper.myLooper();
2087 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08002088 final IllegalStateException exception = new IllegalStateException(
2089 "calling this from your main thread can lead to deadlock");
2090 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
2091 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08002092 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2093 throw exception;
2094 }
Fred Quintana60307342009-03-24 22:48:12 -07002095 }
2096 }
2097
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002098 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
2099 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07002100 handler = handler == null ? mMainHandler : handler;
2101 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002102 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002103 public void run() {
2104 callback.run(future);
2105 }
2106 });
2107 }
Fred Quintana60307342009-03-24 22:48:12 -07002108
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002109 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002110 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002111 final Account[] accountsCopy = new Account[accounts.length];
2112 // send a copy to make sure that one doesn't
2113 // change what another sees
2114 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
2115 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002116 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002117 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002118 public void run() {
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002119 synchronized (mAccountsUpdatedListeners) {
2120 try {
2121 if (mAccountsUpdatedListeners.containsKey(listener)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002122 Set<String> types = mAccountsUpdatedListenersTypes.get(listener);
2123 if (types != null) {
2124 // filter by account type;
2125 ArrayList<Account> filtered = new ArrayList<>();
2126 for (Account account : accountsCopy) {
2127 if (types.contains(account.type)) {
2128 filtered.add(account);
2129 }
2130 }
2131 listener.onAccountsUpdated(
2132 filtered.toArray(new Account[filtered.size()]));
2133 } else {
2134 listener.onAccountsUpdated(accountsCopy);
2135 }
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002136 }
2137 } catch (SQLException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002138 // Better luck next time. If the problem was disk-full,
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002139 // the STORAGE_OK intent will re-trigger the update.
2140 Log.e(TAG, "Can't update accounts", e);
2141 }
Costin Manolacheb6437242009-09-10 16:14:12 -07002142 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002143 }
2144 });
2145 }
2146
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002147 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07002148 final IAccountManagerResponse mResponse;
2149 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002150 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07002151 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002152 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002153 super(new Callable<Bundle>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002154 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002155 public Bundle call() throws Exception {
2156 throw new IllegalStateException("this should never be called");
2157 }
2158 });
2159
2160 mHandler = handler;
2161 mCallback = callback;
2162 mActivity = activity;
2163 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07002164 }
2165
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002166 public final AccountManagerFuture<Bundle> start() {
2167 try {
2168 doWork();
2169 } catch (RemoteException e) {
2170 setException(e);
2171 }
Fred Quintana33269202009-04-20 16:05:10 -07002172 return this;
Fred Quintana60307342009-03-24 22:48:12 -07002173 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002174
Sandra Kwan0b84b452016-01-20 15:25:42 -08002175 @Override
Fred Quintana96580e02010-03-04 13:42:42 -08002176 protected void set(Bundle bundle) {
2177 // TODO: somehow a null is being set as the result of the Future. Log this
2178 // case to help debug where this is occurring. When this bug is fixed this
2179 // condition statement should be removed.
2180 if (bundle == null) {
2181 Log.e(TAG, "the bundle must not be null", new Exception());
2182 }
2183 super.set(bundle);
2184 }
2185
Fred Quintanaa698f422009-04-08 19:14:54 -07002186 public abstract void doWork() throws RemoteException;
2187
2188 private Bundle internalGetResult(Long timeout, TimeUnit unit)
2189 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08002190 if (!isDone()) {
2191 ensureNotOnMainThread();
2192 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002193 try {
2194 if (timeout == null) {
2195 return get();
2196 } else {
2197 return get(timeout, unit);
2198 }
2199 } catch (CancellationException e) {
2200 throw new OperationCanceledException();
2201 } catch (TimeoutException e) {
2202 // fall through and cancel
2203 } catch (InterruptedException e) {
2204 // fall through and cancel
2205 } catch (ExecutionException e) {
2206 final Throwable cause = e.getCause();
2207 if (cause instanceof IOException) {
2208 throw (IOException) cause;
2209 } else if (cause instanceof UnsupportedOperationException) {
2210 throw new AuthenticatorException(cause);
2211 } else if (cause instanceof AuthenticatorException) {
2212 throw (AuthenticatorException) cause;
2213 } else if (cause instanceof RuntimeException) {
2214 throw (RuntimeException) cause;
2215 } else if (cause instanceof Error) {
2216 throw (Error) cause;
2217 } else {
2218 throw new IllegalStateException(cause);
2219 }
2220 } finally {
2221 cancel(true /* interrupt if running */);
2222 }
2223 throw new OperationCanceledException();
2224 }
2225
Sandra Kwan0b84b452016-01-20 15:25:42 -08002226 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002227 public Bundle getResult()
2228 throws OperationCanceledException, IOException, AuthenticatorException {
2229 return internalGetResult(null, null);
2230 }
2231
Sandra Kwan0b84b452016-01-20 15:25:42 -08002232 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002233 public Bundle getResult(long timeout, TimeUnit unit)
2234 throws OperationCanceledException, IOException, AuthenticatorException {
2235 return internalGetResult(timeout, unit);
2236 }
2237
Sandra Kwan0b84b452016-01-20 15:25:42 -08002238 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002239 protected void done() {
2240 if (mCallback != null) {
2241 postToHandler(mHandler, mCallback, this);
2242 }
2243 }
2244
2245 /** Handles the responses from the AccountManager */
2246 private class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002247 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002248 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07002249 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07002250 if (intent != null && mActivity != null) {
2251 // since the user provided an Activity we will silently start intents
2252 // that we see
2253 mActivity.startActivity(intent);
2254 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002255 } else if (bundle.getBoolean("retry")) {
2256 try {
2257 doWork();
2258 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002259 throw e.rethrowFromSystemServer();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002260 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002261 } else {
2262 set(bundle);
2263 }
2264 }
2265
Sandra Kwan0b84b452016-01-20 15:25:42 -08002266 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002267 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002268 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2269 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2270 // the authenticator indicated that this request was canceled or we were
2271 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07002272 cancel(true /* mayInterruptIfRunning */);
2273 return;
2274 }
2275 setException(convertErrorToException(code, message));
2276 }
2277 }
2278
Fred Quintana60307342009-03-24 22:48:12 -07002279 }
2280
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002281 private abstract class BaseFutureTask<T> extends FutureTask<T> {
2282 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002283 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002284
2285 public BaseFutureTask(Handler handler) {
2286 super(new Callable<T>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002287 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002288 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07002289 throw new IllegalStateException("this should never be called");
2290 }
2291 });
Fred Quintanaa698f422009-04-08 19:14:54 -07002292 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002293 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07002294 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002295
2296 public abstract void doWork() throws RemoteException;
2297
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002298 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07002299
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002300 protected void postRunnableToHandler(Runnable runnable) {
2301 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
2302 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07002303 }
2304
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002305 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002306 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002307 doWork();
2308 } catch (RemoteException e) {
2309 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07002310 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002311 }
2312
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002313 protected class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002314 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002315 public void onResult(Bundle bundle) {
2316 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002317 T result = bundleToResult(bundle);
2318 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002319 return;
2320 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002321 set(result);
2322 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002323 } catch (ClassCastException e) {
2324 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002325 } catch (AuthenticatorException e) {
2326 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07002327 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002328 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07002329 }
2330
Sandra Kwan0b84b452016-01-20 15:25:42 -08002331 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002332 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002333 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2334 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2335 // the authenticator indicated that this request was canceled or we were
2336 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07002337 cancel(true /* mayInterruptIfRunning */);
2338 return;
2339 }
2340 setException(convertErrorToException(code, message));
2341 }
2342 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002343 }
2344
2345 private abstract class Future2Task<T>
2346 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
2347 final AccountManagerCallback<T> mCallback;
2348 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
2349 super(handler);
2350 mCallback = callback;
2351 }
2352
Sandra Kwan0b84b452016-01-20 15:25:42 -08002353 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002354 protected void done() {
2355 if (mCallback != null) {
2356 postRunnableToHandler(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002357 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002358 public void run() {
2359 mCallback.run(Future2Task.this);
2360 }
2361 });
2362 }
2363 }
2364
2365 public Future2Task<T> start() {
2366 startTask();
2367 return this;
2368 }
2369
2370 private T internalGetResult(Long timeout, TimeUnit unit)
2371 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08002372 if (!isDone()) {
2373 ensureNotOnMainThread();
2374 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002375 try {
2376 if (timeout == null) {
2377 return get();
2378 } else {
2379 return get(timeout, unit);
2380 }
2381 } catch (InterruptedException e) {
2382 // fall through and cancel
2383 } catch (TimeoutException e) {
2384 // fall through and cancel
2385 } catch (CancellationException e) {
2386 // fall through and cancel
2387 } catch (ExecutionException e) {
2388 final Throwable cause = e.getCause();
2389 if (cause instanceof IOException) {
2390 throw (IOException) cause;
2391 } else if (cause instanceof UnsupportedOperationException) {
2392 throw new AuthenticatorException(cause);
2393 } else if (cause instanceof AuthenticatorException) {
2394 throw (AuthenticatorException) cause;
2395 } else if (cause instanceof RuntimeException) {
2396 throw (RuntimeException) cause;
2397 } else if (cause instanceof Error) {
2398 throw (Error) cause;
2399 } else {
2400 throw new IllegalStateException(cause);
2401 }
2402 } finally {
2403 cancel(true /* interrupt if running */);
2404 }
2405 throw new OperationCanceledException();
2406 }
2407
Sandra Kwan0b84b452016-01-20 15:25:42 -08002408 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002409 public T getResult()
2410 throws OperationCanceledException, IOException, AuthenticatorException {
2411 return internalGetResult(null, null);
2412 }
2413
Sandra Kwan0b84b452016-01-20 15:25:42 -08002414 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002415 public T getResult(long timeout, TimeUnit unit)
2416 throws OperationCanceledException, IOException, AuthenticatorException {
2417 return internalGetResult(timeout, unit);
2418 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002419
Fred Quintana60307342009-03-24 22:48:12 -07002420 }
2421
Fred Quintanaa698f422009-04-08 19:14:54 -07002422 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002423 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002424 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002425 }
Fred Quintana60307342009-03-24 22:48:12 -07002426
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002427 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002428 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002429 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002430
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002431 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002432 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002433 }
2434
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002435 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002436 return new IllegalArgumentException(message);
2437 }
2438
2439 return new AuthenticatorException(message);
2440 }
2441
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002442 private class GetAuthTokenByTypeAndFeaturesTask
2443 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002444 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2445 final String[] features, Activity activityForPrompting,
2446 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002447 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002448 super(activityForPrompting, handler, callback);
2449 if (accountType == null) throw new IllegalArgumentException("account type is null");
2450 mAccountType = accountType;
2451 mAuthTokenType = authTokenType;
2452 mFeatures = features;
2453 mAddAccountOptions = addAccountOptions;
2454 mLoginOptions = loginOptions;
2455 mMyCallback = this;
2456 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002457 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002458 final String mAccountType;
2459 final String mAuthTokenType;
2460 final String[] mFeatures;
2461 final Bundle mAddAccountOptions;
2462 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002463 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002464 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002465
Sandra Kwan0b84b452016-01-20 15:25:42 -08002466 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002467 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002468 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2469 new AccountManagerCallback<Account[]>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002470 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002471 public void run(AccountManagerFuture<Account[]> future) {
2472 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07002473 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002474 accounts = future.getResult();
2475 } catch (OperationCanceledException e) {
2476 setException(e);
2477 return;
2478 } catch (IOException e) {
2479 setException(e);
2480 return;
2481 } catch (AuthenticatorException e) {
2482 setException(e);
2483 return;
Fred Quintana33269202009-04-20 16:05:10 -07002484 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002485
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002486 mNumAccounts = accounts.length;
2487
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002488 if (accounts.length == 0) {
2489 if (mActivity != null) {
2490 // no accounts, add one now. pretend that the user directly
2491 // made this request
2492 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2493 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2494 } else {
2495 // send result since we can't prompt to add an account
2496 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002497 result.putString(KEY_ACCOUNT_NAME, null);
2498 result.putString(KEY_ACCOUNT_TYPE, null);
2499 result.putString(KEY_AUTHTOKEN, null);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002500 result.putBinder(KEY_ACCOUNT_ACCESS_ID, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002501 try {
2502 mResponse.onResult(result);
2503 } catch (RemoteException e) {
2504 // this will never happen
2505 }
2506 // we are done
2507 }
2508 } else if (accounts.length == 1) {
2509 // have a single account, return an authtoken for it
2510 if (mActivity == null) {
2511 mFuture = getAuthToken(accounts[0], mAuthTokenType,
2512 false /* notifyAuthFailure */, mMyCallback, mHandler);
2513 } else {
2514 mFuture = getAuthToken(accounts[0],
2515 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002516 mActivity, mMyCallback, mHandler);
2517 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002518 } else {
2519 if (mActivity != null) {
2520 IAccountManagerResponse chooseResponse =
2521 new IAccountManagerResponse.Stub() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002522 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002523 public void onResult(Bundle value) throws RemoteException {
2524 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002525 value.getString(KEY_ACCOUNT_NAME),
Svet Ganovf6d424f12016-09-20 20:18:53 -07002526 value.getString(KEY_ACCOUNT_TYPE),
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002527 value.getString(KEY_ACCOUNT_ACCESS_ID));
Svet Ganovf6d424f12016-09-20 20:18:53 -07002528 mFuture = getAuthToken(account, mAuthTokenType,
2529 mLoginOptions, mActivity, mMyCallback,
2530 mHandler);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002531 }
Fred Quintana33269202009-04-20 16:05:10 -07002532
Sandra Kwan0b84b452016-01-20 15:25:42 -08002533 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002534 public void onError(int errorCode, String errorMessage)
2535 throws RemoteException {
2536 mResponse.onError(errorCode, errorMessage);
2537 }
2538 };
2539 // have many accounts, launch the chooser
2540 Intent intent = new Intent();
Dmitry Dementyev52745472016-12-02 10:27:45 -08002541 // TODO - this activity will not include
2542 // USER_MANAGED_NOT_VISIBLE
2543 // accounts. We need to move method to service
Amith Yamasani12b8e132013-03-14 10:48:07 -07002544 ComponentName componentName = ComponentName.unflattenFromString(
2545 Resources.getSystem().getString(
2546 R.string.config_chooseAccountActivity));
2547 intent.setClassName(componentName.getPackageName(),
2548 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002549 intent.putExtra(KEY_ACCOUNTS, accounts);
2550 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002551 new AccountManagerResponse(chooseResponse));
2552 mActivity.startActivity(intent);
2553 // the result will arrive via the IAccountManagerResponse
2554 } else {
2555 // send result since we can't prompt to select an account
2556 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002557 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002558 try {
2559 mResponse.onResult(result);
2560 } catch (RemoteException e) {
2561 // this will never happen
2562 }
2563 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07002564 }
Fred Quintana33269202009-04-20 16:05:10 -07002565 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002566 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002567 }
2568
Sandra Kwan0b84b452016-01-20 15:25:42 -08002569 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002570 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002571 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002572 final Bundle result = future.getResult();
2573 if (mNumAccounts == 0) {
2574 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2575 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2576 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2577 setException(new AuthenticatorException("account not in result"));
2578 return;
2579 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002580 final String accessId = result.getString(KEY_ACCOUNT_ACCESS_ID);
2581 final Account account = new Account(accountName, accountType, accessId);
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002582 mNumAccounts = 1;
2583 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2584 mMyCallback, mHandler);
2585 return;
2586 }
2587 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002588 } catch (OperationCanceledException e) {
2589 cancel(true /* mayInterruptIfRUnning */);
2590 } catch (IOException e) {
2591 setException(e);
2592 } catch (AuthenticatorException e) {
2593 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002594 }
2595 }
2596 }
2597
Fred Quintana756b7352009-10-21 13:43:10 -07002598 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -08002599 * This convenience helper combines the functionality of {@link #getAccountsByTypeAndFeatures},
2600 * {@link #getAuthToken}, and {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002601 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002602 * <p>
2603 * This method gets a list of the accounts matching specific type and feature set which are
2604 * visible to the caller or for which user can grant access (see {@link #getAccountsByType} for
2605 * details); if there is exactly one already visible account, it is used; if there are some
2606 * accounts for which user grant visibility, the user is prompted to pick one; if there are
2607 * none, the user is prompted to add one. Finally, an auth token is acquired for the chosen
2608 * account.
Dan Egnor661f0132010-02-19 11:23:00 -08002609 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002610 * <p>
2611 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
2612 * not be used on the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -08002613 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002614 * <p>
2615 * <b>NOTE:</b> If targeting your app to work on API level 22 and before, MANAGE_ACCOUNTS
2616 * permission is needed for those platforms. See docs for this function in API level 22.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002617 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002618 * @param accountType The account type required (see {@link #getAccountsByType}), must not be
2619 * null
2620 * @param authTokenType The desired auth token type (see {@link #getAuthToken}), must not be
2621 * null
2622 * @param features Required features for the account (see
2623 * {@link #getAccountsByTypeAndFeatures}), may be null or empty
2624 * @param activity The {@link Activity} context to use for launching new sub-Activities to
2625 * prompt to add an account, select an account, and/or enter a password, as necessary;
2626 * used only to call startActivity(); should not be null
2627 * @param addAccountOptions Authenticator-specific options to use for adding new accounts; may
2628 * be null or empty
2629 * @param getAuthTokenOptions Authenticator-specific options to use for getting auth tokens; may
2630 * be null or empty
2631 * @param callback Callback to invoke when the request completes, null for no callback
2632 * @param handler {@link Handler} identifying the callback thread, null for the main thread
2633 * @return An {@link AccountManagerFuture} which resolves to a Bundle with at least the
2634 * following fields:
2635 * <ul>
2636 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account
2637 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account
2638 * <li>{@link #KEY_AUTHTOKEN} - the auth token you wanted
2639 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002640 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002641 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
2642 * <ul>
2643 * <li>{@link AuthenticatorException} if no authenticator was registered for this
2644 * account type or the authenticator failed to respond
2645 * <li>{@link OperationCanceledException} if the operation was canceled for any reason,
2646 * including the user canceling any operation
2647 * <li>{@link IOException} if the authenticator experienced an I/O problem updating
2648 * settings, usually because of network trouble
2649 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002650 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002651 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002652 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002653 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07002654 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002655 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002656 if (accountType == null) throw new IllegalArgumentException("account type is null");
2657 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002658 final GetAuthTokenByTypeAndFeaturesTask task =
2659 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002660 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002661 task.start();
2662 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002663 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002664
Fred Quintana1121bb52011-09-14 23:19:35 -07002665 /**
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002666 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
2667 * String, String[], Bundle)}.
2668 *
Fred Quintana1121bb52011-09-14 23:19:35 -07002669 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2670 * accounts.
2671 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002672 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002673 * <p>
2674 * On success the activity returns a Bundle with the account name and type specified using
2675 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2676 * <p>
2677 * The most common case is to call this with one account type, e.g.:
2678 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002679 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002680 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002681 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2682 * selected one, according to the caller's definition of selected.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002683 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
Fred Quintana1121bb52011-09-14 23:19:35 -07002684 * shown. If not specified then this field will not limit the displayed accounts.
2685 * @param allowableAccountTypes an optional string array of account types. These are used
2686 * both to filter the shown accounts and to filter the list of account types that are shown
Simranjit Singh Kohli734f8fb2015-05-22 14:00:32 -07002687 * when adding an account. If not specified then this field will not limit the displayed
2688 * account types when adding an account.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002689 * @param alwaysPromptForAccount boolean that is ignored.
Fred Quintanad88324d2011-09-19 11:43:05 -07002690 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002691 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002692 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2693 * authTokenType parameter
2694 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2695 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002696 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002697 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002698 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002699 */
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002700 @Deprecated
2701 static public Intent newChooseAccountIntent(
2702 Account selectedAccount,
Baligh Uddinf2d248d2015-07-10 03:01:47 +00002703 ArrayList<Account> allowableAccounts,
Fred Quintana1121bb52011-09-14 23:19:35 -07002704 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002705 boolean alwaysPromptForAccount,
2706 String descriptionOverrideText,
2707 String addAccountAuthTokenType,
2708 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002709 Bundle addAccountOptions) {
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002710 return newChooseAccountIntent(
2711 selectedAccount,
2712 allowableAccounts,
2713 allowableAccountTypes,
2714 descriptionOverrideText,
2715 addAccountAuthTokenType,
2716 addAccountRequiredFeatures,
2717 addAccountOptions);
2718 }
2719
2720 /**
2721 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2722 * accounts.
2723 * The caller will then typically start the activity by calling
2724 * <code>startActivityForResult(intent, ...);</code>.
2725 * <p>
2726 * On success the activity returns a Bundle with the account name and type specified using
2727 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2728 * <p>
2729 * The most common case is to call this with one account type, e.g.:
2730 * <p>
2731 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null,
2732 * null);</pre>
2733 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2734 * selected one, according to the caller's definition of selected.
2735 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
2736 * shown. If not specified then this field will not limit the displayed accounts.
2737 * @param allowableAccountTypes an optional string array of account types. These are used
2738 * both to filter the shown accounts and to filter the list of account types that are shown
2739 * when adding an account. If not specified then this field will not limit the displayed
2740 * account types when adding an account.
2741 * @param descriptionOverrideText if non-null this string is used as the description in the
2742 * accounts chooser screen rather than the default
2743 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2744 * authTokenType parameter
2745 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2746 * requiredFeatures parameter
2747 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2748 * parameter
2749 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2750 */
2751 static public Intent newChooseAccountIntent(
2752 Account selectedAccount,
2753 List<Account> allowableAccounts,
2754 String[] allowableAccountTypes,
2755 String descriptionOverrideText,
2756 String addAccountAuthTokenType,
2757 String[] addAccountRequiredFeatures,
2758 Bundle addAccountOptions) {
Fred Quintana1121bb52011-09-14 23:19:35 -07002759 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002760 ComponentName componentName = ComponentName.unflattenFromString(
2761 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2762 intent.setClassName(componentName.getPackageName(),
2763 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002764 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
Craig Lafayette3c9c71d2015-07-14 10:48:46 -04002765 allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts));
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002766 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2767 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002768 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2769 addAccountOptions);
2770 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002771 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2772 descriptionOverrideText);
2773 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2774 addAccountAuthTokenType);
2775 intent.putExtra(
2776 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2777 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002778 return intent;
2779 }
2780
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002781 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002782 Maps.newHashMap();
2783
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002784 private final HashMap<OnAccountsUpdateListener, Set<String> > mAccountsUpdatedListenersTypes =
2785 Maps.newHashMap();
2786
Fred Quintanad9d2f112009-04-23 13:36:27 -07002787 /**
2788 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2789 * so that it can read the updated list of accounts and send them to the listener
2790 * in mAccountsUpdatedListeners.
2791 */
2792 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002793 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002794 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002795 final Account[] accounts = getAccounts();
2796 // send the result to the listeners
2797 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002798 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002799 mAccountsUpdatedListeners.entrySet()) {
2800 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002801 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002802 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002803 }
2804 };
2805
2806 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -08002807 * Adds an {@link OnAccountsUpdateListener} to this instance of the {@link AccountManager}. This
2808 * listener will be notified whenever user or AbstractAcccountAuthenticator made changes to
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002809 * accounts of any type related to the caller. This method is equivalent to
2810 * addOnAccountsUpdatedListener(listener, handler, updateImmediately, null)
Dan Egnor661f0132010-02-19 11:23:00 -08002811 *
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002812 * @see #addOnAccountsUpdatedListener(OnAccountsUpdateListener, Handler, boolean,
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002813 * String[])
2814 */
2815 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
2816 Handler handler, boolean updateImmediately) {
2817 addOnAccountsUpdatedListener(listener, handler,updateImmediately, null);
2818 }
2819
2820 /**
2821 * Adds an {@link OnAccountsUpdateListener} to this instance of the {@link AccountManager}. This
2822 * listener will be notified whenever user or AbstractAcccountAuthenticator made changes to
2823 * accounts of given types related to the caller -
2824 * either list of accounts returned by {@link #getAccounts()}
2825 * was changed, or new account was added for which user can grant access to the caller.
Dmitry Dementyev52745472016-12-02 10:27:45 -08002826 * <p>
2827 * As long as this listener is present, the AccountManager instance will not be
2828 * garbage-collected, and neither will the {@link Context} used to retrieve it, which may be a
2829 * large Activity instance. To avoid memory leaks, you must remove this listener before then.
2830 * Normally listeners are added in an Activity or Service's {@link Activity#onCreate} and
2831 * removed in {@link Activity#onDestroy}.
Dmitry Dementyev52745472016-12-02 10:27:45 -08002832 * <p>
2833 * It is safe to call this method from the main thread.
Ian Pedowitz845d14d2015-08-04 07:47:37 -07002834 *
Dan Egnor661f0132010-02-19 11:23:00 -08002835 * @param listener The listener to send notifications to
Dmitry Dementyev52745472016-12-02 10:27:45 -08002836 * @param handler {@link Handler} identifying the thread to use for notifications, null for the
2837 * main thread
2838 * @param updateImmediately If true, the listener will be invoked (on the handler thread) right
2839 * away with the current account list
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002840 * @param accountTypes If set, only changes to accounts of given types will be reported.
Fred Quintanad9d2f112009-04-23 13:36:27 -07002841 * @throws IllegalArgumentException if listener is null
2842 * @throws IllegalStateException if listener was already added
2843 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002844 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002845 Handler handler, boolean updateImmediately, String[] accountTypes) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07002846 if (listener == null) {
2847 throw new IllegalArgumentException("the listener is null");
2848 }
2849 synchronized (mAccountsUpdatedListeners) {
2850 if (mAccountsUpdatedListeners.containsKey(listener)) {
2851 throw new IllegalStateException("this listener is already added");
2852 }
2853 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2854
2855 mAccountsUpdatedListeners.put(listener, handler);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002856 if (accountTypes != null) {
2857 mAccountsUpdatedListenersTypes.put(listener,
2858 new HashSet<String>(Arrays.asList(accountTypes)));
2859 }
Dmitry Dementyev52745472016-12-02 10:27:45 -08002860
Fred Quintanad9d2f112009-04-23 13:36:27 -07002861 if (wasEmpty) {
2862 // Register a broadcast receiver to monitor account changes
2863 IntentFilter intentFilter = new IntentFilter();
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002864 // TODO get rid of the broadcast receiver
2865 // create android.os.ResultReceiver
2866 // send it to the service via aidl
2867 // handle onReceiveResult
2868 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002869 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002870 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Dmitry Dementyev52745472016-12-02 10:27:45 -08002871 // Register a broadcast receiver to monitor account changes
Fred Quintanad9d2f112009-04-23 13:36:27 -07002872 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2873 }
2874 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002875 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002876 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002877 }
2878 }
2879
2880 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002881 * Removes an {@link OnAccountsUpdateListener} previously registered with
2882 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2883 * receive notifications of account changes.
2884 *
2885 * <p>It is safe to call this method from the main thread.
2886 *
2887 * <p>No permission is required to call this method.
2888 *
2889 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002890 * @throws IllegalArgumentException if listener is null
2891 * @throws IllegalStateException if listener was not already added
2892 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002893 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002894 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002895 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002896 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002897 Log.e(TAG, "Listener was not previously added");
2898 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002899 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002900 mAccountsUpdatedListeners.remove(listener);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002901 mAccountsUpdatedListenersTypes.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002902 if (mAccountsUpdatedListeners.isEmpty()) {
2903 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2904 }
2905 }
2906 }
Sandra Kwan78812282015-11-04 11:19:47 -08002907
2908 /**
2909 * Asks the user to authenticate with an account of a specified type. The
2910 * authenticator for this account type processes this request with the
2911 * appropriate user interface. If the user does elect to authenticate with a
2912 * new account, a bundle of session data for installing the account later is
2913 * returned with optional account password and account status token.
2914 * <p>
2915 * This method may be called from any thread, but the returned
2916 * {@link AccountManagerFuture} must not be used on the main thread.
2917 * <p>
2918 * <p>
2919 * <b>NOTE:</b> The account will not be installed to the device by calling
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002920 * this api alone. #finishSession should be called after this to install the
2921 * account on device.
Sandra Kwan78812282015-11-04 11:19:47 -08002922 *
2923 * @param accountType The type of account to add; must not be null
2924 * @param authTokenType The type of auth token (see {@link #getAuthToken})
2925 * this account will need to be able to generate, null for none
2926 * @param requiredFeatures The features (see {@link #hasFeatures}) this
2927 * account must have, null for none
2928 * @param options Authenticator-specific options for the request, may be
2929 * null or empty
2930 * @param activity The {@link Activity} context to use for launching a new
2931 * authenticator-defined sub-Activity to prompt the user to
2932 * create an account; used only to call startActivity(); if null,
2933 * the prompt will not be launched directly, but the necessary
2934 * {@link Intent} will be returned to the caller instead
2935 * @param callback Callback to invoke when the request completes, null for
2936 * no callback
2937 * @param handler {@link Handler} identifying the callback thread, null for
2938 * the main thread
2939 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2940 * these fields if activity was specified and user was authenticated
2941 * with an account:
2942 * <ul>
2943 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
2944 * adding the the to the device later.
Sandra Kwan78812282015-11-04 11:19:47 -08002945 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
2946 * status of the account
2947 * </ul>
2948 * If no activity was specified, the returned Bundle contains only
2949 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2950 * actual account creation process. If authenticator doesn't support
2951 * this method, the returned Bundle contains only
2952 * {@link #KEY_ACCOUNT_SESSION_BUNDLE} with encrypted
2953 * {@code options} needed to add account later. If an error
2954 * occurred, {@link AccountManagerFuture#getResult()} throws:
2955 * <ul>
2956 * <li>{@link AuthenticatorException} if no authenticator was
2957 * registered for this account type or the authenticator failed to
2958 * respond
2959 * <li>{@link OperationCanceledException} if the operation was
2960 * canceled for any reason, including the user canceling the
2961 * creation process or adding accounts (of this type) has been
2962 * disabled by policy
2963 * <li>{@link IOException} if the authenticator experienced an I/O
2964 * problem creating a new account, usually because of network
2965 * trouble
2966 * </ul>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002967 * @see #finishSession
Sandra Kwan78812282015-11-04 11:19:47 -08002968 */
Sandra Kwane68c37e2015-11-12 17:11:49 -08002969 public AccountManagerFuture<Bundle> startAddAccountSession(
2970 final String accountType,
2971 final String authTokenType,
2972 final String[] requiredFeatures,
2973 final Bundle options,
2974 final Activity activity,
2975 AccountManagerCallback<Bundle> callback,
2976 Handler handler) {
Sandra Kwan78812282015-11-04 11:19:47 -08002977 if (accountType == null) throw new IllegalArgumentException("accountType is null");
2978 final Bundle optionsIn = new Bundle();
2979 if (options != null) {
2980 optionsIn.putAll(options);
2981 }
2982 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
2983
2984 return new AmsTask(activity, handler, callback) {
2985 @Override
2986 public void doWork() throws RemoteException {
Sandra Kwane68c37e2015-11-12 17:11:49 -08002987 mService.startAddAccountSession(
2988 mResponse,
2989 accountType,
2990 authTokenType,
2991 requiredFeatures,
2992 activity != null,
2993 optionsIn);
2994 }
2995 }.start();
2996 }
2997
2998 /**
2999 * Asks the user to enter a new password for an account but not updating the
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003000 * saved credentials for the account until {@link #finishSession} is called.
Sandra Kwane68c37e2015-11-12 17:11:49 -08003001 * <p>
3002 * This method may be called from any thread, but the returned
3003 * {@link AccountManagerFuture} must not be used on the main thread.
3004 * <p>
3005 * <b>NOTE:</b> The saved credentials for the account alone will not be
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003006 * updated by calling this API alone. #finishSession should be called after
3007 * this to update local credentials
Sandra Kwane68c37e2015-11-12 17:11:49 -08003008 *
3009 * @param account The account to update credentials for
3010 * @param authTokenType The credentials entered must allow an auth token of
3011 * this type to be created (but no actual auth token is
3012 * returned); may be null
3013 * @param options Authenticator-specific options for the request; may be
3014 * null or empty
3015 * @param activity The {@link Activity} context to use for launching a new
3016 * authenticator-defined sub-Activity to prompt the user to enter
3017 * a password; used only to call startActivity(); if null, the
3018 * prompt will not be launched directly, but the necessary
3019 * {@link Intent} will be returned to the caller instead
3020 * @param callback Callback to invoke when the request completes, null for
3021 * no callback
3022 * @param handler {@link Handler} identifying the callback thread, null for
3023 * the main thread
3024 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
3025 * these fields if an activity was supplied and user was
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003026 * successfully re-authenticated to the account:
Sandra Kwane68c37e2015-11-12 17:11:49 -08003027 * <ul>
3028 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
3029 * updating the local credentials on device later.
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003030 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3031 * status of the account
Sandra Kwane68c37e2015-11-12 17:11:49 -08003032 * </ul>
3033 * If no activity was specified, the returned Bundle contains
3034 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
3035 * password prompt. If an error occurred,
3036 * {@link AccountManagerFuture#getResult()} throws:
3037 * <ul>
3038 * <li>{@link AuthenticatorException} if the authenticator failed to
3039 * respond
3040 * <li>{@link OperationCanceledException} if the operation was
3041 * canceled for any reason, including the user canceling the
3042 * password prompt
3043 * <li>{@link IOException} if the authenticator experienced an I/O
3044 * problem verifying the password, usually because of network
3045 * trouble
3046 * </ul>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003047 * @see #finishSession
Sandra Kwane68c37e2015-11-12 17:11:49 -08003048 */
3049 public AccountManagerFuture<Bundle> startUpdateCredentialsSession(
3050 final Account account,
3051 final String authTokenType,
3052 final Bundle options,
3053 final Activity activity,
3054 final AccountManagerCallback<Bundle> callback,
3055 final Handler handler) {
3056 if (account == null) {
3057 throw new IllegalArgumentException("account is null");
3058 }
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003059
3060 // Always include the calling package name. This just makes life easier
3061 // down stream.
3062 final Bundle optionsIn = new Bundle();
3063 if (options != null) {
3064 optionsIn.putAll(options);
3065 }
3066 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
3067
Sandra Kwane68c37e2015-11-12 17:11:49 -08003068 return new AmsTask(activity, handler, callback) {
3069 @Override
3070 public void doWork() throws RemoteException {
3071 mService.startUpdateCredentialsSession(
3072 mResponse,
3073 account,
3074 authTokenType,
3075 activity != null,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003076 optionsIn);
Sandra Kwan78812282015-11-04 11:19:47 -08003077 }
3078 }.start();
3079 }
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003080
3081 /**
3082 * Finishes the session started by {@link #startAddAccountSession} or
3083 * {@link #startUpdateCredentialsSession}. This will either add the account
3084 * to AccountManager or update the local credentials stored.
3085 * <p>
3086 * This method may be called from any thread, but the returned
3087 * {@link AccountManagerFuture} must not be used on the main thread.
3088 *
3089 * @param sessionBundle a {@link Bundle} created by {@link #startAddAccountSession} or
3090 * {@link #startUpdateCredentialsSession}
3091 * @param activity The {@link Activity} context to use for launching a new
3092 * authenticator-defined sub-Activity to prompt the user to
3093 * create an account or reauthenticate existing account; used
3094 * only to call startActivity(); if null, the prompt will not
3095 * be launched directly, but the necessary {@link Intent} will
3096 * be returned to the caller instead
3097 * @param callback Callback to invoke when the request completes, null for
3098 * no callback
3099 * @param handler {@link Handler} identifying the callback thread, null for
3100 * the main thread
3101 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
3102 * these fields if an activity was supplied and an account was added
3103 * to device or local credentials were updated::
3104 * <ul>
3105 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account created
3106 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account
Hongming Jin8b442752016-06-26 10:36:21 -07003107 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3108 * status of the account
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003109 * </ul>
3110 * If no activity was specified and additional information is needed
3111 * from user, the returned Bundle may contains only
3112 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
3113 * actual account creation process. If an error occurred,
3114 * {@link AccountManagerFuture#getResult()} throws:
3115 * <ul>
3116 * <li>{@link AuthenticatorException} if no authenticator was
3117 * registered for this account type or the authenticator failed to
3118 * respond
3119 * <li>{@link OperationCanceledException} if the operation was
3120 * canceled for any reason, including the user canceling the
3121 * creation process or adding accounts (of this type) has been
3122 * disabled by policy
3123 * <li>{@link IOException} if the authenticator experienced an I/O
3124 * problem creating a new account, usually because of network
3125 * trouble
3126 * </ul>
3127 * @see #startAddAccountSession and #startUpdateCredentialsSession
3128 */
3129 public AccountManagerFuture<Bundle> finishSession(
3130 final Bundle sessionBundle,
3131 final Activity activity,
3132 AccountManagerCallback<Bundle> callback,
3133 Handler handler) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003134 return finishSessionAsUser(
3135 sessionBundle,
3136 activity,
3137 Process.myUserHandle(),
3138 callback,
3139 handler);
3140 }
3141
3142 /**
3143 * @see #finishSession
3144 * @hide
3145 */
3146 @SystemApi
3147 public AccountManagerFuture<Bundle> finishSessionAsUser(
3148 final Bundle sessionBundle,
3149 final Activity activity,
3150 final UserHandle userHandle,
3151 AccountManagerCallback<Bundle> callback,
3152 Handler handler) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003153 if (sessionBundle == null) {
3154 throw new IllegalArgumentException("sessionBundle is null");
3155 }
3156
3157 /* Add information required by add account flow */
3158 final Bundle appInfo = new Bundle();
3159 appInfo.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
3160
3161 return new AmsTask(activity, handler, callback) {
3162 @Override
3163 public void doWork() throws RemoteException {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003164 mService.finishSessionAsUser(
3165 mResponse,
3166 sessionBundle,
3167 activity != null,
3168 appInfo,
3169 userHandle.getIdentifier());
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003170 }
3171 }.start();
3172 }
Sandra Kwan390c9d22016-01-12 14:13:37 -08003173
3174 /**
3175 * Checks whether {@link #updateCredentials} or {@link #startUpdateCredentialsSession} should be
3176 * called with respect to the specified account.
3177 * <p>
3178 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
3179 * not be used on the main thread.
3180 *
3181 * @param account The {@link Account} to be checked whether {@link #updateCredentials} or
3182 * {@link #startUpdateCredentialsSession} should be called
3183 * @param statusToken a String of token to check account staus
3184 * @param callback Callback to invoke when the request completes, null for no callback
3185 * @param handler {@link Handler} identifying the callback thread, null for the main thread
3186 * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the credentials
3187 * of the account should be updated.
Sandra Kwan390c9d22016-01-12 14:13:37 -08003188 */
Sandra Kwan390c9d22016-01-12 14:13:37 -08003189 public AccountManagerFuture<Boolean> isCredentialsUpdateSuggested(
3190 final Account account,
3191 final String statusToken,
3192 AccountManagerCallback<Boolean> callback,
3193 Handler handler) {
3194 if (account == null) {
3195 throw new IllegalArgumentException("account is null");
3196 }
3197
3198 if (TextUtils.isEmpty(statusToken)) {
3199 throw new IllegalArgumentException("status token is empty");
3200 }
3201
3202 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003203 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003204 public void doWork() throws RemoteException {
3205 mService.isCredentialsUpdateSuggested(
3206 mResponse,
3207 account,
3208 statusToken);
3209 }
Sandra Kwan0b84b452016-01-20 15:25:42 -08003210 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003211 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
3212 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
3213 throw new AuthenticatorException("no result in response");
3214 }
3215 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
3216 }
3217 }.start();
3218 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003219
3220 /**
3221 * Gets whether a given package under a user has access to an account.
3222 * Can be called only from the system UID.
3223 *
3224 * @param account The account for which to check.
3225 * @param packageName The package for which to check.
3226 * @param userHandle The user for which to check.
3227 * @return True if the package can access the account.
3228 *
3229 * @hide
3230 */
3231 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3232 @NonNull UserHandle userHandle) {
3233 try {
3234 return mService.hasAccountAccess(account, packageName, userHandle);
3235 } catch (RemoteException e) {
3236 throw e.rethrowFromSystemServer();
3237 }
3238 }
3239
3240 /**
3241 * Creates an intent to request access to a given account for a UID.
3242 * The returned intent should be stated for a result where {@link
3243 * Activity#RESULT_OK} result means access was granted whereas {@link
3244 * Activity#RESULT_CANCELED} result means access wasn't granted. Can
3245 * be called only from the system UID.
3246 *
3247 * @param account The account for which to request.
3248 * @param packageName The package name which to request.
3249 * @param userHandle The user for which to request.
3250 * @return The intent to request account access or null if the package
3251 * doesn't exist.
3252 *
3253 * @hide
3254 */
3255 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3256 @NonNull String packageName, @NonNull UserHandle userHandle) {
3257 try {
3258 return mService.createRequestAccountAccessIntentSenderAsUser(account, packageName,
3259 userHandle);
3260 } catch (RemoteException e) {
3261 throw e.rethrowFromSystemServer();
3262 }
3263 }
Fred Quintana60307342009-03-24 22:48:12 -07003264}