blob: ffa36d621cd0835ea1aa364b767c321551af2bab [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
Fred Quintana60307342009-03-24 22:48:12 -070019import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080020import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070021import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070022import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080023import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070024import android.content.IntentFilter;
Amith Yamasani12b8e132013-03-14 10:48:07 -070025import android.content.res.Resources;
Costin Manolacheb6437242009-09-10 16:14:12 -070026import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080027import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070028import android.os.Bundle;
29import android.os.Handler;
30import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070031import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080032import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080033import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080034import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080035import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080036import android.util.Log;
37
38import com.android.internal.R;
39import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070040
Fred Quintanaa698f422009-04-08 19:14:54 -070041import java.io.IOException;
Fred Quintana1121bb52011-09-14 23:19:35 -070042import java.util.ArrayList;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080043import java.util.HashMap;
44import java.util.Map;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import java.util.concurrent.Callable;
46import java.util.concurrent.CancellationException;
47import java.util.concurrent.ExecutionException;
48import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070049import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080050import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070051
52/**
Dan Egnor661f0132010-02-19 11:23:00 -080053 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070054 * online accounts. The user enters credentials (username and password) once
55 * per account, granting applications access to online resources with
56 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070057 *
Dan Egnor661f0132010-02-19 11:23:00 -080058 * <p>Different online services have different ways of handling accounts and
59 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070060 * modules for different <em>account types</em>. Authenticators (which may be
61 * written by third parties) handle the actual details of validating account
62 * credentials and storing account information. For example, Google, Facebook,
63 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080064 *
65 * <p>Many servers support some notion of an <em>authentication token</em>,
66 * which can be used to authenticate a request to the server without sending
67 * the user's actual password. (Auth tokens are normally created with a
68 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070069 * can generate auth tokens for applications, so the application doesn't need to
70 * handle passwords directly. Auth tokens are normally reusable and cached by
71 * AccountManager, but must be refreshed periodically. It's the responsibility
72 * of applications to <em>invalidate</em> auth tokens when they stop working so
73 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080074 *
75 * <p>Applications accessing a server normally go through these steps:
76 *
77 * <ul>
78 * <li>Get an instance of AccountManager using {@link #get(Context)}.
79 *
80 * <li>List the available accounts using {@link #getAccountsByType} or
81 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
82 * be interested in accounts with one particular <em>type</em>, which
83 * identifies the authenticator. Account <em>features</em> are used to
84 * identify particular account subtypes and capabilities. Both the account
85 * type and features are authenticator-specific strings, and must be known by
86 * the application in coordination with its preferred authenticators.
87 *
88 * <li>Select one or more of the available accounts, possibly by asking the
89 * user for their preference. If no suitable accounts are available,
90 * {@link #addAccount} may be called to prompt the user to create an
91 * account of the appropriate type.
92 *
Dan Egnor8e4378b2010-08-02 18:22:09 -070093 * <li><b>Important:</b> If the application is using a previously remembered
94 * account selection, it must make sure the account is still in the list
95 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
96 * for an account no longer on the device results in an undefined failure.
97 *
Dan Egnor661f0132010-02-19 11:23:00 -080098 * <li>Request an auth token for the selected account(s) using one of the
99 * {@link #getAuthToken} methods or related helpers. Refer to the description
100 * of each method for exact usage and error handling details.
101 *
102 * <li>Make the request using the auth token. The form of the auth token,
103 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700104 * service you are accessing. The application may use whatever network and
105 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800106 *
107 * <li><b>Important:</b> If the request fails with an authentication error,
108 * it could be that a cached auth token is stale and no longer honored by
109 * the server. The application must call {@link #invalidateAuthToken} to remove
110 * the token from the cache, otherwise requests will continue failing! After
111 * invalidating the auth token, immediately go back to the "Request an auth
112 * token" step above. If the process fails the second time, then it can be
113 * treated as a "genuine" authentication failure and the user notified or other
114 * appropriate actions taken.
115 * </ul>
116 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700117 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800118 * prompt for credentials, present options, or ask the user to add an account.
119 * The caller may choose whether to allow AccountManager to directly launch the
120 * necessary user interface and wait for the user, or to return an Intent which
121 * the caller may use to launch the interface, or (in some cases) to install a
122 * notification which the user can select at any time to launch the interface.
123 * To have AccountManager launch the interface directly, the caller must supply
124 * the current foreground {@link Activity} context.
125 *
126 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700127 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800128 * run asynchronously. If a callback is provided then
129 * {@link AccountManagerCallback#run} will be invoked on the Handler's
130 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700131 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
132 * on the {@link AccountManagerFuture} returned by the method (and also passed
133 * to the callback). This method waits for the operation to complete (if
134 * necessary) and either returns the result or throws an exception if an error
135 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800136 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700137 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800138 *
139 * <p>Requests which may block, including
140 * {@link AccountManagerFuture#getResult()}, must never be called on
141 * the application's main event thread. These operations throw
142 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700143 */
144public class AccountManager {
145 private static final String TAG = "AccountManager";
146
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700147 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
148 public static final int ERROR_CODE_NETWORK_ERROR = 3;
149 public static final int ERROR_CODE_CANCELED = 4;
150 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
151 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
152 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
153 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700154 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700155
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 /** @hide */
157 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100158 /** @hide */
159 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160
Dan Egnor661f0132010-02-19 11:23:00 -0800161 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700162 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800163 * from methods which return information about a particular account.
164 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700165 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800166
167 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700168 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800169 * from methods which return information about a particular account.
170 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700171 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800172
173 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700174 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800175 * from {@link #getAuthToken} and friends.
176 */
177 public static final String KEY_AUTHTOKEN = "authtoken";
178
179 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700180 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800181 * may require the caller to interact with the user. The Intent can
182 * be used to start the corresponding user interface activity.
183 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700184 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800185
186 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700187 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800188 * {@link #confirmCredentials}, rather than prompting the user with
189 * the standard password prompt.
190 */
191 public static final String KEY_PASSWORD = "password";
192
193 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700194
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700195 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
196 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800197 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700198 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
199 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800200 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
201 public static final String KEY_ERROR_CODE = "errorCode";
202 public static final String KEY_ERROR_MESSAGE = "errorMessage";
203 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700204
Costin Manolachea40c6302010-12-13 14:50:45 -0800205 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800206 * Bundle key used to supply the last time the credentials of the account
207 * were authenticated successfully. Time is specified in milliseconds since
208 * epoch.
209 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700210 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800211
212 /**
Costin Manolachea40c6302010-12-13 14:50:45 -0800213 * Authenticators using 'customTokens' option will also get the UID of the
214 * caller
215 */
216 public static final String KEY_CALLER_UID = "callerUid";
217 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800218
Costin Manolached6060452011-01-24 16:11:36 -0800219 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700220 * The Android package of the caller will be set in the options bundle by the
221 * {@link AccountManager} and will be passed to the AccountManagerService and
222 * to the AccountAuthenticators. The uid of the caller will be known by the
223 * AccountManagerService as well as the AccountAuthenticators so they will be able to
224 * verify that the package is consistent with the uid (a uid might be shared by many
225 * packages).
226 */
227 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
228
229 /**
Costin Manolached6060452011-01-24 16:11:36 -0800230 * Boolean, if set and 'customTokens' the authenticator is responsible for
231 * notifications.
232 * @hide
233 */
234 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
235
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700236 public static final String ACTION_AUTHENTICATOR_INTENT =
237 "android.accounts.AccountAuthenticator";
238 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800239 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700240 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
241
Fred Quintana60307342009-03-24 22:48:12 -0700242 private final Context mContext;
243 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700244 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800245
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700246 /**
247 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800248 * when accounts are added, accounts are removed, or an
249 * account's credentials (saved password, etc) are changed.
250 *
251 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700252 */
253 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
254 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700255
Fred Quintana33269202009-04-20 16:05:10 -0700256 /**
257 * @hide
258 */
Fred Quintana60307342009-03-24 22:48:12 -0700259 public AccountManager(Context context, IAccountManager service) {
260 mContext = context;
261 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700262 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700263 }
264
Fred Quintana0eabf022009-04-27 15:08:17 -0700265 /**
266 * @hide used for testing only
267 */
268 public AccountManager(Context context, IAccountManager service, Handler handler) {
269 mContext = context;
270 mService = service;
271 mMainHandler = handler;
272 }
273
Fred Quintana756b7352009-10-21 13:43:10 -0700274 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800275 * @hide for internal use only
276 */
277 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700278 if (result != null) {
279 if (result.containsKey(KEY_AUTHTOKEN)
280 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
281 final Bundle newResult = new Bundle(result);
282 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
283 return newResult;
284 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800285 }
286 return result;
287 }
288
289 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800290 * Gets an AccountManager instance associated with a Context.
291 * The {@link Context} will be used as long as the AccountManager is
292 * active, so make sure to use a {@link Context} whose lifetime is
293 * commensurate with any listeners registered to
294 * {@link #addOnAccountsUpdatedListener} or similar methods.
295 *
296 * <p>It is safe to call this method from the main thread.
297 *
298 * <p>No permission is required to call this method.
299 *
Fred Quintana756b7352009-10-21 13:43:10 -0700300 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800301 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700302 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700303 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700304 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700305 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
306 }
307
Fred Quintana756b7352009-10-21 13:43:10 -0700308 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800309 * Gets the saved password associated with the account.
310 * This is intended for authenticators and related code; applications
311 * should get an auth token instead.
312 *
313 * <p>It is safe to call this method from the main thread.
314 *
315 * <p>This method requires the caller to hold the permission
316 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
317 * and to have the same UID as the account's authenticator.
318 *
319 * @param account The account to query for a password
320 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700321 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700322 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700323 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700324 try {
325 return mService.getPassword(account);
326 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700327 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700328 throw new RuntimeException(e);
329 }
330 }
331
Fred Quintana756b7352009-10-21 13:43:10 -0700332 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800333 * Gets the user data named by "key" associated with the account.
334 * This is intended for authenticators and related code to store
335 * arbitrary metadata along with accounts. The meaning of the keys
336 * and values is up to the authenticator for the account.
337 *
338 * <p>It is safe to call this method from the main thread.
339 *
340 * <p>This method requires the caller to hold the permission
341 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
342 * and to have the same UID as the account's authenticator.
343 *
344 * @param account The account to query for user data
345 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700346 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700347 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700348 if (account == null) throw new IllegalArgumentException("account is null");
349 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700350 try {
351 return mService.getUserData(account, key);
352 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700353 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700354 throw new RuntimeException(e);
355 }
356 }
357
Fred Quintana756b7352009-10-21 13:43:10 -0700358 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800359 * Lists the currently registered authenticators.
360 *
361 * <p>It is safe to call this method from the main thread.
362 *
363 * <p>No permission is required to call this method.
364 *
365 * @return An array of {@link AuthenticatorDescription} for every
366 * authenticator known to the AccountManager service. Empty (never
367 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700368 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700369 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700370 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100371 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
372 } catch (RemoteException e) {
373 // will never happen
374 throw new RuntimeException(e);
375 }
376 }
377
378 /**
379 * @hide
380 * Lists the currently registered authenticators for a given user id.
381 *
382 * <p>It is safe to call this method from the main thread.
383 *
384 * <p>The caller has to be in the same user or have the permission
385 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
386 *
387 * @return An array of {@link AuthenticatorDescription} for every
388 * authenticator known to the AccountManager service. Empty (never
389 * null) if no authenticators are known.
390 */
391 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
392 try {
393 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700394 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700395 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700396 throw new RuntimeException(e);
397 }
398 }
399
Fred Quintana756b7352009-10-21 13:43:10 -0700400 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800401 * Lists all accounts of any type registered on the device.
402 * Equivalent to getAccountsByType(null).
403 *
404 * <p>It is safe to call this method from the main thread.
405 *
406 * <p>This method requires the caller to hold the permission
407 * {@link android.Manifest.permission#GET_ACCOUNTS}.
408 *
409 * @return An array of {@link Account}, one for each account. Empty
410 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700411 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700412 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700413 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700414 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700415 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700416 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700417 throw new RuntimeException(e);
418 }
419 }
420
Fred Quintana756b7352009-10-21 13:43:10 -0700421 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700422 * @hide
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100423 * Lists all accounts of any type registered on the device for a given
424 * user id. Equivalent to getAccountsByType(null).
425 *
426 * <p>It is safe to call this method from the main thread.
427 *
428 * <p>This method requires the caller to hold the permission
429 * {@link android.Manifest.permission#GET_ACCOUNTS}.
430 *
431 * @return An array of {@link Account}, one for each account. Empty
432 * (never null) if no accounts have been added.
433 */
434 public Account[] getAccountsAsUser(int userId) {
435 try {
436 return mService.getAccountsAsUser(null, userId);
437 } catch (RemoteException e) {
438 // won't ever happen
439 throw new RuntimeException(e);
440 }
441 }
442
443 /**
444 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700445 * For use by internal activities. Returns the list of accounts that the calling package
446 * is authorized to use, particularly for shared accounts.
447 * @param packageName package name of the calling app.
448 * @param uid the uid of the calling app.
449 * @return the accounts that are available to this package and user.
450 */
451 public Account[] getAccountsForPackage(String packageName, int uid) {
452 try {
453 return mService.getAccountsForPackage(packageName, uid);
454 } catch (RemoteException re) {
455 // possible security exception
456 throw new RuntimeException(re);
457 }
458 }
459
460 /**
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700461 * Returns the accounts visible to the specified package, in an environment where some apps
462 * are not authorized to view all accounts. This method can only be called by system apps.
463 * @param type The type of accounts to return, null to retrieve all accounts
464 * @param packageName The package name of the app for which the accounts are to be returned
465 * @return An array of {@link Account}, one per matching account. Empty
466 * (never null) if no accounts of the specified type have been added.
467 */
468 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
469 try {
470 return mService.getAccountsByTypeForPackage(type, packageName);
471 } catch (RemoteException re) {
472 // possible security exception
473 throw new RuntimeException(re);
474 }
475 }
476
477 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800478 * Lists all accounts of a particular type. The account type is a
479 * string token corresponding to the authenticator and useful domain
480 * of the account. For example, there are types corresponding to Google
481 * and Facebook. The exact string token to use will be published somewhere
482 * associated with the authenticator in question.
483 *
484 * <p>It is safe to call this method from the main thread.
485 *
486 * <p>This method requires the caller to hold the permission
487 * {@link android.Manifest.permission#GET_ACCOUNTS}.
488 *
489 * @param type The type of accounts to return, null to retrieve all accounts
490 * @return An array of {@link Account}, one per matching account. Empty
491 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700492 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700493 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800494 return getAccountsByTypeAsUser(type, Process.myUserHandle());
495 }
496
497 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
498 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700499 try {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800500 return mService.getAccountsAsUser(type, userHandle.getIdentifier());
Fred Quintana60307342009-03-24 22:48:12 -0700501 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700502 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700503 throw new RuntimeException(e);
504 }
505 }
506
Fred Quintana756b7352009-10-21 13:43:10 -0700507 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700508 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
509 * for an account.
510 * <p>
511 * This is only meant to be used by system activities and is not in the SDK.
512 * @param account The account whose permissions are being modified
513 * @param authTokenType The type of token whose permissions are being modified
514 * @param uid The uid that identifies the app which is being granted or revoked permission.
515 * @param value true is permission is being granted, false for revoked
516 * @hide
517 */
518 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
519 try {
520 mService.updateAppPermission(account, authTokenType, uid, value);
521 } catch (RemoteException e) {
522 // won't ever happen
523 throw new RuntimeException(e);
524 }
525 }
526
527 /**
528 * Get the user-friendly label associated with an authenticator's auth token.
529 * @param accountType the type of the authenticator. must not be null.
530 * @param authTokenType the token type. must not be null.
531 * @param callback callback to invoke when the result is available. may be null.
532 * @param handler the handler on which to invoke the callback, or null for the main thread
533 * @return a future containing the label string
534 * @hide
535 */
536 public AccountManagerFuture<String> getAuthTokenLabel(
537 final String accountType, final String authTokenType,
538 AccountManagerCallback<String> callback, Handler handler) {
539 if (accountType == null) throw new IllegalArgumentException("accountType is null");
540 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
541 return new Future2Task<String>(handler, callback) {
542 public void doWork() throws RemoteException {
543 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
544 }
545
546 @Override
547 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
548 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
549 throw new AuthenticatorException("no result in response");
550 }
551 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
552 }
553 }.start();
554 }
555
556 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800557 * Finds out whether a particular account has all the specified features.
558 * Account features are authenticator-specific string tokens identifying
559 * boolean account properties. For example, features are used to tell
560 * whether Google accounts have a particular service (such as Google
561 * Calendar or Google Talk) enabled. The feature names and their meanings
562 * are published somewhere associated with the authenticator in question.
563 *
564 * <p>This method may be called from any thread, but the returned
565 * {@link AccountManagerFuture} must not be used on the main thread.
566 *
567 * <p>This method requires the caller to hold the permission
568 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800569 *
570 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800571 * @param features An array of the account features to check
572 * @param callback Callback to invoke when the request completes,
573 * null for no callback
574 * @param handler {@link Handler} identifying the callback thread,
575 * null for the main thread
576 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
577 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800578 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800579 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800580 final String[] features,
581 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700582 if (account == null) throw new IllegalArgumentException("account is null");
583 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800584 return new Future2Task<Boolean>(handler, callback) {
585 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800586 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800587 }
588 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
589 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
590 throw new AuthenticatorException("no result in response");
591 }
592 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
593 }
594 }.start();
595 }
596
597 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800598 * Lists all accounts of a type which have certain features. The account
599 * type identifies the authenticator (see {@link #getAccountsByType}).
600 * Account features are authenticator-specific string tokens identifying
601 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700602 *
Dan Egnor661f0132010-02-19 11:23:00 -0800603 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
604 * which may contact the server or do other work to check account features,
605 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700606 *
Dan Egnor661f0132010-02-19 11:23:00 -0800607 * <p>This method may be called from any thread, but the returned
608 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700609 *
Dan Egnor661f0132010-02-19 11:23:00 -0800610 * <p>This method requires the caller to hold the permission
611 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700612 *
Dan Egnor661f0132010-02-19 11:23:00 -0800613 * @param type The type of accounts to return, must not be null
614 * @param features An array of the account features to require,
615 * may be null or empty
616 * @param callback Callback to invoke when the request completes,
617 * null for no callback
618 * @param handler {@link Handler} identifying the callback thread,
619 * null for the main thread
620 * @return An {@link AccountManagerFuture} which resolves to an array of
621 * {@link Account}, one per account of the specified type which
622 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800623 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700624 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
625 final String type, final String[] features,
626 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700627 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700628 return new Future2Task<Account[]>(handler, callback) {
629 public void doWork() throws RemoteException {
630 mService.getAccountsByFeatures(mResponse, type, features);
631 }
632 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700633 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700634 throw new AuthenticatorException("no result in response");
635 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700636 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700637 Account[] descs = new Account[parcelables.length];
638 for (int i = 0; i < parcelables.length; i++) {
639 descs[i] = (Account) parcelables[i];
640 }
641 return descs;
642 }
643 }.start();
644 }
645
Fred Quintana756b7352009-10-21 13:43:10 -0700646 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800647 * Adds an account directly to the AccountManager. Normally used by sign-up
648 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700649 *
Dan Egnor661f0132010-02-19 11:23:00 -0800650 * <p>It is safe to call this method from the main thread.
651 *
652 * <p>This method requires the caller to hold the permission
653 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
654 * and to have the same UID as the added account's authenticator.
655 *
656 * @param account The {@link Account} to add
657 * @param password The password to associate with the account, null for none
658 * @param userdata String values to use for the account's userdata, null for none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700659 * @return True if the account was successfully added, false if the account
Dan Egnor661f0132010-02-19 11:23:00 -0800660 * already exists, the account is null, or another error occurs.
661 */
662 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700663 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800664 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700665 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800666 } catch (RemoteException e) {
667 // won't ever happen
668 throw new RuntimeException(e);
669 }
670 }
671
672 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700673 * Notifies the system that the account has just been authenticated. This
674 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800675 * should be called only when the user has entered correct credentials for
676 * the account.
677 * <p>
678 * It is not safe to call this method from the main thread. As such, call it
679 * from another thread.
680 * <p>
681 * This method requires the caller to hold the permission
682 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} and should be
683 * called from the account's authenticator.
684 *
685 * @param account The {@link Account} to be updated.
686 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700687 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800688 if (account == null)
689 throw new IllegalArgumentException("account is null");
690 try {
691 return mService.accountAuthenticated(account);
692 } catch (RemoteException e) {
693 throw new RuntimeException(e);
694 }
695 }
696
697 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700698 * Rename the specified {@link Account}. This is equivalent to removing
699 * the existing account and adding a new renamed account with the old
700 * account's user data.
701 *
702 * <p>It is safe to call this method from the main thread.
703 *
704 * <p>This method requires the caller to hold the permission
705 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
706 * and have the same UID as the account's authenticator.
707 *
708 * @param account The {@link Account} to rename
709 * @param newName String name to be associated with the account.
710 * @param callback Callback to invoke when the request completes, null for
711 * no callback
712 * @param handler {@link Handler} identifying the callback thread, null for
713 * the main thread
714 * @return An {@link AccountManagerFuture} which resolves to the Account
715 * after the name change. If successful the account's name will be the
716 * specified new name.
717 */
718 public AccountManagerFuture<Account> renameAccount(
719 final Account account,
720 final String newName,
721 AccountManagerCallback<Account> callback,
722 Handler handler) {
723 if (account == null) throw new IllegalArgumentException("account is null.");
724 if (TextUtils.isEmpty(newName)) {
725 throw new IllegalArgumentException("newName is empty or null.");
726 }
727 return new Future2Task<Account>(handler, callback) {
728 @Override
729 public void doWork() throws RemoteException {
730 mService.renameAccount(mResponse, account, newName);
731 }
732 @Override
733 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
734 String name = bundle.getString(KEY_ACCOUNT_NAME);
735 String type = bundle.getString(KEY_ACCOUNT_TYPE);
736 return new Account(name, type);
737 }
738 }.start();
739 }
740
741 /**
742 * Gets the previous name associated with the account or {@code null}, if
743 * none. This is intended so that clients of {@link
744 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
745 * authenticator has renamed an account.
746 *
747 * <p>It is safe to call this method from the main thread.
748 *
749 * @param account The account to query for a previous name.
750 * @return The account's previous name, null if the account has never been
751 * renamed.
752 */
753 public String getPreviousName(final Account account) {
754 if (account == null) throw new IllegalArgumentException("account is null");
755 try {
756 return mService.getPreviousName(account);
757 } catch (RemoteException e) {
758 // will never happen
759 throw new RuntimeException(e);
760 }
761 }
762
763 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800764 * Removes an account from the AccountManager. Does nothing if the account
765 * does not exist. Does not delete the account from the server.
766 * The authenticator may have its own policies preventing account
767 * deletion, in which case the account will not be deleted.
768 *
769 * <p>This method may be called from any thread, but the returned
770 * {@link AccountManagerFuture} must not be used on the main thread.
771 *
772 * <p>This method requires the caller to hold the permission
773 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
774 *
775 * @param account The {@link Account} to remove
776 * @param callback Callback to invoke when the request completes,
777 * null for no callback
778 * @param handler {@link Handler} identifying the callback thread,
779 * null for the main thread
780 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100781 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800782 * @deprecated use
783 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
784 * instead
Dan Egnor661f0132010-02-19 11:23:00 -0800785 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800786 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800787 public AccountManagerFuture<Boolean> removeAccount(final Account account,
788 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700789 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800790 return new Future2Task<Boolean>(handler, callback) {
791 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800792 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -0800793 }
794 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
795 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
796 throw new AuthenticatorException("no result in response");
797 }
798 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
799 }
800 }.start();
801 }
802
803 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800804 * Removes an account from the AccountManager. Does nothing if the account
805 * does not exist. Does not delete the account from the server.
806 * The authenticator may have its own policies preventing account
807 * deletion, in which case the account will not be deleted.
808 *
809 * <p>This method may be called from any thread, but the returned
810 * {@link AccountManagerFuture} must not be used on the main thread.
811 *
812 * <p>This method requires the caller to hold the permission
813 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
814 *
815 * @param account The {@link Account} to remove
816 * @param activity The {@link Activity} context to use for launching a new
817 * authenticator-defined sub-Activity to prompt the user to delete an
818 * account; used only to call startActivity(); if null, the prompt
819 * will not be launched directly, but the {@link Intent} may be
820 * returned to the caller instead
821 * @param callback Callback to invoke when the request completes,
822 * null for no callback
823 * @param handler {@link Handler} identifying the callback thread,
824 * null for the main thread
825 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
826 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
827 * was removed or if active. If no activity was specified, the returned
828 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
829 * needed to launch the actual account removal process, if authenticator
830 * needs the activity launch. If an error occurred,
831 * {@link AccountManagerFuture#getResult()} throws:
832 * <ul>
833 * <li> {@link AuthenticatorException} if no authenticator was registered for
834 * this account type or the authenticator failed to respond
835 * <li> {@link OperationCanceledException} if the operation was canceled for
836 * any reason, including the user canceling the creation process or
837 * adding accounts (of this type) has been disabled by policy
838 * </ul>
839 */
840 public AccountManagerFuture<Bundle> removeAccount(final Account account,
841 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
842 if (account == null) throw new IllegalArgumentException("account is null");
843 return new AmsTask(activity, handler, callback) {
844 public void doWork() throws RemoteException {
845 mService.removeAccount(mResponse, account, activity != null);
846 }
847 }.start();
848 }
849
850 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100851 * @see #removeAccount(Account, AccountManagerCallback, Handler)
852 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800853 * @deprecated use
854 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
855 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100856 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800857 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100858 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
859 AccountManagerCallback<Boolean> callback, Handler handler,
860 final UserHandle userHandle) {
861 if (account == null) throw new IllegalArgumentException("account is null");
862 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
863 return new Future2Task<Boolean>(handler, callback) {
864 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800865 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100866 }
867 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
868 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
869 throw new AuthenticatorException("no result in response");
870 }
871 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
872 }
873 }.start();
874 }
875
876 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800877 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
878 * @hide
879 */
880 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
881 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
882 final UserHandle userHandle) {
883 if (account == null)
884 throw new IllegalArgumentException("account is null");
885 if (userHandle == null)
886 throw new IllegalArgumentException("userHandle is null");
887 return new AmsTask(activity, handler, callback) {
888 public void doWork() throws RemoteException {
889 mService.removeAccountAsUser(mResponse, account, activity != null,
890 userHandle.getIdentifier());
891 }
892 }.start();
893 }
894
895 /**
896 * Removes an account directly. Normally used by authenticators, not
897 * directly by applications. Does not delete the account from the server.
898 * The authenticator may have its own policies preventing account deletion,
899 * in which case the account will not be deleted.
900 * <p>
901 * It is safe to call this method from the main thread.
902 * <p>
903 * This method requires the caller to hold the permission
904 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} and to have the
905 * same UID or signature as the account's authenticator.
906 *
907 * @param account The {@link Account} to delete.
908 * @return True if the account was successfully deleted, false if the
909 * account did not exist, the account is null, or another error
910 * occurs.
911 */
912 public boolean removeAccountExplicitly(Account account) {
913 if (account == null) throw new IllegalArgumentException("account is null");
914 try {
915 return mService.removeAccountExplicitly(account);
916 } catch (RemoteException e) {
917 // won't ever happen
918 throw new RuntimeException(e);
919 }
920 }
921
922 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800923 * Removes an auth token from the AccountManager's cache. Does nothing if
924 * the auth token is not currently in the cache. Applications must call this
925 * method when the auth token is found to have expired or otherwise become
926 * invalid for authenticating requests. The AccountManager does not validate
927 * or expire cached auth tokens otherwise.
928 *
929 * <p>It is safe to call this method from the main thread.
930 *
931 * <p>This method requires the caller to hold the permission
Fred Quintanab38eb142010-02-24 13:40:54 -0800932 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
933 * {@link android.Manifest.permission#USE_CREDENTIALS}
Dan Egnor661f0132010-02-19 11:23:00 -0800934 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700935 * @param accountType The account type of the auth token to invalidate, must not be null
936 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800937 */
938 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700939 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800940 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700941 if (authToken != null) {
942 mService.invalidateAuthToken(accountType, authToken);
943 }
Dan Egnor661f0132010-02-19 11:23:00 -0800944 } catch (RemoteException e) {
945 // won't ever happen
946 throw new RuntimeException(e);
947 }
948 }
949
950 /**
951 * Gets an auth token from the AccountManager's cache. If no auth
952 * token is cached for this account, null will be returned -- a new
953 * auth token will not be generated, and the server will not be contacted.
954 * Intended for use by the authenticator, not directly by applications.
955 *
956 * <p>It is safe to call this method from the main thread.
957 *
958 * <p>This method requires the caller to hold the permission
959 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
960 * and to have the same UID as the account's authenticator.
961 *
962 * @param account The account to fetch an auth token for
963 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
964 * @return The cached auth token for this account and type, or null if
965 * no auth token is cached or the account does not exist.
966 */
967 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700968 if (account == null) throw new IllegalArgumentException("account is null");
969 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800970 try {
971 return mService.peekAuthToken(account, authTokenType);
972 } catch (RemoteException e) {
973 // won't ever happen
974 throw new RuntimeException(e);
975 }
976 }
977
978 /**
979 * Sets or forgets a saved password. This modifies the local copy of the
980 * password used to automatically authenticate the user; it does
981 * not change the user's account password on the server. Intended for use
982 * by the authenticator, not directly by applications.
983 *
984 * <p>It is safe to call this method from the main thread.
985 *
986 * <p>This method requires the caller to hold the permission
987 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
988 * and have the same UID as the account's authenticator.
989 *
990 * @param account The account to set a password for
991 * @param password The password to set, null to clear the password
992 */
993 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700994 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800995 try {
996 mService.setPassword(account, password);
997 } catch (RemoteException e) {
998 // won't ever happen
999 throw new RuntimeException(e);
1000 }
1001 }
1002
1003 /**
1004 * Forgets a saved password. This erases the local copy of the password;
1005 * it does not change the user's account password on the server.
1006 * Has the same effect as setPassword(account, null) but requires fewer
1007 * permissions, and may be used by applications or management interfaces
1008 * to "sign out" from an account.
1009 *
1010 * <p>It is safe to call this method from the main thread.
1011 *
1012 * <p>This method requires the caller to hold the permission
1013 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
1014 *
1015 * @param account The account whose password to clear
1016 */
1017 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001018 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001019 try {
1020 mService.clearPassword(account);
1021 } catch (RemoteException e) {
1022 // won't ever happen
1023 throw new RuntimeException(e);
1024 }
1025 }
1026
1027 /**
1028 * Sets one userdata key for an account. Intended by use for the
1029 * authenticator to stash state for itself, not directly by applications.
1030 * The meaning of the keys and values is up to the authenticator.
1031 *
1032 * <p>It is safe to call this method from the main thread.
1033 *
1034 * <p>This method requires the caller to hold the permission
1035 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
1036 * and to have the same UID as the account's authenticator.
1037 *
1038 * @param account The account to set the userdata for
1039 * @param key The userdata key to set. Must not be null
1040 * @param value The value to set, null to clear this userdata key
1041 */
1042 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001043 if (account == null) throw new IllegalArgumentException("account is null");
1044 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001045 try {
1046 mService.setUserData(account, key, value);
1047 } catch (RemoteException e) {
1048 // won't ever happen
1049 throw new RuntimeException(e);
1050 }
1051 }
1052
1053 /**
1054 * Adds an auth token to the AccountManager cache for an account.
1055 * If the account does not exist then this call has no effect.
1056 * Replaces any previous auth token for this account and auth token type.
1057 * Intended for use by the authenticator, not directly by applications.
1058 *
1059 * <p>It is safe to call this method from the main thread.
1060 *
1061 * <p>This method requires the caller to hold the permission
1062 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
1063 * and to have the same UID as the account's authenticator.
1064 *
1065 * @param account The account to set an auth token for
1066 * @param authTokenType The type of the auth token, see {#getAuthToken}
1067 * @param authToken The auth token to add to the cache
1068 */
1069 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001070 if (account == null) throw new IllegalArgumentException("account is null");
1071 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001072 try {
1073 mService.setAuthToken(account, authTokenType, authToken);
1074 } catch (RemoteException e) {
1075 // won't ever happen
1076 throw new RuntimeException(e);
1077 }
1078 }
1079
1080 /**
1081 * This convenience helper synchronously gets an auth token with
1082 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1083 *
1084 * <p>This method may block while a network request completes, and must
1085 * never be made from the main thread.
1086 *
1087 * <p>This method requires the caller to hold the permission
1088 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1089 *
1090 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001091 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001092 * @param notifyAuthFailure If true, display a notification and return null
1093 * if authentication fails; if false, prompt and wait for the user to
1094 * re-enter correct credentials before returning
1095 * @return An auth token of the specified type for this account, or null
1096 * if authentication fails or none can be fetched.
1097 * @throws AuthenticatorException if the authenticator failed to respond
1098 * @throws OperationCanceledException if the request was canceled for any
1099 * reason, including the user canceling a credential request
1100 * @throws java.io.IOException if the authenticator experienced an I/O problem
1101 * creating a new auth token, usually because of network trouble
1102 */
1103 public String blockingGetAuthToken(Account account, String authTokenType,
1104 boolean notifyAuthFailure)
1105 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001106 if (account == null) throw new IllegalArgumentException("account is null");
1107 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001108 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1109 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001110 if (bundle == null) {
1111 // This should never happen, but it does, occasionally. If it does return null to
1112 // signify that we were not able to get the authtoken.
1113 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1114 // returned
1115 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1116 + account + ", authTokenType " + authTokenType);
1117 return null;
1118 }
Dan Egnor661f0132010-02-19 11:23:00 -08001119 return bundle.getString(KEY_AUTHTOKEN);
1120 }
1121
1122 /**
1123 * Gets an auth token of the specified type for a particular account,
1124 * prompting the user for credentials if necessary. This method is
1125 * intended for applications running in the foreground where it makes
1126 * sense to ask the user directly for a password.
1127 *
1128 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001129 * type, then it is returned. Otherwise, if a saved password is
1130 * available, it is sent to the server to generate a new auth token.
1131 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001132 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001133 * <p>Some authenticators have auth token <em>types</em>, whose value
1134 * is authenticator-dependent. Some services use different token types to
1135 * access different functionality -- for example, Google uses different auth
1136 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001137 *
1138 * <p>This method may be called from any thread, but the returned
1139 * {@link AccountManagerFuture} must not be used on the main thread.
1140 *
1141 * <p>This method requires the caller to hold the permission
1142 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1143 *
1144 * @param account The account to fetch an auth token for
1145 * @param authTokenType The auth token type, an authenticator-dependent
1146 * string token, must not be null
1147 * @param options Authenticator-specific options for the request,
1148 * may be null or empty
1149 * @param activity The {@link Activity} context to use for launching a new
1150 * authenticator-defined sub-Activity to prompt the user for a password
1151 * if necessary; used only to call startActivity(); must not be null.
1152 * @param callback Callback to invoke when the request completes,
1153 * null for no callback
1154 * @param handler {@link Handler} identifying the callback thread,
1155 * null for the main thread
1156 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1157 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001158 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001159 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1160 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1161 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001162 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001163 *
1164 * (Other authenticator-specific values may be returned.) If an auth token
1165 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1166 * <ul>
1167 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1168 * <li> {@link OperationCanceledException} if the operation is canceled for
1169 * any reason, incluidng the user canceling a credential request
1170 * <li> {@link IOException} if the authenticator experienced an I/O problem
1171 * creating a new auth token, usually because of network trouble
1172 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001173 * If the account is no longer present on the device, the return value is
1174 * authenticator-dependent. The caller should verify the validity of the
1175 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001176 */
1177 public AccountManagerFuture<Bundle> getAuthToken(
1178 final Account account, final String authTokenType, final Bundle options,
1179 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001180 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001181 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001182 final Bundle optionsIn = new Bundle();
1183 if (options != null) {
1184 optionsIn.putAll(options);
1185 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001186 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001187 return new AmsTask(activity, handler, callback) {
1188 public void doWork() throws RemoteException {
1189 mService.getAuthToken(mResponse, account, authTokenType,
1190 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001191 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001192 }
1193 }.start();
1194 }
1195
1196 /**
1197 * Gets an auth token of the specified type for a particular account,
1198 * optionally raising a notification if the user must enter credentials.
1199 * This method is intended for background tasks and services where the
1200 * user should not be immediately interrupted with a password prompt.
1201 *
1202 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001203 * type, then it is returned. Otherwise, if a saved password is
1204 * available, it is sent to the server to generate a new auth token.
1205 * Otherwise, an {@link Intent} is returned which, when started, will
1206 * prompt the user for a password. If the notifyAuthFailure parameter is
1207 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001208 * alerting the user that they need to enter a password at some point.
1209 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001210 * <p>In that case, you may need to wait until the user responds, which
1211 * could take hours or days or forever. When the user does respond and
1212 * supply a new password, the account manager will broadcast the
1213 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1214 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001215 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001216 * <p>If notifyAuthFailure is not set, it is the application's
1217 * responsibility to launch the returned Intent at some point.
1218 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001219 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001220 * <p>Some authenticators have auth token <em>types</em>, whose value
1221 * is authenticator-dependent. Some services use different token types to
1222 * access different functionality -- for example, Google uses different auth
1223 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001224 *
1225 * <p>This method may be called from any thread, but the returned
1226 * {@link AccountManagerFuture} must not be used on the main thread.
1227 *
1228 * <p>This method requires the caller to hold the permission
1229 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1230 *
1231 * @param account The account to fetch an auth token for
1232 * @param authTokenType The auth token type, an authenticator-dependent
1233 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001234 * @param notifyAuthFailure True to add a notification to prompt the
1235 * user for a password if necessary, false to leave that to the caller
1236 * @param callback Callback to invoke when the request completes,
1237 * null for no callback
1238 * @param handler {@link Handler} identifying the callback thread,
1239 * null for the main thread
1240 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1241 * at least the following fields on success:
1242 * <ul>
1243 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1244 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1245 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1246 * </ul>
1247 *
1248 * (Other authenticator-specific values may be returned.) If the user
1249 * must enter credentials, the returned Bundle contains only
1250 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1251 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001252 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001253 * <ul>
1254 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1255 * <li> {@link OperationCanceledException} if the operation is canceled for
1256 * any reason, incluidng the user canceling a credential request
1257 * <li> {@link IOException} if the authenticator experienced an I/O problem
1258 * creating a new auth token, usually because of network trouble
1259 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001260 * If the account is no longer present on the device, the return value is
1261 * authenticator-dependent. The caller should verify the validity of the
1262 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001263 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1264 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001265 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001266 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001267 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001268 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001269 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001270 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001271 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001272 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001273 }
1274
1275 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001276 * Gets an auth token of the specified type for a particular account,
1277 * optionally raising a notification if the user must enter credentials.
1278 * This method is intended for background tasks and services where the
1279 * user should not be immediately interrupted with a password prompt.
1280 *
1281 * <p>If a previously generated auth token is cached for this account and
1282 * type, then it is returned. Otherwise, if a saved password is
1283 * available, it is sent to the server to generate a new auth token.
1284 * Otherwise, an {@link Intent} is returned which, when started, will
1285 * prompt the user for a password. If the notifyAuthFailure parameter is
1286 * set, a status bar notification is also created with the same Intent,
1287 * alerting the user that they need to enter a password at some point.
1288 *
1289 * <p>In that case, you may need to wait until the user responds, which
1290 * could take hours or days or forever. When the user does respond and
1291 * supply a new password, the account manager will broadcast the
1292 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1293 * use to try again.
1294 *
1295 * <p>If notifyAuthFailure is not set, it is the application's
1296 * responsibility to launch the returned Intent at some point.
1297 * Either way, the result from this call will not wait for user action.
1298 *
1299 * <p>Some authenticators have auth token <em>types</em>, whose value
1300 * is authenticator-dependent. Some services use different token types to
1301 * access different functionality -- for example, Google uses different auth
1302 * tokens to access Gmail and Google Calendar for the same account.
1303 *
1304 * <p>This method may be called from any thread, but the returned
1305 * {@link AccountManagerFuture} must not be used on the main thread.
1306 *
1307 * <p>This method requires the caller to hold the permission
1308 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1309 *
1310 * @param account The account to fetch an auth token for
1311 * @param authTokenType The auth token type, an authenticator-dependent
1312 * string token, must not be null
1313 * @param options Authenticator-specific options for the request,
1314 * may be null or empty
1315 * @param notifyAuthFailure True to add a notification to prompt the
1316 * user for a password if necessary, false to leave that to the caller
1317 * @param callback Callback to invoke when the request completes,
1318 * null for no callback
1319 * @param handler {@link Handler} identifying the callback thread,
1320 * null for the main thread
1321 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1322 * at least the following fields on success:
1323 * <ul>
1324 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1325 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1326 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1327 * </ul>
1328 *
1329 * (Other authenticator-specific values may be returned.) If the user
1330 * must enter credentials, the returned Bundle contains only
1331 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1332 *
1333 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1334 * <ul>
1335 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1336 * <li> {@link OperationCanceledException} if the operation is canceled for
1337 * any reason, incluidng the user canceling a credential request
1338 * <li> {@link IOException} if the authenticator experienced an I/O problem
1339 * creating a new auth token, usually because of network trouble
1340 * </ul>
1341 * If the account is no longer present on the device, the return value is
1342 * authenticator-dependent. The caller should verify the validity of the
1343 * account before requesting an auth token.
1344 */
1345 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001346 final Account account, final String authTokenType, final Bundle options,
1347 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001348 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001349
Fred Quintanaad93a322011-09-08 13:21:01 -07001350 if (account == null) throw new IllegalArgumentException("account is null");
1351 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001352 final Bundle optionsIn = new Bundle();
1353 if (options != null) {
1354 optionsIn.putAll(options);
1355 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001356 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001357 return new AmsTask(null, handler, callback) {
1358 public void doWork() throws RemoteException {
1359 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001360 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001361 }
1362 }.start();
1363 }
1364
1365 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001366 * Asks the user to add an account of a specified type. The authenticator
1367 * for this account type processes this request with the appropriate user
1368 * interface. If the user does elect to create a new account, the account
1369 * name is returned.
1370 *
1371 * <p>This method may be called from any thread, but the returned
1372 * {@link AccountManagerFuture} must not be used on the main thread.
1373 *
1374 * <p>This method requires the caller to hold the permission
1375 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1376 *
1377 * @param accountType The type of account to add; must not be null
1378 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1379 * this account will need to be able to generate, null for none
1380 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1381 * account must have, null for none
1382 * @param addAccountOptions Authenticator-specific options for the request,
1383 * may be null or empty
1384 * @param activity The {@link Activity} context to use for launching a new
1385 * authenticator-defined sub-Activity to prompt the user to create an
1386 * account; used only to call startActivity(); if null, the prompt
1387 * will not be launched directly, but the necessary {@link Intent}
1388 * will be returned to the caller instead
1389 * @param callback Callback to invoke when the request completes,
1390 * null for no callback
1391 * @param handler {@link Handler} identifying the callback thread,
1392 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001393 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001394 * these fields if activity was specified and an account was created:
1395 * <ul>
1396 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1397 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1398 * </ul>
1399 *
1400 * If no activity was specified, the returned Bundle contains only
1401 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001402 * actual account creation process. If an error occurred,
1403 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001404 * <ul>
1405 * <li> {@link AuthenticatorException} if no authenticator was registered for
1406 * this account type or the authenticator failed to respond
1407 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001408 * any reason, including the user canceling the creation process or adding accounts
1409 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001410 * <li> {@link IOException} if the authenticator experienced an I/O problem
1411 * creating a new account, usually because of network trouble
1412 * </ul>
1413 */
1414 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1415 final String authTokenType, final String[] requiredFeatures,
1416 final Bundle addAccountOptions,
1417 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001418 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001419 final Bundle optionsIn = new Bundle();
1420 if (addAccountOptions != null) {
1421 optionsIn.putAll(addAccountOptions);
1422 }
1423 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001424
Dan Egnor661f0132010-02-19 11:23:00 -08001425 return new AmsTask(activity, handler, callback) {
1426 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001427 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001428 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001429 }
1430 }.start();
1431 }
1432
1433 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001434 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1435 * @hide
1436 */
1437 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1438 final String authTokenType, final String[] requiredFeatures,
1439 final Bundle addAccountOptions, final Activity activity,
1440 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1441 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1442 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1443 final Bundle optionsIn = new Bundle();
1444 if (addAccountOptions != null) {
1445 optionsIn.putAll(addAccountOptions);
1446 }
1447 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1448
1449 return new AmsTask(activity, handler, callback) {
1450 public void doWork() throws RemoteException {
1451 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1452 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1453 }
1454 }.start();
1455 }
1456
1457 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001458 * Adds a shared account from the primary user to a secondary user. Adding the shared account
1459 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1460 * are attempted to be copied to the target user from the primary via calls to the
1461 * authenticator.
1462 * @param account the account to share
1463 * @param user the target user
1464 * @return
1465 * @hide
1466 */
1467 public boolean addSharedAccount(final Account account, UserHandle user) {
1468 try {
1469 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1470 return val;
1471 } catch (RemoteException re) {
1472 // won't ever happen
1473 throw new RuntimeException(re);
1474 }
1475 }
1476
1477 /**
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001478 * Copies an account from the primary user to another user.
1479 * @param account the account to copy
1480 * @param user the target user
1481 * @param callback Callback to invoke when the request completes,
1482 * null for no callback
1483 * @param handler {@link Handler} identifying the callback thread,
1484 * null for the main thread
1485 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1486 * succeeded.
1487 * @hide
1488 */
1489 public AccountManagerFuture<Boolean> copyAccountToUser(
1490 final Account account, final UserHandle user,
1491 AccountManagerCallback<Boolean> callback, Handler handler) {
1492 if (account == null) throw new IllegalArgumentException("account is null");
1493 if (user == null) throw new IllegalArgumentException("user is null");
1494
1495 return new Future2Task<Boolean>(handler, callback) {
1496 @Override
1497 public void doWork() throws RemoteException {
1498 mService.copyAccountToUser(
1499 mResponse, account, UserHandle.USER_OWNER, user.getIdentifier());
1500 }
1501 @Override
1502 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1503 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1504 throw new AuthenticatorException("no result in response");
1505 }
1506 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1507 }
1508 }.start();
1509 }
1510
1511 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001512 * @hide
1513 * Removes the shared account.
1514 * @param account the account to remove
1515 * @param user the user to remove the account from
1516 * @return
1517 */
1518 public boolean removeSharedAccount(final Account account, UserHandle user) {
1519 try {
1520 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1521 return val;
1522 } catch (RemoteException re) {
1523 // won't ever happen
1524 throw new RuntimeException(re);
1525 }
1526 }
1527
1528 /**
1529 * @hide
1530 * @param user
1531 * @return
1532 */
1533 public Account[] getSharedAccounts(UserHandle user) {
1534 try {
1535 return mService.getSharedAccountsAsUser(user.getIdentifier());
1536 } catch (RemoteException re) {
1537 // won't ever happen
1538 throw new RuntimeException(re);
1539 }
1540 }
1541
1542 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001543 * Confirms that the user knows the password for an account to make extra
1544 * sure they are the owner of the account. The user-entered password can
1545 * be supplied directly, otherwise the authenticator for this account type
1546 * prompts the user with the appropriate interface. This method is
1547 * intended for applications which want extra assurance; for example, the
1548 * phone lock screen uses this to let the user unlock the phone with an
1549 * account password if they forget the lock pattern.
1550 *
1551 * <p>If the user-entered password matches a saved password for this
1552 * account, the request is considered valid; otherwise the authenticator
1553 * verifies the password (usually by contacting the server).
1554 *
1555 * <p>This method may be called from any thread, but the returned
1556 * {@link AccountManagerFuture} must not be used on the main thread.
1557 *
1558 * <p>This method requires the caller to hold the permission
1559 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1560 *
1561 * @param account The account to confirm password knowledge for
1562 * @param options Authenticator-specific options for the request;
1563 * if the {@link #KEY_PASSWORD} string field is present, the
1564 * authenticator may use it directly rather than prompting the user;
1565 * may be null or empty
1566 * @param activity The {@link Activity} context to use for launching a new
1567 * authenticator-defined sub-Activity to prompt the user to enter a
1568 * password; used only to call startActivity(); if null, the prompt
1569 * will not be launched directly, but the necessary {@link Intent}
1570 * will be returned to the caller instead
1571 * @param callback Callback to invoke when the request completes,
1572 * null for no callback
1573 * @param handler {@link Handler} identifying the callback thread,
1574 * null for the main thread
1575 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1576 * with these fields if activity or password was supplied and
1577 * the account was successfully verified:
1578 * <ul>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001579 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001580 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1581 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1582 * </ul>
1583 *
1584 * If no activity or password was specified, the returned Bundle contains
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001585 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1586 * password prompt.
1587 *
1588 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001589 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001590 * credential was validated/created.
1591 *
1592 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001593 * <ul>
1594 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1595 * <li> {@link OperationCanceledException} if the operation was canceled for
1596 * any reason, including the user canceling the password prompt
1597 * <li> {@link IOException} if the authenticator experienced an I/O problem
1598 * verifying the password, usually because of network trouble
1599 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001600 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001601 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1602 final Bundle options,
1603 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001604 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001605 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001606 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1607 Process.myUserHandle());
1608 }
1609
1610 /**
1611 * @hide
1612 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1613 * but for the specified user.
1614 */
1615 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1616 final Bundle options,
1617 final Activity activity,
1618 final AccountManagerCallback<Bundle> callback,
1619 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001620 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001621 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001622 return new AmsTask(activity, handler, callback) {
1623 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001624 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1625 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001626 }
Fred Quintana33269202009-04-20 16:05:10 -07001627 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001628 }
1629
Fred Quintana756b7352009-10-21 13:43:10 -07001630 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001631 * Asks the user to enter a new password for an account, updating the
1632 * saved credentials for the account. Normally this happens automatically
1633 * when the server rejects credentials during an auth token fetch, but this
1634 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001635 *
Dan Egnor661f0132010-02-19 11:23:00 -08001636 * <p>This method may be called from any thread, but the returned
1637 * {@link AccountManagerFuture} must not be used on the main thread.
1638 *
1639 * <p>This method requires the caller to hold the permission
1640 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1641 *
1642 * @param account The account to update credentials for
1643 * @param authTokenType The credentials entered must allow an auth token
1644 * of this type to be created (but no actual auth token is returned);
1645 * may be null
1646 * @param options Authenticator-specific options for the request;
1647 * may be null or empty
1648 * @param activity The {@link Activity} context to use for launching a new
1649 * authenticator-defined sub-Activity to prompt the user to enter a
1650 * password; used only to call startActivity(); if null, the prompt
1651 * will not be launched directly, but the necessary {@link Intent}
1652 * will be returned to the caller instead
1653 * @param callback Callback to invoke when the request completes,
1654 * null for no callback
1655 * @param handler {@link Handler} identifying the callback thread,
1656 * null for the main thread
1657 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1658 * with these fields if an activity was supplied and the account
1659 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001660 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001661 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1662 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001663 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001664 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001665 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08001666 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001667 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07001668 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001669 * <ul>
1670 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1671 * <li> {@link OperationCanceledException} if the operation was canceled for
1672 * any reason, including the user canceling the password prompt
1673 * <li> {@link IOException} if the authenticator experienced an I/O problem
1674 * verifying the password, usually because of network trouble
1675 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001676 */
1677 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1678 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001679 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001680 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001681 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001682 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001683 return new AmsTask(activity, handler, callback) {
1684 public void doWork() throws RemoteException {
1685 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001686 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001687 }
Fred Quintana33269202009-04-20 16:05:10 -07001688 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001689 }
1690
Fred Quintana756b7352009-10-21 13:43:10 -07001691 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001692 * Offers the user an opportunity to change an authenticator's settings.
1693 * These properties are for the authenticator in general, not a particular
1694 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001695 *
Dan Egnor661f0132010-02-19 11:23:00 -08001696 * <p>This method may be called from any thread, but the returned
1697 * {@link AccountManagerFuture} must not be used on the main thread.
1698 *
1699 * <p>This method requires the caller to hold the permission
1700 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1701 *
1702 * @param accountType The account type associated with the authenticator
1703 * to adjust
1704 * @param activity The {@link Activity} context to use for launching a new
1705 * authenticator-defined sub-Activity to adjust authenticator settings;
1706 * used only to call startActivity(); if null, the settings dialog will
1707 * not be launched directly, but the necessary {@link Intent} will be
1708 * returned to the caller instead
1709 * @param callback Callback to invoke when the request completes,
1710 * null for no callback
1711 * @param handler {@link Handler} identifying the callback thread,
1712 * null for the main thread
1713 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1714 * which is empty if properties were edited successfully, or
1715 * if no activity was specified, contains only {@link #KEY_INTENT}
1716 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001717 * If an error occurred, {@link AccountManagerFuture#getResult()}
1718 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001719 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001720 * <li> {@link AuthenticatorException} if no authenticator was registered for
1721 * this account type or the authenticator failed to respond
1722 * <li> {@link OperationCanceledException} if the operation was canceled for
1723 * any reason, including the user canceling the settings dialog
1724 * <li> {@link IOException} if the authenticator experienced an I/O problem
1725 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001726 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001727 */
1728 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1729 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001730 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001731 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001732 return new AmsTask(activity, handler, callback) {
1733 public void doWork() throws RemoteException {
1734 mService.editProperties(mResponse, accountType, activity != null);
1735 }
Fred Quintana33269202009-04-20 16:05:10 -07001736 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001737 }
1738
1739 private void ensureNotOnMainThread() {
1740 final Looper looper = Looper.myLooper();
1741 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001742 final IllegalStateException exception = new IllegalStateException(
1743 "calling this from your main thread can lead to deadlock");
1744 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1745 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001746 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1747 throw exception;
1748 }
Fred Quintana60307342009-03-24 22:48:12 -07001749 }
1750 }
1751
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001752 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1753 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001754 handler = handler == null ? mMainHandler : handler;
1755 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001756 public void run() {
1757 callback.run(future);
1758 }
1759 });
1760 }
Fred Quintana60307342009-03-24 22:48:12 -07001761
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001762 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001763 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001764 final Account[] accountsCopy = new Account[accounts.length];
1765 // send a copy to make sure that one doesn't
1766 // change what another sees
1767 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1768 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001769 handler.post(new Runnable() {
1770 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001771 try {
1772 listener.onAccountsUpdated(accountsCopy);
1773 } catch (SQLException e) {
1774 // Better luck next time. If the problem was disk-full,
1775 // the STORAGE_OK intent will re-trigger the update.
1776 Log.e(TAG, "Can't update accounts", e);
1777 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001778 }
1779 });
1780 }
1781
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001782 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001783 final IAccountManagerResponse mResponse;
1784 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001785 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001786 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001787 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001788 super(new Callable<Bundle>() {
1789 public Bundle call() throws Exception {
1790 throw new IllegalStateException("this should never be called");
1791 }
1792 });
1793
1794 mHandler = handler;
1795 mCallback = callback;
1796 mActivity = activity;
1797 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001798 }
1799
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001800 public final AccountManagerFuture<Bundle> start() {
1801 try {
1802 doWork();
1803 } catch (RemoteException e) {
1804 setException(e);
1805 }
Fred Quintana33269202009-04-20 16:05:10 -07001806 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001807 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001808
Fred Quintana96580e02010-03-04 13:42:42 -08001809 protected void set(Bundle bundle) {
1810 // TODO: somehow a null is being set as the result of the Future. Log this
1811 // case to help debug where this is occurring. When this bug is fixed this
1812 // condition statement should be removed.
1813 if (bundle == null) {
1814 Log.e(TAG, "the bundle must not be null", new Exception());
1815 }
1816 super.set(bundle);
1817 }
1818
Fred Quintanaa698f422009-04-08 19:14:54 -07001819 public abstract void doWork() throws RemoteException;
1820
1821 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1822 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001823 if (!isDone()) {
1824 ensureNotOnMainThread();
1825 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001826 try {
1827 if (timeout == null) {
1828 return get();
1829 } else {
1830 return get(timeout, unit);
1831 }
1832 } catch (CancellationException e) {
1833 throw new OperationCanceledException();
1834 } catch (TimeoutException e) {
1835 // fall through and cancel
1836 } catch (InterruptedException e) {
1837 // fall through and cancel
1838 } catch (ExecutionException e) {
1839 final Throwable cause = e.getCause();
1840 if (cause instanceof IOException) {
1841 throw (IOException) cause;
1842 } else if (cause instanceof UnsupportedOperationException) {
1843 throw new AuthenticatorException(cause);
1844 } else if (cause instanceof AuthenticatorException) {
1845 throw (AuthenticatorException) cause;
1846 } else if (cause instanceof RuntimeException) {
1847 throw (RuntimeException) cause;
1848 } else if (cause instanceof Error) {
1849 throw (Error) cause;
1850 } else {
1851 throw new IllegalStateException(cause);
1852 }
1853 } finally {
1854 cancel(true /* interrupt if running */);
1855 }
1856 throw new OperationCanceledException();
1857 }
1858
1859 public Bundle getResult()
1860 throws OperationCanceledException, IOException, AuthenticatorException {
1861 return internalGetResult(null, null);
1862 }
1863
1864 public Bundle getResult(long timeout, TimeUnit unit)
1865 throws OperationCanceledException, IOException, AuthenticatorException {
1866 return internalGetResult(timeout, unit);
1867 }
1868
1869 protected void done() {
1870 if (mCallback != null) {
1871 postToHandler(mHandler, mCallback, this);
1872 }
1873 }
1874
1875 /** Handles the responses from the AccountManager */
1876 private class Response extends IAccountManagerResponse.Stub {
1877 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07001878 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07001879 if (intent != null && mActivity != null) {
1880 // since the user provided an Activity we will silently start intents
1881 // that we see
1882 mActivity.startActivity(intent);
1883 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001884 } else if (bundle.getBoolean("retry")) {
1885 try {
1886 doWork();
1887 } catch (RemoteException e) {
1888 // this will only happen if the system process is dead, which means
1889 // we will be dying ourselves
1890 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001891 } else {
1892 set(bundle);
1893 }
1894 }
1895
1896 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001897 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1898 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1899 // the authenticator indicated that this request was canceled or we were
1900 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001901 cancel(true /* mayInterruptIfRunning */);
1902 return;
1903 }
1904 setException(convertErrorToException(code, message));
1905 }
1906 }
1907
Fred Quintana60307342009-03-24 22:48:12 -07001908 }
1909
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001910 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1911 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001912 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001913
1914 public BaseFutureTask(Handler handler) {
1915 super(new Callable<T>() {
1916 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001917 throw new IllegalStateException("this should never be called");
1918 }
1919 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001920 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001921 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001922 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001923
1924 public abstract void doWork() throws RemoteException;
1925
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001926 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001927
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001928 protected void postRunnableToHandler(Runnable runnable) {
1929 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1930 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001931 }
1932
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001933 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001934 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001935 doWork();
1936 } catch (RemoteException e) {
1937 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001938 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001939 }
1940
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001941 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001942 public void onResult(Bundle bundle) {
1943 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001944 T result = bundleToResult(bundle);
1945 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001946 return;
1947 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001948 set(result);
1949 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001950 } catch (ClassCastException e) {
1951 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001952 } catch (AuthenticatorException e) {
1953 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001954 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001955 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001956 }
1957
1958 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001959 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1960 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1961 // the authenticator indicated that this request was canceled or we were
1962 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001963 cancel(true /* mayInterruptIfRunning */);
1964 return;
1965 }
1966 setException(convertErrorToException(code, message));
1967 }
1968 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001969 }
1970
1971 private abstract class Future2Task<T>
1972 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1973 final AccountManagerCallback<T> mCallback;
1974 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1975 super(handler);
1976 mCallback = callback;
1977 }
1978
1979 protected void done() {
1980 if (mCallback != null) {
1981 postRunnableToHandler(new Runnable() {
1982 public void run() {
1983 mCallback.run(Future2Task.this);
1984 }
1985 });
1986 }
1987 }
1988
1989 public Future2Task<T> start() {
1990 startTask();
1991 return this;
1992 }
1993
1994 private T internalGetResult(Long timeout, TimeUnit unit)
1995 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001996 if (!isDone()) {
1997 ensureNotOnMainThread();
1998 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001999 try {
2000 if (timeout == null) {
2001 return get();
2002 } else {
2003 return get(timeout, unit);
2004 }
2005 } catch (InterruptedException e) {
2006 // fall through and cancel
2007 } catch (TimeoutException e) {
2008 // fall through and cancel
2009 } catch (CancellationException e) {
2010 // fall through and cancel
2011 } catch (ExecutionException e) {
2012 final Throwable cause = e.getCause();
2013 if (cause instanceof IOException) {
2014 throw (IOException) cause;
2015 } else if (cause instanceof UnsupportedOperationException) {
2016 throw new AuthenticatorException(cause);
2017 } else if (cause instanceof AuthenticatorException) {
2018 throw (AuthenticatorException) cause;
2019 } else if (cause instanceof RuntimeException) {
2020 throw (RuntimeException) cause;
2021 } else if (cause instanceof Error) {
2022 throw (Error) cause;
2023 } else {
2024 throw new IllegalStateException(cause);
2025 }
2026 } finally {
2027 cancel(true /* interrupt if running */);
2028 }
2029 throw new OperationCanceledException();
2030 }
2031
2032 public T getResult()
2033 throws OperationCanceledException, IOException, AuthenticatorException {
2034 return internalGetResult(null, null);
2035 }
2036
2037 public T getResult(long timeout, TimeUnit unit)
2038 throws OperationCanceledException, IOException, AuthenticatorException {
2039 return internalGetResult(timeout, unit);
2040 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002041
Fred Quintana60307342009-03-24 22:48:12 -07002042 }
2043
Fred Quintanaa698f422009-04-08 19:14:54 -07002044 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002045 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002046 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002047 }
Fred Quintana60307342009-03-24 22:48:12 -07002048
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002049 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002050 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002051 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002052
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002053 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002054 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002055 }
2056
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002057 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002058 return new IllegalArgumentException(message);
2059 }
2060
2061 return new AuthenticatorException(message);
2062 }
2063
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002064 private class GetAuthTokenByTypeAndFeaturesTask
2065 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002066 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2067 final String[] features, Activity activityForPrompting,
2068 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002069 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002070 super(activityForPrompting, handler, callback);
2071 if (accountType == null) throw new IllegalArgumentException("account type is null");
2072 mAccountType = accountType;
2073 mAuthTokenType = authTokenType;
2074 mFeatures = features;
2075 mAddAccountOptions = addAccountOptions;
2076 mLoginOptions = loginOptions;
2077 mMyCallback = this;
2078 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002079 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002080 final String mAccountType;
2081 final String mAuthTokenType;
2082 final String[] mFeatures;
2083 final Bundle mAddAccountOptions;
2084 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002085 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002086 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002087
2088 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002089 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2090 new AccountManagerCallback<Account[]>() {
2091 public void run(AccountManagerFuture<Account[]> future) {
2092 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07002093 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002094 accounts = future.getResult();
2095 } catch (OperationCanceledException e) {
2096 setException(e);
2097 return;
2098 } catch (IOException e) {
2099 setException(e);
2100 return;
2101 } catch (AuthenticatorException e) {
2102 setException(e);
2103 return;
Fred Quintana33269202009-04-20 16:05:10 -07002104 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002105
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002106 mNumAccounts = accounts.length;
2107
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002108 if (accounts.length == 0) {
2109 if (mActivity != null) {
2110 // no accounts, add one now. pretend that the user directly
2111 // made this request
2112 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2113 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2114 } else {
2115 // send result since we can't prompt to add an account
2116 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002117 result.putString(KEY_ACCOUNT_NAME, null);
2118 result.putString(KEY_ACCOUNT_TYPE, null);
2119 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002120 try {
2121 mResponse.onResult(result);
2122 } catch (RemoteException e) {
2123 // this will never happen
2124 }
2125 // we are done
2126 }
2127 } else if (accounts.length == 1) {
2128 // have a single account, return an authtoken for it
2129 if (mActivity == null) {
2130 mFuture = getAuthToken(accounts[0], mAuthTokenType,
2131 false /* notifyAuthFailure */, mMyCallback, mHandler);
2132 } else {
2133 mFuture = getAuthToken(accounts[0],
2134 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002135 mActivity, mMyCallback, mHandler);
2136 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002137 } else {
2138 if (mActivity != null) {
2139 IAccountManagerResponse chooseResponse =
2140 new IAccountManagerResponse.Stub() {
2141 public void onResult(Bundle value) throws RemoteException {
2142 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002143 value.getString(KEY_ACCOUNT_NAME),
2144 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002145 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2146 mActivity, mMyCallback, mHandler);
2147 }
Fred Quintana33269202009-04-20 16:05:10 -07002148
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002149 public void onError(int errorCode, String errorMessage)
2150 throws RemoteException {
2151 mResponse.onError(errorCode, errorMessage);
2152 }
2153 };
2154 // have many accounts, launch the chooser
2155 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002156 ComponentName componentName = ComponentName.unflattenFromString(
2157 Resources.getSystem().getString(
2158 R.string.config_chooseAccountActivity));
2159 intent.setClassName(componentName.getPackageName(),
2160 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002161 intent.putExtra(KEY_ACCOUNTS, accounts);
2162 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002163 new AccountManagerResponse(chooseResponse));
2164 mActivity.startActivity(intent);
2165 // the result will arrive via the IAccountManagerResponse
2166 } else {
2167 // send result since we can't prompt to select an account
2168 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002169 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002170 try {
2171 mResponse.onResult(result);
2172 } catch (RemoteException e) {
2173 // this will never happen
2174 }
2175 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07002176 }
Fred Quintana33269202009-04-20 16:05:10 -07002177 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002178 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002179 }
2180
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002181 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002182 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002183 final Bundle result = future.getResult();
2184 if (mNumAccounts == 0) {
2185 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2186 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2187 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2188 setException(new AuthenticatorException("account not in result"));
2189 return;
2190 }
2191 final Account account = new Account(accountName, accountType);
2192 mNumAccounts = 1;
2193 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2194 mMyCallback, mHandler);
2195 return;
2196 }
2197 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002198 } catch (OperationCanceledException e) {
2199 cancel(true /* mayInterruptIfRUnning */);
2200 } catch (IOException e) {
2201 setException(e);
2202 } catch (AuthenticatorException e) {
2203 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002204 }
2205 }
2206 }
2207
Fred Quintana756b7352009-10-21 13:43:10 -07002208 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002209 * This convenience helper combines the functionality of
2210 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2211 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002212 *
Dan Egnor661f0132010-02-19 11:23:00 -08002213 * <p>This method gets a list of the accounts matching the
2214 * specified type and feature set; if there is exactly one, it is
2215 * used; if there are more than one, the user is prompted to pick one;
2216 * if there are none, the user is prompted to add one. Finally,
2217 * an auth token is acquired for the chosen account.
2218 *
2219 * <p>This method may be called from any thread, but the returned
2220 * {@link AccountManagerFuture} must not be used on the main thread.
2221 *
2222 * <p>This method requires the caller to hold the permission
2223 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
2224 *
2225 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08002226 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08002227 * @param authTokenType The desired auth token type
2228 * (see {@link #getAuthToken}), must not be null
2229 * @param features Required features for the account
2230 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2231 * @param activity The {@link Activity} context to use for launching new
2232 * sub-Activities to prompt to add an account, select an account,
2233 * and/or enter a password, as necessary; used only to call
2234 * startActivity(); should not be null
2235 * @param addAccountOptions Authenticator-specific options to use for
2236 * adding new accounts; may be null or empty
2237 * @param getAuthTokenOptions Authenticator-specific options to use for
2238 * getting auth tokens; may be null or empty
2239 * @param callback Callback to invoke when the request completes,
2240 * null for no callback
2241 * @param handler {@link Handler} identifying the callback thread,
2242 * null for the main thread
2243 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2244 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07002245 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002246 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2247 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2248 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07002249 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002250 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07002251 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002252 * <ul>
2253 * <li> {@link AuthenticatorException} if no authenticator was registered for
2254 * this account type or the authenticator failed to respond
2255 * <li> {@link OperationCanceledException} if the operation was canceled for
2256 * any reason, including the user canceling any operation
2257 * <li> {@link IOException} if the authenticator experienced an I/O problem
2258 * updating settings, usually because of network trouble
2259 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002260 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002261 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002262 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002263 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07002264 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002265 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002266 if (accountType == null) throw new IllegalArgumentException("account type is null");
2267 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002268 final GetAuthTokenByTypeAndFeaturesTask task =
2269 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002270 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002271 task.start();
2272 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002273 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002274
Fred Quintana1121bb52011-09-14 23:19:35 -07002275 /**
2276 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2277 * accounts.
2278 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002279 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002280 * <p>
2281 * On success the activity returns a Bundle with the account name and type specified using
2282 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2283 * <p>
2284 * The most common case is to call this with one account type, e.g.:
2285 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002286 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002287 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002288 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2289 * selected one, according to the caller's definition of selected.
2290 * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
2291 * shown. If not specified then this field will not limit the displayed accounts.
2292 * @param allowableAccountTypes an optional string array of account types. These are used
2293 * both to filter the shown accounts and to filter the list of account types that are shown
2294 * when adding an account.
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002295 * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
2296 * it is only shown when there is more than one account from which to choose
Fred Quintanad88324d2011-09-19 11:43:05 -07002297 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002298 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002299 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2300 * authTokenType parameter
2301 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2302 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002303 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002304 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002305 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002306 */
2307 static public Intent newChooseAccountIntent(Account selectedAccount,
2308 ArrayList<Account> allowableAccounts,
2309 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002310 boolean alwaysPromptForAccount,
2311 String descriptionOverrideText,
2312 String addAccountAuthTokenType,
2313 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002314 Bundle addAccountOptions) {
2315 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002316 ComponentName componentName = ComponentName.unflattenFromString(
2317 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2318 intent.setClassName(componentName.getPackageName(),
2319 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002320 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
2321 allowableAccounts);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002322 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2323 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002324 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2325 addAccountOptions);
2326 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002327 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
2328 alwaysPromptForAccount);
2329 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2330 descriptionOverrideText);
2331 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2332 addAccountAuthTokenType);
2333 intent.putExtra(
2334 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2335 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002336 return intent;
2337 }
2338
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002339 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002340 Maps.newHashMap();
2341
Fred Quintanad9d2f112009-04-23 13:36:27 -07002342 /**
2343 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2344 * so that it can read the updated list of accounts and send them to the listener
2345 * in mAccountsUpdatedListeners.
2346 */
2347 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
2348 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002349 final Account[] accounts = getAccounts();
2350 // send the result to the listeners
2351 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002352 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002353 mAccountsUpdatedListeners.entrySet()) {
2354 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002355 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002356 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002357 }
2358 };
2359
2360 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002361 * Adds an {@link OnAccountsUpdateListener} to this instance of the
2362 * {@link AccountManager}. This listener will be notified whenever the
2363 * list of accounts on the device changes.
2364 *
2365 * <p>As long as this listener is present, the AccountManager instance
2366 * will not be garbage-collected, and neither will the {@link Context}
2367 * used to retrieve it, which may be a large Activity instance. To avoid
2368 * memory leaks, you must remove this listener before then. Normally
2369 * listeners are added in an Activity or Service's {@link Activity#onCreate}
2370 * and removed in {@link Activity#onDestroy}.
2371 *
2372 * <p>It is safe to call this method from the main thread.
2373 *
Nicolas Falliere9530e3a2012-06-18 17:21:06 -07002374 * <p>This method requires the caller to hold the permission
2375 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Dan Egnor661f0132010-02-19 11:23:00 -08002376 *
2377 * @param listener The listener to send notifications to
2378 * @param handler {@link Handler} identifying the thread to use
2379 * for notifications, null for the main thread
2380 * @param updateImmediately If true, the listener will be invoked
2381 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002382 * @throws IllegalArgumentException if listener is null
2383 * @throws IllegalStateException if listener was already added
2384 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002385 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002386 Handler handler, boolean updateImmediately) {
2387 if (listener == null) {
2388 throw new IllegalArgumentException("the listener is null");
2389 }
2390 synchronized (mAccountsUpdatedListeners) {
2391 if (mAccountsUpdatedListeners.containsKey(listener)) {
2392 throw new IllegalStateException("this listener is already added");
2393 }
2394 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2395
2396 mAccountsUpdatedListeners.put(listener, handler);
2397
2398 if (wasEmpty) {
2399 // Register a broadcast receiver to monitor account changes
2400 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002401 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002402 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002403 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002404 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2405 }
2406 }
2407
2408 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002409 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002410 }
2411 }
2412
2413 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002414 * Removes an {@link OnAccountsUpdateListener} previously registered with
2415 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2416 * receive notifications of account changes.
2417 *
2418 * <p>It is safe to call this method from the main thread.
2419 *
2420 * <p>No permission is required to call this method.
2421 *
2422 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002423 * @throws IllegalArgumentException if listener is null
2424 * @throws IllegalStateException if listener was not already added
2425 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002426 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002427 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002428 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002429 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002430 Log.e(TAG, "Listener was not previously added");
2431 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002432 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002433 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002434 if (mAccountsUpdatedListeners.isEmpty()) {
2435 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2436 }
2437 }
2438 }
Fred Quintana60307342009-03-24 22:48:12 -07002439}