blob: 1d9e3bb4b4bb0bdaff110dfb462d88675626dcb6 [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
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070021import android.annotation.NonNull;
Tor Norbye80b530a2015-04-23 16:36:09 -070022import android.annotation.RequiresPermission;
23import android.annotation.Size;
Sandra Kwana578d112015-12-16 16:01:43 -080024import android.annotation.SystemApi;
Fred Quintana60307342009-03-24 22:48:12 -070025import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080026import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070027import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070028import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080029import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070030import android.content.IntentFilter;
Amith Yamasani12b8e132013-03-14 10:48:07 -070031import android.content.res.Resources;
Costin Manolacheb6437242009-09-10 16:14:12 -070032import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080033import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070034import android.os.Bundle;
35import android.os.Handler;
36import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070037import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080038import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080039import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080040import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080041import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080042import android.util.Log;
43
44import com.android.internal.R;
45import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070046
Fred Quintanaa698f422009-04-08 19:14:54 -070047import java.io.IOException;
Fred Quintana1121bb52011-09-14 23:19:35 -070048import java.util.ArrayList;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080049import java.util.HashMap;
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -070050import java.util.List;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080051import java.util.Map;
Fred Quintanaa698f422009-04-08 19:14:54 -070052import java.util.concurrent.Callable;
53import java.util.concurrent.CancellationException;
54import java.util.concurrent.ExecutionException;
55import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080057import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070058
59/**
Dan Egnor661f0132010-02-19 11:23:00 -080060 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070061 * online accounts. The user enters credentials (username and password) once
62 * per account, granting applications access to online resources with
63 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070064 *
Dan Egnor661f0132010-02-19 11:23:00 -080065 * <p>Different online services have different ways of handling accounts and
66 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070067 * modules for different <em>account types</em>. Authenticators (which may be
68 * written by third parties) handle the actual details of validating account
69 * credentials and storing account information. For example, Google, Facebook,
70 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080071 *
72 * <p>Many servers support some notion of an <em>authentication token</em>,
73 * which can be used to authenticate a request to the server without sending
74 * the user's actual password. (Auth tokens are normally created with a
75 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070076 * can generate auth tokens for applications, so the application doesn't need to
77 * handle passwords directly. Auth tokens are normally reusable and cached by
78 * AccountManager, but must be refreshed periodically. It's the responsibility
79 * of applications to <em>invalidate</em> auth tokens when they stop working so
80 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080081 *
82 * <p>Applications accessing a server normally go through these steps:
83 *
84 * <ul>
85 * <li>Get an instance of AccountManager using {@link #get(Context)}.
86 *
87 * <li>List the available accounts using {@link #getAccountsByType} or
88 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
89 * be interested in accounts with one particular <em>type</em>, which
90 * identifies the authenticator. Account <em>features</em> are used to
91 * identify particular account subtypes and capabilities. Both the account
92 * type and features are authenticator-specific strings, and must be known by
93 * the application in coordination with its preferred authenticators.
94 *
95 * <li>Select one or more of the available accounts, possibly by asking the
96 * user for their preference. If no suitable accounts are available,
97 * {@link #addAccount} may be called to prompt the user to create an
98 * account of the appropriate type.
99 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700100 * <li><b>Important:</b> If the application is using a previously remembered
101 * account selection, it must make sure the account is still in the list
102 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
103 * for an account no longer on the device results in an undefined failure.
104 *
Dan Egnor661f0132010-02-19 11:23:00 -0800105 * <li>Request an auth token for the selected account(s) using one of the
106 * {@link #getAuthToken} methods or related helpers. Refer to the description
107 * of each method for exact usage and error handling details.
108 *
109 * <li>Make the request using the auth token. The form of the auth token,
110 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700111 * service you are accessing. The application may use whatever network and
112 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800113 *
114 * <li><b>Important:</b> If the request fails with an authentication error,
115 * it could be that a cached auth token is stale and no longer honored by
116 * the server. The application must call {@link #invalidateAuthToken} to remove
117 * the token from the cache, otherwise requests will continue failing! After
118 * invalidating the auth token, immediately go back to the "Request an auth
119 * token" step above. If the process fails the second time, then it can be
120 * treated as a "genuine" authentication failure and the user notified or other
121 * appropriate actions taken.
122 * </ul>
123 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700124 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800125 * prompt for credentials, present options, or ask the user to add an account.
126 * The caller may choose whether to allow AccountManager to directly launch the
127 * necessary user interface and wait for the user, or to return an Intent which
128 * the caller may use to launch the interface, or (in some cases) to install a
129 * notification which the user can select at any time to launch the interface.
130 * To have AccountManager launch the interface directly, the caller must supply
131 * the current foreground {@link Activity} context.
132 *
133 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700134 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800135 * run asynchronously. If a callback is provided then
136 * {@link AccountManagerCallback#run} will be invoked on the Handler's
137 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700138 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
139 * on the {@link AccountManagerFuture} returned by the method (and also passed
140 * to the callback). This method waits for the operation to complete (if
141 * necessary) and either returns the result or throws an exception if an error
142 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800143 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700144 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800145 *
146 * <p>Requests which may block, including
147 * {@link AccountManagerFuture#getResult()}, must never be called on
148 * the application's main event thread. These operations throw
149 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700150 */
151public class AccountManager {
152 private static final String TAG = "AccountManager";
153
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700154 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
155 public static final int ERROR_CODE_NETWORK_ERROR = 3;
156 public static final int ERROR_CODE_CANCELED = 4;
157 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
158 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
159 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
160 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700161 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700162
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800163 /** @hide */
164 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100165 /** @hide */
166 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800167
Dan Egnor661f0132010-02-19 11:23:00 -0800168 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700169 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800170 * from methods which return information about a particular account.
171 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700172 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800173
174 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700175 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800176 * from methods which return information about a particular account.
177 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700178 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800179
180 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700181 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800182 * from {@link #getAuthToken} and friends.
183 */
184 public static final String KEY_AUTHTOKEN = "authtoken";
185
186 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700187 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800188 * may require the caller to interact with the user. The Intent can
189 * be used to start the corresponding user interface activity.
190 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700191 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800192
193 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700194 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800195 * {@link #confirmCredentials}, rather than prompting the user with
196 * the standard password prompt.
197 */
198 public static final String KEY_PASSWORD = "password";
199
200 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700201
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700202 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
203 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800204 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700205 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
206 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800207 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
208 public static final String KEY_ERROR_CODE = "errorCode";
209 public static final String KEY_ERROR_MESSAGE = "errorMessage";
210 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700211
Costin Manolachea40c6302010-12-13 14:50:45 -0800212 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800213 * Bundle key used to supply the last time the credentials of the account
214 * were authenticated successfully. Time is specified in milliseconds since
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700215 * epoch. Associated time is updated on successful authentication of account
216 * on adding account, confirming credentials, or updating credentials.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800217 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700218 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800219
220 /**
Costin Manolachea40c6302010-12-13 14:50:45 -0800221 * Authenticators using 'customTokens' option will also get the UID of the
222 * caller
223 */
224 public static final String KEY_CALLER_UID = "callerUid";
225 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800226
Costin Manolached6060452011-01-24 16:11:36 -0800227 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700228 * The Android package of the caller will be set in the options bundle by the
229 * {@link AccountManager} and will be passed to the AccountManagerService and
230 * to the AccountAuthenticators. The uid of the caller will be known by the
231 * AccountManagerService as well as the AccountAuthenticators so they will be able to
232 * verify that the package is consistent with the uid (a uid might be shared by many
233 * packages).
234 */
235 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
236
237 /**
Costin Manolached6060452011-01-24 16:11:36 -0800238 * Boolean, if set and 'customTokens' the authenticator is responsible for
239 * notifications.
240 * @hide
241 */
242 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
243
Sandra Kwan78812282015-11-04 11:19:47 -0800244 /**
245 * Bundle key used for a {@link Bundle} in result from
246 * {@link #startAddAccountSession} and friends which returns session data
247 * for installing an account later.
Sandra Kwana578d112015-12-16 16:01:43 -0800248 * @hide
Sandra Kwan78812282015-11-04 11:19:47 -0800249 */
Sandra Kwana578d112015-12-16 16:01:43 -0800250 @SystemApi
Sandra Kwan78812282015-11-04 11:19:47 -0800251 public static final String KEY_ACCOUNT_SESSION_BUNDLE = "accountSessionBundle";
252
253 /**
254 * Bundle key used for the {@link String} account status token in result
255 * from {@link #startAddAccountSession} and friends which returns
256 * information about a particular account.
Sandra Kwana578d112015-12-16 16:01:43 -0800257 * @hide
Sandra Kwan78812282015-11-04 11:19:47 -0800258 */
Sandra Kwana578d112015-12-16 16:01:43 -0800259 @SystemApi
Sandra Kwan78812282015-11-04 11:19:47 -0800260 public static final String KEY_ACCOUNT_STATUS_TOKEN = "accountStatusToken";
261
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700262 public static final String ACTION_AUTHENTICATOR_INTENT =
263 "android.accounts.AccountAuthenticator";
264 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800265 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700266 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
267
Fred Quintana60307342009-03-24 22:48:12 -0700268 private final Context mContext;
269 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700270 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800271
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700272 /**
273 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800274 * when accounts are added, accounts are removed, or an
275 * account's credentials (saved password, etc) are changed.
276 *
277 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700278 */
279 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
280 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700281
Fred Quintana33269202009-04-20 16:05:10 -0700282 /**
283 * @hide
284 */
Fred Quintana60307342009-03-24 22:48:12 -0700285 public AccountManager(Context context, IAccountManager service) {
286 mContext = context;
287 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700288 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700289 }
290
Fred Quintana0eabf022009-04-27 15:08:17 -0700291 /**
292 * @hide used for testing only
293 */
294 public AccountManager(Context context, IAccountManager service, Handler handler) {
295 mContext = context;
296 mService = service;
297 mMainHandler = handler;
298 }
299
Fred Quintana756b7352009-10-21 13:43:10 -0700300 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800301 * @hide for internal use only
302 */
303 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700304 if (result != null) {
305 if (result.containsKey(KEY_AUTHTOKEN)
306 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
307 final Bundle newResult = new Bundle(result);
308 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
309 return newResult;
310 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800311 }
312 return result;
313 }
314
315 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800316 * Gets an AccountManager instance associated with a Context.
317 * The {@link Context} will be used as long as the AccountManager is
318 * active, so make sure to use a {@link Context} whose lifetime is
319 * commensurate with any listeners registered to
320 * {@link #addOnAccountsUpdatedListener} or similar methods.
321 *
322 * <p>It is safe to call this method from the main thread.
323 *
324 * <p>No permission is required to call this method.
325 *
Fred Quintana756b7352009-10-21 13:43:10 -0700326 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800327 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700328 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700329 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700330 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700331 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
332 }
333
Fred Quintana756b7352009-10-21 13:43:10 -0700334 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800335 * Gets the saved password associated with the account.
336 * This is intended for authenticators and related code; applications
337 * should get an auth token instead.
338 *
339 * <p>It is safe to call this method from the main thread.
340 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700341 * <p>This method requires the caller to have a signature match with the
342 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800343 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700344 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
345 * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs for
346 * this function in API level 22.
347 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700348 * @param account The account to query for a password. Must not be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800349 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700350 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700351 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700352 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700353 try {
354 return mService.getPassword(account);
355 } catch (RemoteException e) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000356 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700357 throw new RuntimeException(e);
358 }
359 }
360
Fred Quintana756b7352009-10-21 13:43:10 -0700361 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800362 * Gets the user data named by "key" associated with the account.
363 * This is intended for authenticators and related code to store
364 * arbitrary metadata along with accounts. The meaning of the keys
365 * and values is up to the authenticator for the account.
366 *
367 * <p>It is safe to call this method from the main thread.
368 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700369 * <p>This method requires the caller to have a signature match with the
370 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800371 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700372 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
373 * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs
374 * for this function in API level 22.
375 *
Dan Egnor661f0132010-02-19 11:23:00 -0800376 * @param account The account to query for user data
377 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700378 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700379 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700380 if (account == null) throw new IllegalArgumentException("account is null");
381 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700382 try {
383 return mService.getUserData(account, key);
384 } catch (RemoteException e) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000385 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700386 throw new RuntimeException(e);
387 }
388 }
389
Fred Quintana756b7352009-10-21 13:43:10 -0700390 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800391 * Lists the currently registered authenticators.
392 *
393 * <p>It is safe to call this method from the main thread.
394 *
395 * <p>No permission is required to call this method.
396 *
397 * @return An array of {@link AuthenticatorDescription} for every
398 * authenticator known to the AccountManager service. Empty (never
399 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700400 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700401 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700402 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100403 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
404 } catch (RemoteException e) {
405 // will never happen
406 throw new RuntimeException(e);
407 }
408 }
409
410 /**
411 * @hide
412 * Lists the currently registered authenticators for a given user id.
413 *
414 * <p>It is safe to call this method from the main thread.
415 *
416 * <p>The caller has to be in the same user or have the permission
417 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
418 *
419 * @return An array of {@link AuthenticatorDescription} for every
420 * authenticator known to the AccountManager service. Empty (never
421 * null) if no authenticators are known.
422 */
423 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
424 try {
425 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700426 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700427 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700428 throw new RuntimeException(e);
429 }
430 }
431
Fred Quintana756b7352009-10-21 13:43:10 -0700432 /**
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000433 * Lists all accounts of any type registered on the device.
434 * Equivalent to getAccountsByType(null).
Dan Egnor661f0132010-02-19 11:23:00 -0800435 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000436 * <p>It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800437 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000438 * <p>Clients of this method that have not been granted the
439 * {@link android.Manifest.permission#GET_ACCOUNTS} permission,
440 * will only see those accounts managed by AbstractAccountAuthenticators whose
441 * signature matches the client.
Dan Egnor661f0132010-02-19 11:23:00 -0800442 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000443 * @return An array of {@link Account}, one for each account. Empty
444 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700445 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700446 @NonNull
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000447 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700448 public Account[] getAccounts() {
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000449 try {
450 return mService.getAccounts(null, mContext.getOpPackageName());
451 } catch (RemoteException e) {
452 // won't ever happen
453 throw new RuntimeException(e);
454 }
Fred Quintana60307342009-03-24 22:48:12 -0700455 }
456
Fred Quintana756b7352009-10-21 13:43:10 -0700457 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700458 * @hide
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000459 * Lists all accounts of any type registered on the device for a given
460 * user id. Equivalent to getAccountsByType(null).
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100461 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000462 * <p>It is safe to call this method from the main thread.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100463 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000464 * <p>Clients of this method that have not been granted the
465 * {@link android.Manifest.permission#GET_ACCOUNTS} permission,
466 * will only see those accounts managed by AbstractAccountAuthenticators whose
467 * signature matches the client.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100468 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000469 * @return An array of {@link Account}, one for each account. Empty
470 * (never null) if no accounts have been added.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100471 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700472 @NonNull
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000473 @RequiresPermission(GET_ACCOUNTS)
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100474 public Account[] getAccountsAsUser(int userId) {
475 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700476 return mService.getAccountsAsUser(null, userId, mContext.getOpPackageName());
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100477 } catch (RemoteException e) {
478 // won't ever happen
479 throw new RuntimeException(e);
480 }
481 }
482
483 /**
484 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700485 * For use by internal activities. Returns the list of accounts that the calling package
486 * is authorized to use, particularly for shared accounts.
487 * @param packageName package name of the calling app.
488 * @param uid the uid of the calling app.
489 * @return the accounts that are available to this package and user.
490 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700491 @NonNull
Amith Yamasani27db4682013-03-30 17:07:47 -0700492 public Account[] getAccountsForPackage(String packageName, int uid) {
493 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700494 return mService.getAccountsForPackage(packageName, uid, mContext.getOpPackageName());
Amith Yamasani27db4682013-03-30 17:07:47 -0700495 } catch (RemoteException re) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000496 // won't ever happen
Amith Yamasani27db4682013-03-30 17:07:47 -0700497 throw new RuntimeException(re);
498 }
499 }
500
501 /**
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700502 * Returns the accounts visible to the specified package, in an environment where some apps
503 * are not authorized to view all accounts. This method can only be called by system apps.
504 * @param type The type of accounts to return, null to retrieve all accounts
505 * @param packageName The package name of the app for which the accounts are to be returned
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000506 * @return An array of {@link Account}, one per matching account. Empty
507 * (never null) if no accounts of the specified type have been added.
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700508 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700509 @NonNull
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700510 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
511 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700512 return mService.getAccountsByTypeForPackage(type, packageName,
513 mContext.getOpPackageName());
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700514 } catch (RemoteException re) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000515 // won't ever happen
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700516 throw new RuntimeException(re);
517 }
518 }
519
520 /**
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000521 * Lists all accounts of a particular type. The account type is a
522 * string token corresponding to the authenticator and useful domain
523 * of the account. For example, there are types corresponding to Google
524 * and Facebook. The exact string token to use will be published somewhere
525 * associated with the authenticator in question.
Dan Egnor661f0132010-02-19 11:23:00 -0800526 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000527 * <p>It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800528 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000529 * <p>Clients of this method that have not been granted the
530 * {@link android.Manifest.permission#GET_ACCOUNTS} permission,
531 * will only see those accounts managed by AbstractAccountAuthenticators whose
532 * signature matches the client.
Dan Egnor661f0132010-02-19 11:23:00 -0800533 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000534 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
535 * GET_ACCOUNTS permission is needed for those platforms, irrespective of uid
536 * or signature match. See docs for this function in API level 22.
537 *
538 * @param type The type of accounts to return, null to retrieve all accounts
539 * @return An array of {@link Account}, one per matching account. Empty
540 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700541 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700542 @NonNull
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000543 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700544 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800545 return getAccountsByTypeAsUser(type, Process.myUserHandle());
546 }
547
548 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700549 @NonNull
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800550 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700551 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700552 return mService.getAccountsAsUser(type, userHandle.getIdentifier(),
553 mContext.getOpPackageName());
Fred Quintana60307342009-03-24 22:48:12 -0700554 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700555 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700556 throw new RuntimeException(e);
557 }
558 }
559
Fred Quintana756b7352009-10-21 13:43:10 -0700560 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700561 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
562 * for an account.
563 * <p>
564 * This is only meant to be used by system activities and is not in the SDK.
565 * @param account The account whose permissions are being modified
566 * @param authTokenType The type of token whose permissions are being modified
567 * @param uid The uid that identifies the app which is being granted or revoked permission.
568 * @param value true is permission is being granted, false for revoked
569 * @hide
570 */
571 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
572 try {
573 mService.updateAppPermission(account, authTokenType, uid, value);
574 } catch (RemoteException e) {
575 // won't ever happen
576 throw new RuntimeException(e);
577 }
578 }
579
580 /**
581 * Get the user-friendly label associated with an authenticator's auth token.
582 * @param accountType the type of the authenticator. must not be null.
583 * @param authTokenType the token type. must not be null.
584 * @param callback callback to invoke when the result is available. may be null.
585 * @param handler the handler on which to invoke the callback, or null for the main thread
586 * @return a future containing the label string
587 * @hide
588 */
589 public AccountManagerFuture<String> getAuthTokenLabel(
590 final String accountType, final String authTokenType,
591 AccountManagerCallback<String> callback, Handler handler) {
592 if (accountType == null) throw new IllegalArgumentException("accountType is null");
593 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
594 return new Future2Task<String>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800595 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -0700596 public void doWork() throws RemoteException {
597 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
598 }
599
600 @Override
601 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
602 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
603 throw new AuthenticatorException("no result in response");
604 }
605 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
606 }
607 }.start();
608 }
609
610 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800611 * Finds out whether a particular account has all the specified features.
612 * Account features are authenticator-specific string tokens identifying
613 * boolean account properties. For example, features are used to tell
614 * whether Google accounts have a particular service (such as Google
615 * Calendar or Google Talk) enabled. The feature names and their meanings
616 * are published somewhere associated with the authenticator in question.
617 *
618 * <p>This method may be called from any thread, but the returned
619 * {@link AccountManagerFuture} must not be used on the main thread.
620 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000621 * <p>This method requires the caller to hold the permission
622 * {@link android.Manifest.permission#GET_ACCOUNTS} or be a signature
623 * match with the AbstractAccountAuthenticator that manages the account.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800624 *
625 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800626 * @param features An array of the account features to check
627 * @param callback Callback to invoke when the request completes,
628 * null for no callback
629 * @param handler {@link Handler} identifying the callback thread,
630 * null for the main thread
631 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000632 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800633 */
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000634 @RequiresPermission(GET_ACCOUNTS)
Fred Quintana3084a6f2010-01-14 18:02:03 -0800635 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800636 final String[] features,
637 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700638 if (account == null) throw new IllegalArgumentException("account is null");
639 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800640 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800641 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800642 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700643 mService.hasFeatures(mResponse, account, features, mContext.getOpPackageName());
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800644 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800645 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800646 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
647 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
648 throw new AuthenticatorException("no result in response");
649 }
650 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
651 }
652 }.start();
653 }
654
655 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800656 * Lists all accounts of a type which have certain features. The account
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000657 * type identifies the authenticator (see {@link #getAccountsByType}).
658 * Account features are authenticator-specific string tokens identifying
659 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700660 *
Dan Egnor661f0132010-02-19 11:23:00 -0800661 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
662 * which may contact the server or do other work to check account features,
663 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700664 *
Dan Egnor661f0132010-02-19 11:23:00 -0800665 * <p>This method may be called from any thread, but the returned
666 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700667 *
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000668 * <p>Clients of this method that have not been granted the
669 * {@link android.Manifest.permission#GET_ACCOUNTS} permission,
670 * will only see those accounts managed by AbstractAccountAuthenticators whose
671 * signature matches the client.
Fred Quintana756b7352009-10-21 13:43:10 -0700672 *
Dan Egnor661f0132010-02-19 11:23:00 -0800673 * @param type The type of accounts to return, must not be null
674 * @param features An array of the account features to require,
675 * may be null or empty
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000676 *
677 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
678 * GET_ACCOUNTS permission is needed for those platforms, irrespective of uid
679 * or signature match. See docs for this function in API level 22.
680 *
Dan Egnor661f0132010-02-19 11:23:00 -0800681 * @param callback Callback to invoke when the request completes,
682 * null for no callback
683 * @param handler {@link Handler} identifying the callback thread,
684 * null for the main thread
685 * @return An {@link AccountManagerFuture} which resolves to an array of
686 * {@link Account}, one per account of the specified type which
687 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800688 */
Carlos Valdiviabf33bd42016-02-02 20:20:42 +0000689 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700690 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
691 final String type, final String[] features,
692 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700693 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700694 return new Future2Task<Account[]>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800695 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700696 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700697 mService.getAccountsByFeatures(mResponse, type, features,
698 mContext.getOpPackageName());
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700699 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800700 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700701 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700702 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700703 throw new AuthenticatorException("no result in response");
704 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700705 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700706 Account[] descs = new Account[parcelables.length];
707 for (int i = 0; i < parcelables.length; i++) {
708 descs[i] = (Account) parcelables[i];
709 }
710 return descs;
711 }
712 }.start();
713 }
714
Fred Quintana756b7352009-10-21 13:43:10 -0700715 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700716 * Adds an account directly to the AccountManager. Normally used by sign-up
Dan Egnor661f0132010-02-19 11:23:00 -0800717 * wizards associated with authenticators, not directly by applications.
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700718 * <p>Calling this method does not update the last authenticated timestamp,
719 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
720 * {@link #notifyAccountAuthenticated(Account)} after getting success.
721 * However, if this method is called when it is triggered by addAccount() or
722 * addAccountAsUser() or similar functions, then there is no need to update
723 * timestamp manually as it is updated automatically by framework on
724 * successful completion of the mentioned functions.
Dan Egnor661f0132010-02-19 11:23:00 -0800725 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700726 * <p>This method requires the caller to have a signature match with the
727 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800728 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700729 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
730 * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs
731 * for this function in API level 22.
732 *
Dan Egnor661f0132010-02-19 11:23:00 -0800733 * @param account The {@link Account} to add
734 * @param password The password to associate with the account, null for none
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700735 * @param userdata String values to use for the account's userdata, null for
736 * none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700737 * @return True if the account was successfully added, false if the account
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700738 * already exists, the account is null, or another error occurs.
Dan Egnor661f0132010-02-19 11:23:00 -0800739 */
740 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700741 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800742 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700743 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800744 } catch (RemoteException e) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000745 // Can happen if there was a SecurityException was thrown.
Dan Egnor661f0132010-02-19 11:23:00 -0800746 throw new RuntimeException(e);
747 }
748 }
749
750 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700751 * Notifies the system that the account has just been authenticated. This
752 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800753 * should be called only when the user has entered correct credentials for
754 * the account.
755 * <p>
756 * It is not safe to call this method from the main thread. As such, call it
757 * from another thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700758 * <p>This method requires the caller to have a signature match with the
759 * authenticator that owns the specified account.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800760 *
761 * @param account The {@link Account} to be updated.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700762 * @return boolean {@code true} if the authentication of the account has been successfully
763 * acknowledged. Otherwise {@code false}.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800764 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700765 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800766 if (account == null)
767 throw new IllegalArgumentException("account is null");
768 try {
769 return mService.accountAuthenticated(account);
770 } catch (RemoteException e) {
771 throw new RuntimeException(e);
772 }
773 }
774
775 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700776 * Rename the specified {@link Account}. This is equivalent to removing
777 * the existing account and adding a new renamed account with the old
778 * account's user data.
779 *
780 * <p>It is safe to call this method from the main thread.
781 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700782 * <p>This method requires the caller to have a signature match with the
783 * authenticator that manages the specified account.
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700784 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700785 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
786 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
787 * is needed for those platforms. See docs for this function in API level 22.
788 *
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700789 * @param account The {@link Account} to rename
790 * @param newName String name to be associated with the account.
791 * @param callback Callback to invoke when the request completes, null for
792 * no callback
793 * @param handler {@link Handler} identifying the callback thread, null for
794 * the main thread
795 * @return An {@link AccountManagerFuture} which resolves to the Account
796 * after the name change. If successful the account's name will be the
797 * specified new name.
798 */
799 public AccountManagerFuture<Account> renameAccount(
800 final Account account,
Tor Norbye80b530a2015-04-23 16:36:09 -0700801 @Size(min = 1) final String newName,
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700802 AccountManagerCallback<Account> callback,
803 Handler handler) {
804 if (account == null) throw new IllegalArgumentException("account is null.");
805 if (TextUtils.isEmpty(newName)) {
806 throw new IllegalArgumentException("newName is empty or null.");
807 }
808 return new Future2Task<Account>(handler, callback) {
809 @Override
810 public void doWork() throws RemoteException {
811 mService.renameAccount(mResponse, account, newName);
812 }
813 @Override
814 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
815 String name = bundle.getString(KEY_ACCOUNT_NAME);
816 String type = bundle.getString(KEY_ACCOUNT_TYPE);
817 return new Account(name, type);
818 }
819 }.start();
820 }
821
822 /**
823 * Gets the previous name associated with the account or {@code null}, if
824 * none. This is intended so that clients of {@link
825 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
826 * authenticator has renamed an account.
827 *
828 * <p>It is safe to call this method from the main thread.
829 *
830 * @param account The account to query for a previous name.
831 * @return The account's previous name, null if the account has never been
832 * renamed.
833 */
834 public String getPreviousName(final Account account) {
835 if (account == null) throw new IllegalArgumentException("account is null");
836 try {
837 return mService.getPreviousName(account);
838 } catch (RemoteException e) {
839 // will never happen
840 throw new RuntimeException(e);
841 }
842 }
843
844 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800845 * Removes an account from the AccountManager. Does nothing if the account
846 * does not exist. Does not delete the account from the server.
847 * The authenticator may have its own policies preventing account
848 * deletion, in which case the account will not be deleted.
849 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700850 * <p>This method requires the caller to have a signature match with the
851 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800852 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700853 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
854 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
855 * this function in API level 22.
856 *
Dan Egnor661f0132010-02-19 11:23:00 -0800857 * @param account The {@link Account} to remove
858 * @param callback Callback to invoke when the request completes,
859 * null for no callback
860 * @param handler {@link Handler} identifying the callback thread,
861 * null for the main thread
862 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100863 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800864 * @deprecated use
865 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
866 * instead
Dan Egnor661f0132010-02-19 11:23:00 -0800867 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800868 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800869 public AccountManagerFuture<Boolean> removeAccount(final Account account,
870 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700871 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800872 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700873 @Override
Dan Egnor661f0132010-02-19 11:23:00 -0800874 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800875 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -0800876 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700877 @Override
Dan Egnor661f0132010-02-19 11:23:00 -0800878 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
879 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
880 throw new AuthenticatorException("no result in response");
881 }
882 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
883 }
884 }.start();
885 }
886
887 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800888 * Removes an account from the AccountManager. Does nothing if the account
889 * does not exist. Does not delete the account from the server.
890 * The authenticator may have its own policies preventing account
891 * deletion, in which case the account will not be deleted.
892 *
893 * <p>This method may be called from any thread, but the returned
894 * {@link AccountManagerFuture} must not be used on the main thread.
895 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700896 * <p>This method requires the caller to have a signature match with the
897 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800898 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700899 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
900 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
901 * this function in API level 22.
902 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800903 * @param account The {@link Account} to remove
904 * @param activity The {@link Activity} context to use for launching a new
905 * authenticator-defined sub-Activity to prompt the user to delete an
906 * account; used only to call startActivity(); if null, the prompt
907 * will not be launched directly, but the {@link Intent} may be
908 * returned to the caller instead
909 * @param callback Callback to invoke when the request completes,
910 * null for no callback
911 * @param handler {@link Handler} identifying the callback thread,
912 * null for the main thread
913 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
914 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
915 * was removed or if active. If no activity was specified, the returned
916 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
917 * needed to launch the actual account removal process, if authenticator
918 * needs the activity launch. If an error occurred,
919 * {@link AccountManagerFuture#getResult()} throws:
920 * <ul>
921 * <li> {@link AuthenticatorException} if no authenticator was registered for
922 * this account type or the authenticator failed to respond
923 * <li> {@link OperationCanceledException} if the operation was canceled for
924 * any reason, including the user canceling the creation process or
925 * adding accounts (of this type) has been disabled by policy
926 * </ul>
927 */
928 public AccountManagerFuture<Bundle> removeAccount(final Account account,
929 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
930 if (account == null) throw new IllegalArgumentException("account is null");
931 return new AmsTask(activity, handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700932 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800933 public void doWork() throws RemoteException {
934 mService.removeAccount(mResponse, account, activity != null);
935 }
936 }.start();
937 }
938
939 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100940 * @see #removeAccount(Account, AccountManagerCallback, Handler)
941 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800942 * @deprecated use
943 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
944 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100945 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800946 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100947 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
948 AccountManagerCallback<Boolean> callback, Handler handler,
949 final UserHandle userHandle) {
950 if (account == null) throw new IllegalArgumentException("account is null");
951 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
952 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700953 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100954 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800955 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100956 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700957 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100958 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
959 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
960 throw new AuthenticatorException("no result in response");
961 }
962 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
963 }
964 }.start();
965 }
966
967 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800968 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
969 * @hide
970 */
971 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
972 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
973 final UserHandle userHandle) {
974 if (account == null)
975 throw new IllegalArgumentException("account is null");
976 if (userHandle == null)
977 throw new IllegalArgumentException("userHandle is null");
978 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800979 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800980 public void doWork() throws RemoteException {
981 mService.removeAccountAsUser(mResponse, account, activity != null,
982 userHandle.getIdentifier());
983 }
984 }.start();
985 }
986
987 /**
988 * Removes an account directly. Normally used by authenticators, not
989 * directly by applications. Does not delete the account from the server.
990 * The authenticator may have its own policies preventing account deletion,
991 * in which case the account will not be deleted.
992 * <p>
993 * It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700994 * <p>This method requires the caller to have a signature match with the
995 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800996 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700997 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
998 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
999 * is needed for those platforms. See docs for this function in API level 22.
1000 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001001 * @param account The {@link Account} to delete.
1002 * @return True if the account was successfully deleted, false if the
1003 * account did not exist, the account is null, or another error
1004 * occurs.
1005 */
1006 public boolean removeAccountExplicitly(Account account) {
1007 if (account == null) throw new IllegalArgumentException("account is null");
1008 try {
1009 return mService.removeAccountExplicitly(account);
1010 } catch (RemoteException e) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001011 // May happen if the caller doesn't match the signature of the authenticator.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001012 throw new RuntimeException(e);
1013 }
1014 }
1015
1016 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001017 * Removes an auth token from the AccountManager's cache. Does nothing if
1018 * the auth token is not currently in the cache. Applications must call this
1019 * method when the auth token is found to have expired or otherwise become
1020 * invalid for authenticating requests. The AccountManager does not validate
1021 * or expire cached auth tokens otherwise.
1022 *
1023 * <p>It is safe to call this method from the main thread.
1024 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001025 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1026 * MANAGE_ACCOUNTS or USE_CREDENTIALS permission is needed for those
1027 * platforms. See docs for this function in API level 22.
1028 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001029 * @param accountType The account type of the auth token to invalidate, must not be null
1030 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -08001031 */
1032 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001033 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001034 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001035 if (authToken != null) {
1036 mService.invalidateAuthToken(accountType, authToken);
1037 }
Dan Egnor661f0132010-02-19 11:23:00 -08001038 } catch (RemoteException e) {
1039 // won't ever happen
1040 throw new RuntimeException(e);
1041 }
1042 }
1043
1044 /**
1045 * Gets an auth token from the AccountManager's cache. If no auth
1046 * token is cached for this account, null will be returned -- a new
1047 * auth token will not be generated, and the server will not be contacted.
1048 * Intended for use by the authenticator, not directly by applications.
1049 *
1050 * <p>It is safe to call this method from the main thread.
1051 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001052 * <p>This method requires the caller to have a signature match with the
1053 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001054 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001055 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1056 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1057 * is needed for those platforms. See docs for this function in API level 22.
1058 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001059 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001060 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001061 * @return The cached auth token for this account and type, or null if
1062 * no auth token is cached or the account does not exist.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001063 * @see #getAuthToken
Dan Egnor661f0132010-02-19 11:23:00 -08001064 */
1065 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -07001066 if (account == null) throw new IllegalArgumentException("account is null");
1067 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001068 try {
1069 return mService.peekAuthToken(account, authTokenType);
1070 } catch (RemoteException e) {
1071 // won't ever happen
1072 throw new RuntimeException(e);
1073 }
1074 }
1075
1076 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001077 * Sets or forgets a saved password. This modifies the local copy of the
1078 * password used to automatically authenticate the user; it does not change
1079 * the user's account password on the server. Intended for use by the
1080 * authenticator, not directly by applications.
1081 * <p>Calling this method does not update the last authenticated timestamp,
1082 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
1083 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dan Egnor661f0132010-02-19 11:23:00 -08001084 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001085 * <p>This method requires the caller to have a signature match with the
1086 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001087 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001088 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1089 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1090 * is needed for those platforms. See docs for this function in API level 22.
1091 *
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001092 * @param account The account whose password is to be set. Cannot be
1093 * {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001094 * @param password The password to set, null to clear the password
1095 */
1096 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -07001097 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001098 try {
1099 mService.setPassword(account, password);
1100 } catch (RemoteException e) {
1101 // won't ever happen
1102 throw new RuntimeException(e);
1103 }
1104 }
1105
1106 /**
1107 * Forgets a saved password. This erases the local copy of the password;
1108 * it does not change the user's account password on the server.
1109 * Has the same effect as setPassword(account, null) but requires fewer
1110 * permissions, and may be used by applications or management interfaces
1111 * to "sign out" from an account.
1112 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001113 * <p>This method only successfully clear the account's password when the
1114 * caller has the same signature as the authenticator that owns the
1115 * specified account. Otherwise, this method will silently fail.
Dan Egnor661f0132010-02-19 11:23:00 -08001116 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001117 * <p>It is safe to call this method from the main thread.
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001118 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001119 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1120 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1121 * this function in API level 22.
1122 *
Dan Egnor661f0132010-02-19 11:23:00 -08001123 * @param account The account whose password to clear
1124 */
1125 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001126 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001127 try {
1128 mService.clearPassword(account);
1129 } catch (RemoteException e) {
1130 // won't ever happen
1131 throw new RuntimeException(e);
1132 }
1133 }
1134
1135 /**
1136 * Sets one userdata key for an account. Intended by use for the
1137 * authenticator to stash state for itself, not directly by applications.
1138 * The meaning of the keys and values is up to the authenticator.
1139 *
1140 * <p>It is safe to call this method from the main thread.
1141 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001142 * <p>This method requires the caller to have a signature match with the
1143 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001144 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001145 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1146 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1147 * is needed for those platforms. See docs for this function in API level 22.
1148 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001149 * @param account Account whose user data is to be set. Must not be {@code null}.
1150 * @param key String user data key to set. Must not be null
1151 * @param value String value to set, {@code null} to clear this user data key
Dan Egnor661f0132010-02-19 11:23:00 -08001152 */
1153 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001154 if (account == null) throw new IllegalArgumentException("account is null");
1155 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001156 try {
1157 mService.setUserData(account, key, value);
1158 } catch (RemoteException e) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001159 // Will happen if there is not signature match.
Dan Egnor661f0132010-02-19 11:23:00 -08001160 throw new RuntimeException(e);
1161 }
1162 }
1163
1164 /**
1165 * Adds an auth token to the AccountManager cache for an account.
1166 * If the account does not exist then this call has no effect.
1167 * Replaces any previous auth token for this account and auth token type.
1168 * Intended for use by the authenticator, not directly by applications.
1169 *
1170 * <p>It is safe to call this method from the main thread.
1171 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001172 * <p>This method requires the caller to have a signature match with the
1173 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001174 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001175 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1176 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1177 * is needed for those platforms. See docs for this function in API level 22.
1178 *
Dan Egnor661f0132010-02-19 11:23:00 -08001179 * @param account The account to set an auth token for
1180 * @param authTokenType The type of the auth token, see {#getAuthToken}
1181 * @param authToken The auth token to add to the cache
1182 */
1183 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001184 if (account == null) throw new IllegalArgumentException("account is null");
1185 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001186 try {
1187 mService.setAuthToken(account, authTokenType, authToken);
1188 } catch (RemoteException e) {
1189 // won't ever happen
1190 throw new RuntimeException(e);
1191 }
1192 }
1193
1194 /**
1195 * This convenience helper synchronously gets an auth token with
1196 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1197 *
1198 * <p>This method may block while a network request completes, and must
1199 * never be made from the main thread.
1200 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001201 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1202 * USE_CREDENTIALS permission is needed for those platforms. See docs for
1203 * this function in API level 22.
1204 *
Dan Egnor661f0132010-02-19 11:23:00 -08001205 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001206 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001207 * @param notifyAuthFailure If true, display a notification and return null
1208 * if authentication fails; if false, prompt and wait for the user to
1209 * re-enter correct credentials before returning
1210 * @return An auth token of the specified type for this account, or null
1211 * if authentication fails or none can be fetched.
1212 * @throws AuthenticatorException if the authenticator failed to respond
1213 * @throws OperationCanceledException if the request was canceled for any
1214 * reason, including the user canceling a credential request
1215 * @throws java.io.IOException if the authenticator experienced an I/O problem
1216 * creating a new auth token, usually because of network trouble
1217 */
1218 public String blockingGetAuthToken(Account account, String authTokenType,
1219 boolean notifyAuthFailure)
1220 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001221 if (account == null) throw new IllegalArgumentException("account is null");
1222 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001223 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1224 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001225 if (bundle == null) {
1226 // This should never happen, but it does, occasionally. If it does return null to
1227 // signify that we were not able to get the authtoken.
1228 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1229 // returned
1230 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1231 + account + ", authTokenType " + authTokenType);
1232 return null;
1233 }
Dan Egnor661f0132010-02-19 11:23:00 -08001234 return bundle.getString(KEY_AUTHTOKEN);
1235 }
1236
1237 /**
1238 * Gets an auth token of the specified type for a particular account,
1239 * prompting the user for credentials if necessary. This method is
1240 * intended for applications running in the foreground where it makes
1241 * sense to ask the user directly for a password.
1242 *
1243 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001244 * type, then it is returned. Otherwise, if a saved password is
1245 * available, it is sent to the server to generate a new auth token.
1246 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001247 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001248 * <p>Some authenticators have auth token <em>types</em>, whose value
1249 * is authenticator-dependent. Some services use different token types to
1250 * access different functionality -- for example, Google uses different auth
1251 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001252 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001253 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001254 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001255 * this function in API level 22.
1256 *
Dan Egnor661f0132010-02-19 11:23:00 -08001257 * <p>This method may be called from any thread, but the returned
1258 * {@link AccountManagerFuture} must not be used on the main thread.
1259 *
Dan Egnor661f0132010-02-19 11:23:00 -08001260 * @param account The account to fetch an auth token for
1261 * @param authTokenType The auth token type, an authenticator-dependent
1262 * string token, must not be null
1263 * @param options Authenticator-specific options for the request,
1264 * may be null or empty
1265 * @param activity The {@link Activity} context to use for launching a new
1266 * authenticator-defined sub-Activity to prompt the user for a password
1267 * if necessary; used only to call startActivity(); must not be null.
1268 * @param callback Callback to invoke when the request completes,
1269 * null for no callback
1270 * @param handler {@link Handler} identifying the callback thread,
1271 * null for the main thread
1272 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1273 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001274 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001275 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1276 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1277 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001278 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001279 *
1280 * (Other authenticator-specific values may be returned.) If an auth token
1281 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1282 * <ul>
1283 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1284 * <li> {@link OperationCanceledException} if the operation is canceled for
1285 * any reason, incluidng the user canceling a credential request
1286 * <li> {@link IOException} if the authenticator experienced an I/O problem
1287 * creating a new auth token, usually because of network trouble
1288 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001289 * If the account is no longer present on the device, the return value is
1290 * authenticator-dependent. The caller should verify the validity of the
1291 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001292 */
1293 public AccountManagerFuture<Bundle> getAuthToken(
1294 final Account account, final String authTokenType, final Bundle options,
1295 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001296 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001297 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001298 final Bundle optionsIn = new Bundle();
1299 if (options != null) {
1300 optionsIn.putAll(options);
1301 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001302 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001303 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001304 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001305 public void doWork() throws RemoteException {
1306 mService.getAuthToken(mResponse, account, authTokenType,
1307 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001308 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001309 }
1310 }.start();
1311 }
1312
1313 /**
1314 * Gets an auth token of the specified type for a particular account,
1315 * optionally raising a notification if the user must enter credentials.
1316 * This method is intended for background tasks and services where the
1317 * user should not be immediately interrupted with a password prompt.
1318 *
1319 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001320 * type, then it is returned. Otherwise, if a saved password is
1321 * available, it is sent to the server to generate a new auth token.
1322 * Otherwise, an {@link Intent} is returned which, when started, will
1323 * prompt the user for a password. If the notifyAuthFailure parameter is
1324 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001325 * alerting the user that they need to enter a password at some point.
1326 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001327 * <p>In that case, you may need to wait until the user responds, which
1328 * could take hours or days or forever. When the user does respond and
1329 * supply a new password, the account manager will broadcast the
1330 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1331 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001332 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001333 * <p>If notifyAuthFailure is not set, it is the application's
1334 * responsibility to launch the returned Intent at some point.
1335 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001336 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001337 * <p>Some authenticators have auth token <em>types</em>, whose value
1338 * is authenticator-dependent. Some services use different token types to
1339 * access different functionality -- for example, Google uses different auth
1340 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001341 *
1342 * <p>This method may be called from any thread, but the returned
1343 * {@link AccountManagerFuture} must not be used on the main thread.
1344 *
Dan Egnor661f0132010-02-19 11:23:00 -08001345 * @param account The account to fetch an auth token for
1346 * @param authTokenType The auth token type, an authenticator-dependent
1347 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001348 * @param notifyAuthFailure True to add a notification to prompt the
1349 * user for a password if necessary, false to leave that to the caller
1350 * @param callback Callback to invoke when the request completes,
1351 * null for no callback
1352 * @param handler {@link Handler} identifying the callback thread,
1353 * null for the main thread
1354 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1355 * at least the following fields on success:
1356 * <ul>
1357 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1358 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1359 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1360 * </ul>
1361 *
1362 * (Other authenticator-specific values may be returned.) If the user
1363 * must enter credentials, the returned Bundle contains only
1364 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1365 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001366 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001367 * <ul>
1368 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1369 * <li> {@link OperationCanceledException} if the operation is canceled for
1370 * any reason, incluidng the user canceling a credential request
1371 * <li> {@link IOException} if the authenticator experienced an I/O problem
1372 * creating a new auth token, usually because of network trouble
1373 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001374 * If the account is no longer present on the device, the return value is
1375 * authenticator-dependent. The caller should verify the validity of the
1376 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001377 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1378 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001379 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001380 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001381 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001382 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001383 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001384 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001385 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001386 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001387 }
1388
1389 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001390 * Gets an auth token of the specified type for a particular account,
1391 * optionally raising a notification if the user must enter credentials.
1392 * This method is intended for background tasks and services where the
1393 * user should not be immediately interrupted with a password prompt.
1394 *
1395 * <p>If a previously generated auth token is cached for this account and
1396 * type, then it is returned. Otherwise, if a saved password is
1397 * available, it is sent to the server to generate a new auth token.
1398 * Otherwise, an {@link Intent} is returned which, when started, will
1399 * prompt the user for a password. If the notifyAuthFailure parameter is
1400 * set, a status bar notification is also created with the same Intent,
1401 * alerting the user that they need to enter a password at some point.
1402 *
1403 * <p>In that case, you may need to wait until the user responds, which
1404 * could take hours or days or forever. When the user does respond and
1405 * supply a new password, the account manager will broadcast the
1406 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1407 * use to try again.
1408 *
1409 * <p>If notifyAuthFailure is not set, it is the application's
1410 * responsibility to launch the returned Intent at some point.
1411 * Either way, the result from this call will not wait for user action.
1412 *
1413 * <p>Some authenticators have auth token <em>types</em>, whose value
1414 * is authenticator-dependent. Some services use different token types to
1415 * access different functionality -- for example, Google uses different auth
1416 * tokens to access Gmail and Google Calendar for the same account.
1417 *
1418 * <p>This method may be called from any thread, but the returned
1419 * {@link AccountManagerFuture} must not be used on the main thread.
1420 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001421 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001422 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001423 * this function in API level 22.
1424 *
Fred Quintanaad93a322011-09-08 13:21:01 -07001425 * @param account The account to fetch an auth token for
1426 * @param authTokenType The auth token type, an authenticator-dependent
1427 * string token, must not be null
1428 * @param options Authenticator-specific options for the request,
1429 * may be null or empty
1430 * @param notifyAuthFailure True to add a notification to prompt the
1431 * user for a password if necessary, false to leave that to the caller
1432 * @param callback Callback to invoke when the request completes,
1433 * null for no callback
1434 * @param handler {@link Handler} identifying the callback thread,
1435 * null for the main thread
1436 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1437 * at least the following fields on success:
1438 * <ul>
1439 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1440 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1441 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1442 * </ul>
1443 *
1444 * (Other authenticator-specific values may be returned.) If the user
1445 * must enter credentials, the returned Bundle contains only
1446 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1447 *
1448 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1449 * <ul>
1450 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1451 * <li> {@link OperationCanceledException} if the operation is canceled for
1452 * any reason, incluidng the user canceling a credential request
1453 * <li> {@link IOException} if the authenticator experienced an I/O problem
1454 * creating a new auth token, usually because of network trouble
1455 * </ul>
1456 * If the account is no longer present on the device, the return value is
1457 * authenticator-dependent. The caller should verify the validity of the
1458 * account before requesting an auth token.
1459 */
1460 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001461 final Account account, final String authTokenType, final Bundle options,
1462 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001463 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001464
Fred Quintanaad93a322011-09-08 13:21:01 -07001465 if (account == null) throw new IllegalArgumentException("account is null");
1466 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001467 final Bundle optionsIn = new Bundle();
1468 if (options != null) {
1469 optionsIn.putAll(options);
1470 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001471 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001472 return new AmsTask(null, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001473 @Override
Fred Quintanaad93a322011-09-08 13:21:01 -07001474 public void doWork() throws RemoteException {
1475 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001476 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001477 }
1478 }.start();
1479 }
1480
1481 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001482 * Asks the user to add an account of a specified type. The authenticator
1483 * for this account type processes this request with the appropriate user
1484 * interface. If the user does elect to create a new account, the account
1485 * name is returned.
1486 *
1487 * <p>This method may be called from any thread, but the returned
1488 * {@link AccountManagerFuture} must not be used on the main thread.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001489 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001490 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1491 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1492 * this function in API level 22.
Dan Egnor661f0132010-02-19 11:23:00 -08001493 *
Dan Egnor661f0132010-02-19 11:23:00 -08001494 * @param accountType The type of account to add; must not be null
1495 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1496 * this account will need to be able to generate, null for none
1497 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1498 * account must have, null for none
1499 * @param addAccountOptions Authenticator-specific options for the request,
1500 * may be null or empty
1501 * @param activity The {@link Activity} context to use for launching a new
1502 * authenticator-defined sub-Activity to prompt the user to create an
1503 * account; used only to call startActivity(); if null, the prompt
1504 * will not be launched directly, but the necessary {@link Intent}
1505 * will be returned to the caller instead
1506 * @param callback Callback to invoke when the request completes,
1507 * null for no callback
1508 * @param handler {@link Handler} identifying the callback thread,
1509 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001510 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001511 * these fields if activity was specified and an account was created:
1512 * <ul>
1513 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1514 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1515 * </ul>
1516 *
1517 * If no activity was specified, the returned Bundle contains only
1518 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001519 * actual account creation process. If an error occurred,
1520 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001521 * <ul>
1522 * <li> {@link AuthenticatorException} if no authenticator was registered for
1523 * this account type or the authenticator failed to respond
1524 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001525 * any reason, including the user canceling the creation process or adding accounts
1526 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001527 * <li> {@link IOException} if the authenticator experienced an I/O problem
1528 * creating a new account, usually because of network trouble
1529 * </ul>
1530 */
1531 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1532 final String authTokenType, final String[] requiredFeatures,
1533 final Bundle addAccountOptions,
1534 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001535 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001536 final Bundle optionsIn = new Bundle();
1537 if (addAccountOptions != null) {
1538 optionsIn.putAll(addAccountOptions);
1539 }
1540 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001541
Dan Egnor661f0132010-02-19 11:23:00 -08001542 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001543 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001544 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001545 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001546 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001547 }
1548 }.start();
1549 }
1550
1551 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001552 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1553 * @hide
1554 */
1555 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1556 final String authTokenType, final String[] requiredFeatures,
1557 final Bundle addAccountOptions, final Activity activity,
1558 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1559 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1560 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1561 final Bundle optionsIn = new Bundle();
1562 if (addAccountOptions != null) {
1563 optionsIn.putAll(addAccountOptions);
1564 }
1565 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1566
1567 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001568 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001569 public void doWork() throws RemoteException {
1570 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1571 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1572 }
1573 }.start();
1574 }
1575
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001576
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001577 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001578 * Adds shared accounts from a parent user to a secondary user. Adding the shared account
Amith Yamasani67df64b2012-12-14 12:09:36 -08001579 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1580 * are attempted to be copied to the target user from the primary via calls to the
1581 * authenticator.
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001582 * @param parentUser parent user
1583 * @param user target user
Amith Yamasani67df64b2012-12-14 12:09:36 -08001584 * @hide
1585 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001586 public void addSharedAccountsFromParentUser(UserHandle parentUser, UserHandle user) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001587 try {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001588 mService.addSharedAccountsFromParentUser(parentUser.getIdentifier(),
1589 user.getIdentifier());
Amith Yamasani67df64b2012-12-14 12:09:36 -08001590 } catch (RemoteException re) {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001591 throw new IllegalStateException(re);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001592 }
1593 }
1594
1595 /**
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001596 * Copies an account from one user to another user.
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001597 * @param account the account to copy
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001598 * @param fromUser the user to copy the account from
1599 * @param toUser the target user
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001600 * @param callback Callback to invoke when the request completes,
1601 * null for no callback
1602 * @param handler {@link Handler} identifying the callback thread,
1603 * null for the main thread
1604 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1605 * succeeded.
1606 * @hide
1607 */
1608 public AccountManagerFuture<Boolean> copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001609 final Account account, final UserHandle fromUser, final UserHandle toUser,
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001610 AccountManagerCallback<Boolean> callback, Handler handler) {
1611 if (account == null) throw new IllegalArgumentException("account is null");
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001612 if (toUser == null || fromUser == null) {
1613 throw new IllegalArgumentException("fromUser and toUser cannot be null");
1614 }
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001615
1616 return new Future2Task<Boolean>(handler, callback) {
1617 @Override
1618 public void doWork() throws RemoteException {
1619 mService.copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001620 mResponse, account, fromUser.getIdentifier(), toUser.getIdentifier());
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001621 }
1622 @Override
1623 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1624 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1625 throw new AuthenticatorException("no result in response");
1626 }
1627 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1628 }
1629 }.start();
1630 }
1631
1632 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001633 * @hide
1634 * Removes the shared account.
1635 * @param account the account to remove
1636 * @param user the user to remove the account from
1637 * @return
1638 */
1639 public boolean removeSharedAccount(final Account account, UserHandle user) {
1640 try {
1641 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1642 return val;
1643 } catch (RemoteException re) {
1644 // won't ever happen
1645 throw new RuntimeException(re);
1646 }
1647 }
1648
1649 /**
1650 * @hide
1651 * @param user
1652 * @return
1653 */
1654 public Account[] getSharedAccounts(UserHandle user) {
1655 try {
1656 return mService.getSharedAccountsAsUser(user.getIdentifier());
1657 } catch (RemoteException re) {
1658 // won't ever happen
1659 throw new RuntimeException(re);
1660 }
1661 }
1662
1663 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001664 * Confirms that the user knows the password for an account to make extra
1665 * sure they are the owner of the account. The user-entered password can
1666 * be supplied directly, otherwise the authenticator for this account type
1667 * prompts the user with the appropriate interface. This method is
1668 * intended for applications which want extra assurance; for example, the
1669 * phone lock screen uses this to let the user unlock the phone with an
1670 * account password if they forget the lock pattern.
1671 *
1672 * <p>If the user-entered password matches a saved password for this
1673 * account, the request is considered valid; otherwise the authenticator
1674 * verifies the password (usually by contacting the server).
1675 *
1676 * <p>This method may be called from any thread, but the returned
1677 * {@link AccountManagerFuture} must not be used on the main thread.
1678 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001679 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1680 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
1681 * for this function in API level 22.
1682 *
Dan Egnor661f0132010-02-19 11:23:00 -08001683 * @param account The account to confirm password knowledge for
1684 * @param options Authenticator-specific options for the request;
1685 * if the {@link #KEY_PASSWORD} string field is present, the
1686 * authenticator may use it directly rather than prompting the user;
1687 * may be null or empty
1688 * @param activity The {@link Activity} context to use for launching a new
1689 * authenticator-defined sub-Activity to prompt the user to enter a
1690 * password; used only to call startActivity(); if null, the prompt
1691 * will not be launched directly, but the necessary {@link Intent}
1692 * will be returned to the caller instead
1693 * @param callback Callback to invoke when the request completes,
1694 * null for no callback
1695 * @param handler {@link Handler} identifying the callback thread,
1696 * null for the main thread
1697 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1698 * with these fields if activity or password was supplied and
1699 * the account was successfully verified:
1700 * <ul>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001701 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001702 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1703 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1704 * </ul>
1705 *
1706 * If no activity or password was specified, the returned Bundle contains
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001707 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1708 * password prompt.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001709 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001710 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001711 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001712 * credential was validated/created.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001713 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001714 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001715 * <ul>
1716 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1717 * <li> {@link OperationCanceledException} if the operation was canceled for
1718 * any reason, including the user canceling the password prompt
1719 * <li> {@link IOException} if the authenticator experienced an I/O problem
1720 * verifying the password, usually because of network trouble
1721 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001722 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001723 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1724 final Bundle options,
1725 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001726 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001727 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001728 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1729 Process.myUserHandle());
1730 }
1731
1732 /**
1733 * @hide
1734 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1735 * but for the specified user.
1736 */
1737 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1738 final Bundle options,
1739 final Activity activity,
1740 final AccountManagerCallback<Bundle> callback,
1741 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001742 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001743 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001744 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001745 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001746 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001747 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1748 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001749 }
Fred Quintana33269202009-04-20 16:05:10 -07001750 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001751 }
1752
Fred Quintana756b7352009-10-21 13:43:10 -07001753 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001754 * Asks the user to enter a new password for an account, updating the
1755 * saved credentials for the account. Normally this happens automatically
1756 * when the server rejects credentials during an auth token fetch, but this
1757 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001758 *
Dan Egnor661f0132010-02-19 11:23:00 -08001759 * <p>This method may be called from any thread, but the returned
1760 * {@link AccountManagerFuture} must not be used on the main thread.
1761 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001762 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1763 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1764 * this function in API level 22.
1765 *
Dan Egnor661f0132010-02-19 11:23:00 -08001766 * @param account The account to update credentials for
1767 * @param authTokenType The credentials entered must allow an auth token
1768 * of this type to be created (but no actual auth token is returned);
1769 * may be null
1770 * @param options Authenticator-specific options for the request;
1771 * may be null or empty
1772 * @param activity The {@link Activity} context to use for launching a new
1773 * authenticator-defined sub-Activity to prompt the user to enter a
1774 * password; used only to call startActivity(); if null, the prompt
1775 * will not be launched directly, but the necessary {@link Intent}
1776 * will be returned to the caller instead
1777 * @param callback Callback to invoke when the request completes,
1778 * null for no callback
1779 * @param handler {@link Handler} identifying the callback thread,
1780 * null for the main thread
1781 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1782 * with these fields if an activity was supplied and the account
1783 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001784 * <ul>
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001785 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
Dan Egnor661f0132010-02-19 11:23:00 -08001786 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001787 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001788 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001789 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08001790 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001791 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07001792 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001793 * <ul>
1794 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1795 * <li> {@link OperationCanceledException} if the operation was canceled for
1796 * any reason, including the user canceling the password prompt
1797 * <li> {@link IOException} if the authenticator experienced an I/O problem
1798 * verifying the password, usually because of network trouble
1799 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001800 */
1801 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1802 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001803 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001804 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001805 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001806 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001807 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001808 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001809 public void doWork() throws RemoteException {
1810 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001811 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001812 }
Fred Quintana33269202009-04-20 16:05:10 -07001813 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001814 }
1815
Fred Quintana756b7352009-10-21 13:43:10 -07001816 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001817 * Offers the user an opportunity to change an authenticator's settings.
1818 * These properties are for the authenticator in general, not a particular
1819 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001820 *
Dan Egnor661f0132010-02-19 11:23:00 -08001821 * <p>This method may be called from any thread, but the returned
1822 * {@link AccountManagerFuture} must not be used on the main thread.
1823 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001824 * <p>This method requires the caller to have the same signature as the
1825 * authenticator associated with the specified account type.
Dan Egnor661f0132010-02-19 11:23:00 -08001826 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001827 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1828 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
1829 * for this function in API level 22.
1830 *
Dan Egnor661f0132010-02-19 11:23:00 -08001831 * @param accountType The account type associated with the authenticator
1832 * to adjust
1833 * @param activity The {@link Activity} context to use for launching a new
1834 * authenticator-defined sub-Activity to adjust authenticator settings;
1835 * used only to call startActivity(); if null, the settings dialog will
1836 * not be launched directly, but the necessary {@link Intent} will be
1837 * returned to the caller instead
1838 * @param callback Callback to invoke when the request completes,
1839 * null for no callback
1840 * @param handler {@link Handler} identifying the callback thread,
1841 * null for the main thread
1842 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1843 * which is empty if properties were edited successfully, or
1844 * if no activity was specified, contains only {@link #KEY_INTENT}
1845 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001846 * If an error occurred, {@link AccountManagerFuture#getResult()}
1847 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001848 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001849 * <li> {@link AuthenticatorException} if no authenticator was registered for
1850 * this account type or the authenticator failed to respond
1851 * <li> {@link OperationCanceledException} if the operation was canceled for
1852 * any reason, including the user canceling the settings dialog
1853 * <li> {@link IOException} if the authenticator experienced an I/O problem
1854 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001855 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001856 */
1857 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1858 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001859 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001860 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001861 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001862 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001863 public void doWork() throws RemoteException {
1864 mService.editProperties(mResponse, accountType, activity != null);
1865 }
Fred Quintana33269202009-04-20 16:05:10 -07001866 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001867 }
1868
Amith Yamasani12747872015-12-07 14:19:49 -08001869 /**
1870 * @hide
1871 * Checks if the given account exists on any of the users on the device.
1872 * Only the system process can call this method.
1873 *
1874 * @param account The account to check for existence.
1875 * @return whether any user has this account
1876 */
1877 public boolean someUserHasAccount(@NonNull final Account account) {
1878 try {
1879 return mService.someUserHasAccount(account);
1880 } catch (RemoteException re) {
1881 throw new RuntimeException(re);
1882 }
1883 }
1884
Fred Quintanaa698f422009-04-08 19:14:54 -07001885 private void ensureNotOnMainThread() {
1886 final Looper looper = Looper.myLooper();
1887 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001888 final IllegalStateException exception = new IllegalStateException(
1889 "calling this from your main thread can lead to deadlock");
1890 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1891 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001892 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1893 throw exception;
1894 }
Fred Quintana60307342009-03-24 22:48:12 -07001895 }
1896 }
1897
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001898 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1899 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001900 handler = handler == null ? mMainHandler : handler;
1901 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001902 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001903 public void run() {
1904 callback.run(future);
1905 }
1906 });
1907 }
Fred Quintana60307342009-03-24 22:48:12 -07001908
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001909 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001910 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001911 final Account[] accountsCopy = new Account[accounts.length];
1912 // send a copy to make sure that one doesn't
1913 // change what another sees
1914 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1915 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001916 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001917 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07001918 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001919 try {
1920 listener.onAccountsUpdated(accountsCopy);
1921 } catch (SQLException e) {
1922 // Better luck next time. If the problem was disk-full,
1923 // the STORAGE_OK intent will re-trigger the update.
1924 Log.e(TAG, "Can't update accounts", e);
1925 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001926 }
1927 });
1928 }
1929
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001930 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001931 final IAccountManagerResponse mResponse;
1932 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001933 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001934 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001935 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001936 super(new Callable<Bundle>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001937 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001938 public Bundle call() throws Exception {
1939 throw new IllegalStateException("this should never be called");
1940 }
1941 });
1942
1943 mHandler = handler;
1944 mCallback = callback;
1945 mActivity = activity;
1946 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001947 }
1948
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001949 public final AccountManagerFuture<Bundle> start() {
1950 try {
1951 doWork();
1952 } catch (RemoteException e) {
1953 setException(e);
1954 }
Fred Quintana33269202009-04-20 16:05:10 -07001955 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001956 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001957
Sandra Kwan0b84b452016-01-20 15:25:42 -08001958 @Override
Fred Quintana96580e02010-03-04 13:42:42 -08001959 protected void set(Bundle bundle) {
1960 // TODO: somehow a null is being set as the result of the Future. Log this
1961 // case to help debug where this is occurring. When this bug is fixed this
1962 // condition statement should be removed.
1963 if (bundle == null) {
1964 Log.e(TAG, "the bundle must not be null", new Exception());
1965 }
1966 super.set(bundle);
1967 }
1968
Fred Quintanaa698f422009-04-08 19:14:54 -07001969 public abstract void doWork() throws RemoteException;
1970
1971 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1972 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001973 if (!isDone()) {
1974 ensureNotOnMainThread();
1975 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001976 try {
1977 if (timeout == null) {
1978 return get();
1979 } else {
1980 return get(timeout, unit);
1981 }
1982 } catch (CancellationException e) {
1983 throw new OperationCanceledException();
1984 } catch (TimeoutException e) {
1985 // fall through and cancel
1986 } catch (InterruptedException e) {
1987 // fall through and cancel
1988 } catch (ExecutionException e) {
1989 final Throwable cause = e.getCause();
1990 if (cause instanceof IOException) {
1991 throw (IOException) cause;
1992 } else if (cause instanceof UnsupportedOperationException) {
1993 throw new AuthenticatorException(cause);
1994 } else if (cause instanceof AuthenticatorException) {
1995 throw (AuthenticatorException) cause;
1996 } else if (cause instanceof RuntimeException) {
1997 throw (RuntimeException) cause;
1998 } else if (cause instanceof Error) {
1999 throw (Error) cause;
2000 } else {
2001 throw new IllegalStateException(cause);
2002 }
2003 } finally {
2004 cancel(true /* interrupt if running */);
2005 }
2006 throw new OperationCanceledException();
2007 }
2008
Sandra Kwan0b84b452016-01-20 15:25:42 -08002009 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002010 public Bundle getResult()
2011 throws OperationCanceledException, IOException, AuthenticatorException {
2012 return internalGetResult(null, null);
2013 }
2014
Sandra Kwan0b84b452016-01-20 15:25:42 -08002015 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002016 public Bundle getResult(long timeout, TimeUnit unit)
2017 throws OperationCanceledException, IOException, AuthenticatorException {
2018 return internalGetResult(timeout, unit);
2019 }
2020
Sandra Kwan0b84b452016-01-20 15:25:42 -08002021 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002022 protected void done() {
2023 if (mCallback != null) {
2024 postToHandler(mHandler, mCallback, this);
2025 }
2026 }
2027
2028 /** Handles the responses from the AccountManager */
2029 private class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002030 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002031 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07002032 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07002033 if (intent != null && mActivity != null) {
2034 // since the user provided an Activity we will silently start intents
2035 // that we see
2036 mActivity.startActivity(intent);
2037 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002038 } else if (bundle.getBoolean("retry")) {
2039 try {
2040 doWork();
2041 } catch (RemoteException e) {
2042 // this will only happen if the system process is dead, which means
2043 // we will be dying ourselves
2044 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002045 } else {
2046 set(bundle);
2047 }
2048 }
2049
Sandra Kwan0b84b452016-01-20 15:25:42 -08002050 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002051 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002052 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2053 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2054 // the authenticator indicated that this request was canceled or we were
2055 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07002056 cancel(true /* mayInterruptIfRunning */);
2057 return;
2058 }
2059 setException(convertErrorToException(code, message));
2060 }
2061 }
2062
Fred Quintana60307342009-03-24 22:48:12 -07002063 }
2064
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002065 private abstract class BaseFutureTask<T> extends FutureTask<T> {
2066 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002067 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002068
2069 public BaseFutureTask(Handler handler) {
2070 super(new Callable<T>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002071 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002072 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07002073 throw new IllegalStateException("this should never be called");
2074 }
2075 });
Fred Quintanaa698f422009-04-08 19:14:54 -07002076 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002077 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07002078 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002079
2080 public abstract void doWork() throws RemoteException;
2081
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002082 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07002083
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002084 protected void postRunnableToHandler(Runnable runnable) {
2085 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
2086 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07002087 }
2088
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002089 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002090 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002091 doWork();
2092 } catch (RemoteException e) {
2093 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07002094 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002095 }
2096
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002097 protected class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002098 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002099 public void onResult(Bundle bundle) {
2100 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002101 T result = bundleToResult(bundle);
2102 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002103 return;
2104 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002105 set(result);
2106 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002107 } catch (ClassCastException e) {
2108 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002109 } catch (AuthenticatorException e) {
2110 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07002111 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002112 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07002113 }
2114
Sandra Kwan0b84b452016-01-20 15:25:42 -08002115 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002116 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002117 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2118 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2119 // the authenticator indicated that this request was canceled or we were
2120 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07002121 cancel(true /* mayInterruptIfRunning */);
2122 return;
2123 }
2124 setException(convertErrorToException(code, message));
2125 }
2126 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002127 }
2128
2129 private abstract class Future2Task<T>
2130 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
2131 final AccountManagerCallback<T> mCallback;
2132 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
2133 super(handler);
2134 mCallback = callback;
2135 }
2136
Sandra Kwan0b84b452016-01-20 15:25:42 -08002137 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002138 protected void done() {
2139 if (mCallback != null) {
2140 postRunnableToHandler(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002141 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002142 public void run() {
2143 mCallback.run(Future2Task.this);
2144 }
2145 });
2146 }
2147 }
2148
2149 public Future2Task<T> start() {
2150 startTask();
2151 return this;
2152 }
2153
2154 private T internalGetResult(Long timeout, TimeUnit unit)
2155 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08002156 if (!isDone()) {
2157 ensureNotOnMainThread();
2158 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002159 try {
2160 if (timeout == null) {
2161 return get();
2162 } else {
2163 return get(timeout, unit);
2164 }
2165 } catch (InterruptedException e) {
2166 // fall through and cancel
2167 } catch (TimeoutException e) {
2168 // fall through and cancel
2169 } catch (CancellationException e) {
2170 // fall through and cancel
2171 } catch (ExecutionException e) {
2172 final Throwable cause = e.getCause();
2173 if (cause instanceof IOException) {
2174 throw (IOException) cause;
2175 } else if (cause instanceof UnsupportedOperationException) {
2176 throw new AuthenticatorException(cause);
2177 } else if (cause instanceof AuthenticatorException) {
2178 throw (AuthenticatorException) cause;
2179 } else if (cause instanceof RuntimeException) {
2180 throw (RuntimeException) cause;
2181 } else if (cause instanceof Error) {
2182 throw (Error) cause;
2183 } else {
2184 throw new IllegalStateException(cause);
2185 }
2186 } finally {
2187 cancel(true /* interrupt if running */);
2188 }
2189 throw new OperationCanceledException();
2190 }
2191
Sandra Kwan0b84b452016-01-20 15:25:42 -08002192 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002193 public T getResult()
2194 throws OperationCanceledException, IOException, AuthenticatorException {
2195 return internalGetResult(null, null);
2196 }
2197
Sandra Kwan0b84b452016-01-20 15:25:42 -08002198 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002199 public T getResult(long timeout, TimeUnit unit)
2200 throws OperationCanceledException, IOException, AuthenticatorException {
2201 return internalGetResult(timeout, unit);
2202 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002203
Fred Quintana60307342009-03-24 22:48:12 -07002204 }
2205
Fred Quintanaa698f422009-04-08 19:14:54 -07002206 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002207 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002208 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002209 }
Fred Quintana60307342009-03-24 22:48:12 -07002210
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002211 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002212 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002213 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002214
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002215 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002216 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002217 }
2218
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002219 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002220 return new IllegalArgumentException(message);
2221 }
2222
2223 return new AuthenticatorException(message);
2224 }
2225
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002226 private class GetAuthTokenByTypeAndFeaturesTask
2227 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002228 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2229 final String[] features, Activity activityForPrompting,
2230 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002231 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002232 super(activityForPrompting, handler, callback);
2233 if (accountType == null) throw new IllegalArgumentException("account type is null");
2234 mAccountType = accountType;
2235 mAuthTokenType = authTokenType;
2236 mFeatures = features;
2237 mAddAccountOptions = addAccountOptions;
2238 mLoginOptions = loginOptions;
2239 mMyCallback = this;
2240 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002241 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002242 final String mAccountType;
2243 final String mAuthTokenType;
2244 final String[] mFeatures;
2245 final Bundle mAddAccountOptions;
2246 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002247 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002248 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002249
Sandra Kwan0b84b452016-01-20 15:25:42 -08002250 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002251 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002252 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2253 new AccountManagerCallback<Account[]>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002254 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002255 public void run(AccountManagerFuture<Account[]> future) {
2256 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07002257 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002258 accounts = future.getResult();
2259 } catch (OperationCanceledException e) {
2260 setException(e);
2261 return;
2262 } catch (IOException e) {
2263 setException(e);
2264 return;
2265 } catch (AuthenticatorException e) {
2266 setException(e);
2267 return;
Fred Quintana33269202009-04-20 16:05:10 -07002268 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002269
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002270 mNumAccounts = accounts.length;
2271
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002272 if (accounts.length == 0) {
2273 if (mActivity != null) {
2274 // no accounts, add one now. pretend that the user directly
2275 // made this request
2276 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2277 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2278 } else {
2279 // send result since we can't prompt to add an account
2280 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002281 result.putString(KEY_ACCOUNT_NAME, null);
2282 result.putString(KEY_ACCOUNT_TYPE, null);
2283 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002284 try {
2285 mResponse.onResult(result);
2286 } catch (RemoteException e) {
2287 // this will never happen
2288 }
2289 // we are done
2290 }
2291 } else if (accounts.length == 1) {
2292 // have a single account, return an authtoken for it
2293 if (mActivity == null) {
2294 mFuture = getAuthToken(accounts[0], mAuthTokenType,
2295 false /* notifyAuthFailure */, mMyCallback, mHandler);
2296 } else {
2297 mFuture = getAuthToken(accounts[0],
2298 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002299 mActivity, mMyCallback, mHandler);
2300 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002301 } else {
2302 if (mActivity != null) {
2303 IAccountManagerResponse chooseResponse =
2304 new IAccountManagerResponse.Stub() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002305 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002306 public void onResult(Bundle value) throws RemoteException {
2307 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002308 value.getString(KEY_ACCOUNT_NAME),
2309 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002310 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2311 mActivity, mMyCallback, mHandler);
2312 }
Fred Quintana33269202009-04-20 16:05:10 -07002313
Sandra Kwan0b84b452016-01-20 15:25:42 -08002314 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002315 public void onError(int errorCode, String errorMessage)
2316 throws RemoteException {
2317 mResponse.onError(errorCode, errorMessage);
2318 }
2319 };
2320 // have many accounts, launch the chooser
2321 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002322 ComponentName componentName = ComponentName.unflattenFromString(
2323 Resources.getSystem().getString(
2324 R.string.config_chooseAccountActivity));
2325 intent.setClassName(componentName.getPackageName(),
2326 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002327 intent.putExtra(KEY_ACCOUNTS, accounts);
2328 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002329 new AccountManagerResponse(chooseResponse));
2330 mActivity.startActivity(intent);
2331 // the result will arrive via the IAccountManagerResponse
2332 } else {
2333 // send result since we can't prompt to select an account
2334 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002335 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002336 try {
2337 mResponse.onResult(result);
2338 } catch (RemoteException e) {
2339 // this will never happen
2340 }
2341 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07002342 }
Fred Quintana33269202009-04-20 16:05:10 -07002343 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002344 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002345 }
2346
Sandra Kwan0b84b452016-01-20 15:25:42 -08002347 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002348 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002349 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002350 final Bundle result = future.getResult();
2351 if (mNumAccounts == 0) {
2352 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2353 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2354 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2355 setException(new AuthenticatorException("account not in result"));
2356 return;
2357 }
2358 final Account account = new Account(accountName, accountType);
2359 mNumAccounts = 1;
2360 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2361 mMyCallback, mHandler);
2362 return;
2363 }
2364 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002365 } catch (OperationCanceledException e) {
2366 cancel(true /* mayInterruptIfRUnning */);
2367 } catch (IOException e) {
2368 setException(e);
2369 } catch (AuthenticatorException e) {
2370 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002371 }
2372 }
2373 }
2374
Fred Quintana756b7352009-10-21 13:43:10 -07002375 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002376 * This convenience helper combines the functionality of
2377 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2378 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002379 *
Dan Egnor661f0132010-02-19 11:23:00 -08002380 * <p>This method gets a list of the accounts matching the
2381 * specified type and feature set; if there is exactly one, it is
2382 * used; if there are more than one, the user is prompted to pick one;
2383 * if there are none, the user is prompted to add one. Finally,
2384 * an auth token is acquired for the chosen account.
2385 *
2386 * <p>This method may be called from any thread, but the returned
2387 * {@link AccountManagerFuture} must not be used on the main thread.
2388 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002389 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
2390 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
2391 * this function in API level 22.
2392 *
Dan Egnor661f0132010-02-19 11:23:00 -08002393 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08002394 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08002395 * @param authTokenType The desired auth token type
2396 * (see {@link #getAuthToken}), must not be null
2397 * @param features Required features for the account
2398 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2399 * @param activity The {@link Activity} context to use for launching new
2400 * sub-Activities to prompt to add an account, select an account,
2401 * and/or enter a password, as necessary; used only to call
2402 * startActivity(); should not be null
2403 * @param addAccountOptions Authenticator-specific options to use for
2404 * adding new accounts; may be null or empty
2405 * @param getAuthTokenOptions Authenticator-specific options to use for
2406 * getting auth tokens; may be null or empty
2407 * @param callback Callback to invoke when the request completes,
2408 * null for no callback
2409 * @param handler {@link Handler} identifying the callback thread,
2410 * null for the main thread
2411 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2412 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07002413 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002414 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2415 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2416 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07002417 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002418 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07002419 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002420 * <ul>
2421 * <li> {@link AuthenticatorException} if no authenticator was registered for
2422 * this account type or the authenticator failed to respond
2423 * <li> {@link OperationCanceledException} if the operation was canceled for
2424 * any reason, including the user canceling any operation
2425 * <li> {@link IOException} if the authenticator experienced an I/O problem
2426 * updating settings, usually because of network trouble
2427 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002428 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002429 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002430 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002431 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07002432 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002433 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002434 if (accountType == null) throw new IllegalArgumentException("account type is null");
2435 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002436 final GetAuthTokenByTypeAndFeaturesTask task =
2437 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002438 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002439 task.start();
2440 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002441 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002442
Fred Quintana1121bb52011-09-14 23:19:35 -07002443 /**
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002444 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
2445 * String, String[], Bundle)}.
2446 *
Fred Quintana1121bb52011-09-14 23:19:35 -07002447 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2448 * accounts.
2449 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002450 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002451 * <p>
2452 * On success the activity returns a Bundle with the account name and type specified using
2453 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2454 * <p>
2455 * The most common case is to call this with one account type, e.g.:
2456 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002457 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002458 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002459 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2460 * selected one, according to the caller's definition of selected.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002461 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
Fred Quintana1121bb52011-09-14 23:19:35 -07002462 * shown. If not specified then this field will not limit the displayed accounts.
2463 * @param allowableAccountTypes an optional string array of account types. These are used
2464 * 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 -07002465 * when adding an account. If not specified then this field will not limit the displayed
2466 * account types when adding an account.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002467 * @param alwaysPromptForAccount boolean that is ignored.
Fred Quintanad88324d2011-09-19 11:43:05 -07002468 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002469 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002470 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2471 * authTokenType parameter
2472 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2473 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002474 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002475 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002476 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002477 */
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002478 @Deprecated
2479 static public Intent newChooseAccountIntent(
2480 Account selectedAccount,
Baligh Uddinf2d248d2015-07-10 03:01:47 +00002481 ArrayList<Account> allowableAccounts,
Fred Quintana1121bb52011-09-14 23:19:35 -07002482 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002483 boolean alwaysPromptForAccount,
2484 String descriptionOverrideText,
2485 String addAccountAuthTokenType,
2486 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002487 Bundle addAccountOptions) {
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002488 return newChooseAccountIntent(
2489 selectedAccount,
2490 allowableAccounts,
2491 allowableAccountTypes,
2492 descriptionOverrideText,
2493 addAccountAuthTokenType,
2494 addAccountRequiredFeatures,
2495 addAccountOptions);
2496 }
2497
2498 /**
2499 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2500 * accounts.
2501 * The caller will then typically start the activity by calling
2502 * <code>startActivityForResult(intent, ...);</code>.
2503 * <p>
2504 * On success the activity returns a Bundle with the account name and type specified using
2505 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2506 * <p>
2507 * The most common case is to call this with one account type, e.g.:
2508 * <p>
2509 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null,
2510 * null);</pre>
2511 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2512 * selected one, according to the caller's definition of selected.
2513 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
2514 * shown. If not specified then this field will not limit the displayed accounts.
2515 * @param allowableAccountTypes an optional string array of account types. These are used
2516 * both to filter the shown accounts and to filter the list of account types that are shown
2517 * when adding an account. If not specified then this field will not limit the displayed
2518 * account types when adding an account.
2519 * @param descriptionOverrideText if non-null this string is used as the description in the
2520 * accounts chooser screen rather than the default
2521 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2522 * authTokenType parameter
2523 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2524 * requiredFeatures parameter
2525 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2526 * parameter
2527 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2528 */
2529 static public Intent newChooseAccountIntent(
2530 Account selectedAccount,
2531 List<Account> allowableAccounts,
2532 String[] allowableAccountTypes,
2533 String descriptionOverrideText,
2534 String addAccountAuthTokenType,
2535 String[] addAccountRequiredFeatures,
2536 Bundle addAccountOptions) {
Fred Quintana1121bb52011-09-14 23:19:35 -07002537 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002538 ComponentName componentName = ComponentName.unflattenFromString(
2539 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2540 intent.setClassName(componentName.getPackageName(),
2541 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002542 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
Craig Lafayette3c9c71d2015-07-14 10:48:46 -04002543 allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts));
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002544 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2545 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002546 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2547 addAccountOptions);
2548 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002549 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2550 descriptionOverrideText);
2551 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2552 addAccountAuthTokenType);
2553 intent.putExtra(
2554 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2555 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002556 return intent;
2557 }
2558
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002559 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002560 Maps.newHashMap();
2561
Fred Quintanad9d2f112009-04-23 13:36:27 -07002562 /**
2563 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2564 * so that it can read the updated list of accounts and send them to the listener
2565 * in mAccountsUpdatedListeners.
2566 */
2567 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002568 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002569 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002570 final Account[] accounts = getAccounts();
2571 // send the result to the listeners
2572 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002573 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002574 mAccountsUpdatedListeners.entrySet()) {
2575 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002576 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002577 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002578 }
2579 };
2580
2581 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002582 * Adds an {@link OnAccountsUpdateListener} to this instance of the
2583 * {@link AccountManager}. This listener will be notified whenever the
2584 * list of accounts on the device changes.
2585 *
2586 * <p>As long as this listener is present, the AccountManager instance
2587 * will not be garbage-collected, and neither will the {@link Context}
2588 * used to retrieve it, which may be a large Activity instance. To avoid
2589 * memory leaks, you must remove this listener before then. Normally
2590 * listeners are added in an Activity or Service's {@link Activity#onCreate}
2591 * and removed in {@link Activity#onDestroy}.
2592 *
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002593 * <p>The listener will only be informed of accounts that would be returned
2594 * to the caller via {@link #getAccounts()}. Typically this means that to
2595 * get any accounts, the caller will need to be grated the GET_ACCOUNTS
2596 * permission.
Dan Egnor661f0132010-02-19 11:23:00 -08002597 *
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002598 * <p>It is safe to call this method from the main thread.
Ian Pedowitz845d14d2015-08-04 07:47:37 -07002599 *
Dan Egnor661f0132010-02-19 11:23:00 -08002600 * @param listener The listener to send notifications to
2601 * @param handler {@link Handler} identifying the thread to use
2602 * for notifications, null for the main thread
2603 * @param updateImmediately If true, the listener will be invoked
2604 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002605 * @throws IllegalArgumentException if listener is null
2606 * @throws IllegalStateException if listener was already added
2607 */
Tor Norbye80b530a2015-04-23 16:36:09 -07002608 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002609 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002610 Handler handler, boolean updateImmediately) {
2611 if (listener == null) {
2612 throw new IllegalArgumentException("the listener is null");
2613 }
2614 synchronized (mAccountsUpdatedListeners) {
2615 if (mAccountsUpdatedListeners.containsKey(listener)) {
2616 throw new IllegalStateException("this listener is already added");
2617 }
2618 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2619
2620 mAccountsUpdatedListeners.put(listener, handler);
2621
2622 if (wasEmpty) {
2623 // Register a broadcast receiver to monitor account changes
2624 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002625 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002626 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002627 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002628 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2629 }
2630 }
2631
2632 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002633 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002634 }
2635 }
2636
2637 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002638 * Removes an {@link OnAccountsUpdateListener} previously registered with
2639 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2640 * receive notifications of account changes.
2641 *
2642 * <p>It is safe to call this method from the main thread.
2643 *
2644 * <p>No permission is required to call this method.
2645 *
2646 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002647 * @throws IllegalArgumentException if listener is null
2648 * @throws IllegalStateException if listener was not already added
2649 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002650 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002651 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002652 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002653 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002654 Log.e(TAG, "Listener was not previously added");
2655 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002656 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002657 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002658 if (mAccountsUpdatedListeners.isEmpty()) {
2659 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2660 }
2661 }
2662 }
Sandra Kwan78812282015-11-04 11:19:47 -08002663
2664 /**
2665 * Asks the user to authenticate with an account of a specified type. The
2666 * authenticator for this account type processes this request with the
2667 * appropriate user interface. If the user does elect to authenticate with a
2668 * new account, a bundle of session data for installing the account later is
2669 * returned with optional account password and account status token.
2670 * <p>
2671 * This method may be called from any thread, but the returned
2672 * {@link AccountManagerFuture} must not be used on the main thread.
2673 * <p>
2674 * <p>
2675 * <b>NOTE:</b> The account will not be installed to the device by calling
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002676 * this api alone. #finishSession should be called after this to install the
2677 * account on device.
Sandra Kwan78812282015-11-04 11:19:47 -08002678 *
2679 * @param accountType The type of account to add; must not be null
2680 * @param authTokenType The type of auth token (see {@link #getAuthToken})
2681 * this account will need to be able to generate, null for none
2682 * @param requiredFeatures The features (see {@link #hasFeatures}) this
2683 * account must have, null for none
2684 * @param options Authenticator-specific options for the request, may be
2685 * null or empty
2686 * @param activity The {@link Activity} context to use for launching a new
2687 * authenticator-defined sub-Activity to prompt the user to
2688 * create an account; used only to call startActivity(); if null,
2689 * the prompt will not be launched directly, but the necessary
2690 * {@link Intent} will be returned to the caller instead
2691 * @param callback Callback to invoke when the request completes, null for
2692 * no callback
2693 * @param handler {@link Handler} identifying the callback thread, null for
2694 * the main thread
2695 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2696 * these fields if activity was specified and user was authenticated
2697 * with an account:
2698 * <ul>
2699 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
2700 * adding the the to the device later.
2701 * <li>{@link #KEY_PASSWORD} - optional, the password or password
2702 * hash of the account.
2703 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
2704 * status of the account
2705 * </ul>
2706 * If no activity was specified, the returned Bundle contains only
2707 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2708 * actual account creation process. If authenticator doesn't support
2709 * this method, the returned Bundle contains only
2710 * {@link #KEY_ACCOUNT_SESSION_BUNDLE} with encrypted
2711 * {@code options} needed to add account later. If an error
2712 * occurred, {@link AccountManagerFuture#getResult()} throws:
2713 * <ul>
2714 * <li>{@link AuthenticatorException} if no authenticator was
2715 * registered for this account type or the authenticator failed to
2716 * respond
2717 * <li>{@link OperationCanceledException} if the operation was
2718 * canceled for any reason, including the user canceling the
2719 * creation process or adding accounts (of this type) has been
2720 * disabled by policy
2721 * <li>{@link IOException} if the authenticator experienced an I/O
2722 * problem creating a new account, usually because of network
2723 * trouble
2724 * </ul>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002725 * @see #finishSession
Sandra Kwana578d112015-12-16 16:01:43 -08002726 * @hide
Sandra Kwan78812282015-11-04 11:19:47 -08002727 */
Sandra Kwana578d112015-12-16 16:01:43 -08002728 @SystemApi
Sandra Kwane68c37e2015-11-12 17:11:49 -08002729 public AccountManagerFuture<Bundle> startAddAccountSession(
2730 final String accountType,
2731 final String authTokenType,
2732 final String[] requiredFeatures,
2733 final Bundle options,
2734 final Activity activity,
2735 AccountManagerCallback<Bundle> callback,
2736 Handler handler) {
Sandra Kwan78812282015-11-04 11:19:47 -08002737 if (accountType == null) throw new IllegalArgumentException("accountType is null");
2738 final Bundle optionsIn = new Bundle();
2739 if (options != null) {
2740 optionsIn.putAll(options);
2741 }
2742 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
2743
2744 return new AmsTask(activity, handler, callback) {
2745 @Override
2746 public void doWork() throws RemoteException {
Sandra Kwane68c37e2015-11-12 17:11:49 -08002747 mService.startAddAccountSession(
2748 mResponse,
2749 accountType,
2750 authTokenType,
2751 requiredFeatures,
2752 activity != null,
2753 optionsIn);
2754 }
2755 }.start();
2756 }
2757
2758 /**
2759 * Asks the user to enter a new password for an account but not updating the
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002760 * saved credentials for the account until {@link #finishSession} is called.
Sandra Kwane68c37e2015-11-12 17:11:49 -08002761 * <p>
2762 * This method may be called from any thread, but the returned
2763 * {@link AccountManagerFuture} must not be used on the main thread.
2764 * <p>
2765 * <b>NOTE:</b> The saved credentials for the account alone will not be
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002766 * updated by calling this API alone. #finishSession should be called after
2767 * this to update local credentials
Sandra Kwane68c37e2015-11-12 17:11:49 -08002768 *
2769 * @param account The account to update credentials for
2770 * @param authTokenType The credentials entered must allow an auth token of
2771 * this type to be created (but no actual auth token is
2772 * returned); may be null
2773 * @param options Authenticator-specific options for the request; may be
2774 * null or empty
2775 * @param activity The {@link Activity} context to use for launching a new
2776 * authenticator-defined sub-Activity to prompt the user to enter
2777 * a password; used only to call startActivity(); if null, the
2778 * prompt will not be launched directly, but the necessary
2779 * {@link Intent} will be returned to the caller instead
2780 * @param callback Callback to invoke when the request completes, null for
2781 * no callback
2782 * @param handler {@link Handler} identifying the callback thread, null for
2783 * the main thread
2784 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2785 * these fields if an activity was supplied and user was
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002786 * successfully re-authenticated to the account:
Sandra Kwane68c37e2015-11-12 17:11:49 -08002787 * <ul>
2788 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
2789 * updating the local credentials on device later.
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002790 * <li>{@link #KEY_PASSWORD} - optional, the password or password
2791 * hash of the account
2792 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
2793 * status of the account
Sandra Kwane68c37e2015-11-12 17:11:49 -08002794 * </ul>
2795 * If no activity was specified, the returned Bundle contains
2796 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2797 * password prompt. If an error occurred,
2798 * {@link AccountManagerFuture#getResult()} throws:
2799 * <ul>
2800 * <li>{@link AuthenticatorException} if the authenticator failed to
2801 * respond
2802 * <li>{@link OperationCanceledException} if the operation was
2803 * canceled for any reason, including the user canceling the
2804 * password prompt
2805 * <li>{@link IOException} if the authenticator experienced an I/O
2806 * problem verifying the password, usually because of network
2807 * trouble
2808 * </ul>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002809 * @see #finishSession
Sandra Kwana578d112015-12-16 16:01:43 -08002810 * @hide
Sandra Kwane68c37e2015-11-12 17:11:49 -08002811 */
Sandra Kwana578d112015-12-16 16:01:43 -08002812 @SystemApi
Sandra Kwane68c37e2015-11-12 17:11:49 -08002813 public AccountManagerFuture<Bundle> startUpdateCredentialsSession(
2814 final Account account,
2815 final String authTokenType,
2816 final Bundle options,
2817 final Activity activity,
2818 final AccountManagerCallback<Bundle> callback,
2819 final Handler handler) {
2820 if (account == null) {
2821 throw new IllegalArgumentException("account is null");
2822 }
2823 return new AmsTask(activity, handler, callback) {
2824 @Override
2825 public void doWork() throws RemoteException {
2826 mService.startUpdateCredentialsSession(
2827 mResponse,
2828 account,
2829 authTokenType,
2830 activity != null,
2831 options);
Sandra Kwan78812282015-11-04 11:19:47 -08002832 }
2833 }.start();
2834 }
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002835
2836 /**
2837 * Finishes the session started by {@link #startAddAccountSession} or
2838 * {@link #startUpdateCredentialsSession}. This will either add the account
2839 * to AccountManager or update the local credentials stored.
2840 * <p>
2841 * This method may be called from any thread, but the returned
2842 * {@link AccountManagerFuture} must not be used on the main thread.
2843 *
2844 * @param sessionBundle a {@link Bundle} created by {@link #startAddAccountSession} or
2845 * {@link #startUpdateCredentialsSession}
2846 * @param activity The {@link Activity} context to use for launching a new
2847 * authenticator-defined sub-Activity to prompt the user to
2848 * create an account or reauthenticate existing account; used
2849 * only to call startActivity(); if null, the prompt will not
2850 * be launched directly, but the necessary {@link Intent} will
2851 * be returned to the caller instead
2852 * @param callback Callback to invoke when the request completes, null for
2853 * no callback
2854 * @param handler {@link Handler} identifying the callback thread, null for
2855 * the main thread
2856 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2857 * these fields if an activity was supplied and an account was added
2858 * to device or local credentials were updated::
2859 * <ul>
2860 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account created
2861 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account
2862 * </ul>
2863 * If no activity was specified and additional information is needed
2864 * from user, the returned Bundle may contains only
2865 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
2866 * actual account creation process. If an error occurred,
2867 * {@link AccountManagerFuture#getResult()} throws:
2868 * <ul>
2869 * <li>{@link AuthenticatorException} if no authenticator was
2870 * registered for this account type or the authenticator failed to
2871 * respond
2872 * <li>{@link OperationCanceledException} if the operation was
2873 * canceled for any reason, including the user canceling the
2874 * creation process or adding accounts (of this type) has been
2875 * disabled by policy
2876 * <li>{@link IOException} if the authenticator experienced an I/O
2877 * problem creating a new account, usually because of network
2878 * trouble
2879 * </ul>
2880 * @see #startAddAccountSession and #startUpdateCredentialsSession
Sandra Kwana578d112015-12-16 16:01:43 -08002881 * @hide
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002882 */
Sandra Kwana578d112015-12-16 16:01:43 -08002883 @SystemApi
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002884 public AccountManagerFuture<Bundle> finishSession(
2885 final Bundle sessionBundle,
2886 final Activity activity,
2887 AccountManagerCallback<Bundle> callback,
2888 Handler handler) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002889 return finishSessionAsUser(
2890 sessionBundle,
2891 activity,
2892 Process.myUserHandle(),
2893 callback,
2894 handler);
2895 }
2896
2897 /**
2898 * @see #finishSession
2899 * @hide
2900 */
2901 @SystemApi
2902 public AccountManagerFuture<Bundle> finishSessionAsUser(
2903 final Bundle sessionBundle,
2904 final Activity activity,
2905 final UserHandle userHandle,
2906 AccountManagerCallback<Bundle> callback,
2907 Handler handler) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002908 if (sessionBundle == null) {
2909 throw new IllegalArgumentException("sessionBundle is null");
2910 }
2911
2912 /* Add information required by add account flow */
2913 final Bundle appInfo = new Bundle();
2914 appInfo.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
2915
2916 return new AmsTask(activity, handler, callback) {
2917 @Override
2918 public void doWork() throws RemoteException {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002919 mService.finishSessionAsUser(
2920 mResponse,
2921 sessionBundle,
2922 activity != null,
2923 appInfo,
2924 userHandle.getIdentifier());
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002925 }
2926 }.start();
2927 }
Sandra Kwan390c9d22016-01-12 14:13:37 -08002928
2929 /**
2930 * Checks whether {@link #updateCredentials} or {@link #startUpdateCredentialsSession} should be
2931 * called with respect to the specified account.
2932 * <p>
2933 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
2934 * not be used on the main thread.
2935 *
2936 * @param account The {@link Account} to be checked whether {@link #updateCredentials} or
2937 * {@link #startUpdateCredentialsSession} should be called
2938 * @param statusToken a String of token to check account staus
2939 * @param callback Callback to invoke when the request completes, null for no callback
2940 * @param handler {@link Handler} identifying the callback thread, null for the main thread
2941 * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the credentials
2942 * of the account should be updated.
2943 * @hide
2944 */
2945 @SystemApi
2946 public AccountManagerFuture<Boolean> isCredentialsUpdateSuggested(
2947 final Account account,
2948 final String statusToken,
2949 AccountManagerCallback<Boolean> callback,
2950 Handler handler) {
2951 if (account == null) {
2952 throw new IllegalArgumentException("account is null");
2953 }
2954
2955 if (TextUtils.isEmpty(statusToken)) {
2956 throw new IllegalArgumentException("status token is empty");
2957 }
2958
2959 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002960 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08002961 public void doWork() throws RemoteException {
2962 mService.isCredentialsUpdateSuggested(
2963 mResponse,
2964 account,
2965 statusToken);
2966 }
Sandra Kwan0b84b452016-01-20 15:25:42 -08002967 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08002968 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
2969 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
2970 throw new AuthenticatorException("no result in response");
2971 }
2972 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
2973 }
2974 }.start();
2975 }
Fred Quintana60307342009-03-24 22:48:12 -07002976}