blob: 81aa504e941aba5eb5f12cd52cda3ce31993af82 [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;
20import android.content.Intent;
Amith Yamasani12b8e132013-03-14 10:48:07 -070021import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070022import android.content.Context;
Fred Quintanad9d2f112009-04-23 13:36:27 -070023import android.content.IntentFilter;
24import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070025import android.content.res.Resources;
Costin Manolacheb6437242009-09-10 16:14:12 -070026import android.database.SQLException;
Fred Quintanaa698f422009-04-08 19:14:54 -070027import android.os.Bundle;
28import android.os.Handler;
29import android.os.Looper;
30import android.os.RemoteException;
Fred Quintana33269202009-04-20 16:05:10 -070031import android.os.Parcelable;
Fred Quintana751fdc02010-02-09 14:13:18 -080032import android.os.Build;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080033import android.os.Process;
34import android.os.UserHandle;
Costin Manolacheb6437242009-09-10 16:14:12 -070035import android.util.Log;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080036import android.text.TextUtils;
Fred Quintana60307342009-03-24 22:48:12 -070037
Fred Quintanaa698f422009-04-08 19:14:54 -070038import java.io.IOException;
Fred Quintana1121bb52011-09-14 23:19:35 -070039import java.util.ArrayList;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import java.util.concurrent.Callable;
41import java.util.concurrent.CancellationException;
42import java.util.concurrent.ExecutionException;
43import java.util.concurrent.FutureTask;
44import java.util.concurrent.TimeoutException;
45import java.util.concurrent.TimeUnit;
Fred Quintanad9d2f112009-04-23 13:36:27 -070046import java.util.HashMap;
47import java.util.Map;
48
Amith Yamasani12b8e132013-03-14 10:48:07 -070049import com.android.internal.R;
Fred Quintanad9d2f112009-04-23 13:36:27 -070050import com.google.android.collect.Maps;
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;
158
Dan Egnor661f0132010-02-19 11:23:00 -0800159 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700160 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800161 * from methods which return information about a particular account.
162 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700163 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800164
165 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700166 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800167 * from methods which return information about a particular account.
168 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700169 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800170
171 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700172 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800173 * from {@link #getAuthToken} and friends.
174 */
175 public static final String KEY_AUTHTOKEN = "authtoken";
176
177 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700178 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800179 * may require the caller to interact with the user. The Intent can
180 * be used to start the corresponding user interface activity.
181 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700182 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800183
184 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700185 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800186 * {@link #confirmCredentials}, rather than prompting the user with
187 * the standard password prompt.
188 */
189 public static final String KEY_PASSWORD = "password";
190
191 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700192
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700193 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
194 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800195 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700196 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
197 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800198 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
199 public static final String KEY_ERROR_CODE = "errorCode";
200 public static final String KEY_ERROR_MESSAGE = "errorMessage";
201 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700202
Costin Manolachea40c6302010-12-13 14:50:45 -0800203 /**
204 * Authenticators using 'customTokens' option will also get the UID of the
205 * caller
206 */
207 public static final String KEY_CALLER_UID = "callerUid";
208 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800209
Costin Manolached6060452011-01-24 16:11:36 -0800210 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700211 * The Android package of the caller will be set in the options bundle by the
212 * {@link AccountManager} and will be passed to the AccountManagerService and
213 * to the AccountAuthenticators. The uid of the caller will be known by the
214 * AccountManagerService as well as the AccountAuthenticators so they will be able to
215 * verify that the package is consistent with the uid (a uid might be shared by many
216 * packages).
217 */
218 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
219
220 /**
Costin Manolached6060452011-01-24 16:11:36 -0800221 * Boolean, if set and 'customTokens' the authenticator is responsible for
222 * notifications.
223 * @hide
224 */
225 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
226
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700227 public static final String ACTION_AUTHENTICATOR_INTENT =
228 "android.accounts.AccountAuthenticator";
229 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800230 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700231 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
232
Fred Quintana60307342009-03-24 22:48:12 -0700233 private final Context mContext;
234 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700235 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800236
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700237 /**
238 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800239 * when accounts are added, accounts are removed, or an
240 * account's credentials (saved password, etc) are changed.
241 *
242 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700243 */
244 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
245 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700246
Fred Quintana33269202009-04-20 16:05:10 -0700247 /**
248 * @hide
249 */
Fred Quintana60307342009-03-24 22:48:12 -0700250 public AccountManager(Context context, IAccountManager service) {
251 mContext = context;
252 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700253 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700254 }
255
Fred Quintana0eabf022009-04-27 15:08:17 -0700256 /**
257 * @hide used for testing only
258 */
259 public AccountManager(Context context, IAccountManager service, Handler handler) {
260 mContext = context;
261 mService = service;
262 mMainHandler = handler;
263 }
264
Fred Quintana756b7352009-10-21 13:43:10 -0700265 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800266 * @hide for internal use only
267 */
268 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700269 if (result != null) {
270 if (result.containsKey(KEY_AUTHTOKEN)
271 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
272 final Bundle newResult = new Bundle(result);
273 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
274 return newResult;
275 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800276 }
277 return result;
278 }
279
280 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800281 * Gets an AccountManager instance associated with a Context.
282 * The {@link Context} will be used as long as the AccountManager is
283 * active, so make sure to use a {@link Context} whose lifetime is
284 * commensurate with any listeners registered to
285 * {@link #addOnAccountsUpdatedListener} or similar methods.
286 *
287 * <p>It is safe to call this method from the main thread.
288 *
289 * <p>No permission is required to call this method.
290 *
Fred Quintana756b7352009-10-21 13:43:10 -0700291 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800292 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700293 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700294 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700295 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700296 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
297 }
298
Fred Quintana756b7352009-10-21 13:43:10 -0700299 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800300 * Gets the saved password associated with the account.
301 * This is intended for authenticators and related code; applications
302 * should get an auth token instead.
303 *
304 * <p>It is safe to call this method from the main thread.
305 *
306 * <p>This method requires the caller to hold the permission
307 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
308 * and to have the same UID as the account's authenticator.
309 *
310 * @param account The account to query for a password
311 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700312 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700313 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700314 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700315 try {
316 return mService.getPassword(account);
317 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700318 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700319 throw new RuntimeException(e);
320 }
321 }
322
Fred Quintana756b7352009-10-21 13:43:10 -0700323 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800324 * Gets the user data named by "key" associated with the account.
325 * This is intended for authenticators and related code to store
326 * arbitrary metadata along with accounts. The meaning of the keys
327 * and values is up to the authenticator for the account.
328 *
329 * <p>It is safe to call this method from the main thread.
330 *
331 * <p>This method requires the caller to hold the permission
332 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
333 * and to have the same UID as the account's authenticator.
334 *
335 * @param account The account to query for user data
336 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700337 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700338 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700339 if (account == null) throw new IllegalArgumentException("account is null");
340 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700341 try {
342 return mService.getUserData(account, key);
343 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700344 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700345 throw new RuntimeException(e);
346 }
347 }
348
Fred Quintana756b7352009-10-21 13:43:10 -0700349 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800350 * Lists the currently registered authenticators.
351 *
352 * <p>It is safe to call this method from the main thread.
353 *
354 * <p>No permission is required to call this method.
355 *
356 * @return An array of {@link AuthenticatorDescription} for every
357 * authenticator known to the AccountManager service. Empty (never
358 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700359 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700360 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700361 try {
362 return mService.getAuthenticatorTypes();
363 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700364 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700365 throw new RuntimeException(e);
366 }
367 }
368
Fred Quintana756b7352009-10-21 13:43:10 -0700369 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800370 * Lists all accounts of any type registered on the device.
371 * Equivalent to getAccountsByType(null).
372 *
373 * <p>It is safe to call this method from the main thread.
374 *
375 * <p>This method requires the caller to hold the permission
376 * {@link android.Manifest.permission#GET_ACCOUNTS}.
377 *
378 * @return An array of {@link Account}, one for each account. Empty
379 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700380 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700381 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700382 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700383 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700384 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700385 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700386 throw new RuntimeException(e);
387 }
388 }
389
Fred Quintana756b7352009-10-21 13:43:10 -0700390 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800391 * Lists all accounts of a particular type. The account type is a
392 * string token corresponding to the authenticator and useful domain
393 * of the account. For example, there are types corresponding to Google
394 * and Facebook. The exact string token to use will be published somewhere
395 * associated with the authenticator in question.
396 *
397 * <p>It is safe to call this method from the main thread.
398 *
399 * <p>This method requires the caller to hold the permission
400 * {@link android.Manifest.permission#GET_ACCOUNTS}.
401 *
402 * @param type The type of accounts to return, null to retrieve all accounts
403 * @return An array of {@link Account}, one per matching account. Empty
404 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700405 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700406 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800407 return getAccountsByTypeAsUser(type, Process.myUserHandle());
408 }
409
410 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
411 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700412 try {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800413 return mService.getAccountsAsUser(type, userHandle.getIdentifier());
Fred Quintana60307342009-03-24 22:48:12 -0700414 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700415 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700416 throw new RuntimeException(e);
417 }
418 }
419
Fred Quintana756b7352009-10-21 13:43:10 -0700420 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700421 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
422 * for an account.
423 * <p>
424 * This is only meant to be used by system activities and is not in the SDK.
425 * @param account The account whose permissions are being modified
426 * @param authTokenType The type of token whose permissions are being modified
427 * @param uid The uid that identifies the app which is being granted or revoked permission.
428 * @param value true is permission is being granted, false for revoked
429 * @hide
430 */
431 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
432 try {
433 mService.updateAppPermission(account, authTokenType, uid, value);
434 } catch (RemoteException e) {
435 // won't ever happen
436 throw new RuntimeException(e);
437 }
438 }
439
440 /**
441 * Get the user-friendly label associated with an authenticator's auth token.
442 * @param accountType the type of the authenticator. must not be null.
443 * @param authTokenType the token type. must not be null.
444 * @param callback callback to invoke when the result is available. may be null.
445 * @param handler the handler on which to invoke the callback, or null for the main thread
446 * @return a future containing the label string
447 * @hide
448 */
449 public AccountManagerFuture<String> getAuthTokenLabel(
450 final String accountType, final String authTokenType,
451 AccountManagerCallback<String> callback, Handler handler) {
452 if (accountType == null) throw new IllegalArgumentException("accountType is null");
453 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
454 return new Future2Task<String>(handler, callback) {
455 public void doWork() throws RemoteException {
456 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
457 }
458
459 @Override
460 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
461 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
462 throw new AuthenticatorException("no result in response");
463 }
464 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
465 }
466 }.start();
467 }
468
469 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800470 * Finds out whether a particular account has all the specified features.
471 * Account features are authenticator-specific string tokens identifying
472 * boolean account properties. For example, features are used to tell
473 * whether Google accounts have a particular service (such as Google
474 * Calendar or Google Talk) enabled. The feature names and their meanings
475 * are published somewhere associated with the authenticator in question.
476 *
477 * <p>This method may be called from any thread, but the returned
478 * {@link AccountManagerFuture} must not be used on the main thread.
479 *
480 * <p>This method requires the caller to hold the permission
481 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800482 *
483 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800484 * @param features An array of the account features to check
485 * @param callback Callback to invoke when the request completes,
486 * null for no callback
487 * @param handler {@link Handler} identifying the callback thread,
488 * null for the main thread
489 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
490 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800491 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800492 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800493 final String[] features,
494 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700495 if (account == null) throw new IllegalArgumentException("account is null");
496 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800497 return new Future2Task<Boolean>(handler, callback) {
498 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800499 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800500 }
501 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
502 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
503 throw new AuthenticatorException("no result in response");
504 }
505 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
506 }
507 }.start();
508 }
509
510 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800511 * Lists all accounts of a type which have certain features. The account
512 * type identifies the authenticator (see {@link #getAccountsByType}).
513 * Account features are authenticator-specific string tokens identifying
514 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700515 *
Dan Egnor661f0132010-02-19 11:23:00 -0800516 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
517 * which may contact the server or do other work to check account features,
518 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700519 *
Dan Egnor661f0132010-02-19 11:23:00 -0800520 * <p>This method may be called from any thread, but the returned
521 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700522 *
Dan Egnor661f0132010-02-19 11:23:00 -0800523 * <p>This method requires the caller to hold the permission
524 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700525 *
Dan Egnor661f0132010-02-19 11:23:00 -0800526 * @param type The type of accounts to return, must not be null
527 * @param features An array of the account features to require,
528 * may be null or empty
529 * @param callback Callback to invoke when the request completes,
530 * null for no callback
531 * @param handler {@link Handler} identifying the callback thread,
532 * null for the main thread
533 * @return An {@link AccountManagerFuture} which resolves to an array of
534 * {@link Account}, one per account of the specified type which
535 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800536 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700537 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
538 final String type, final String[] features,
539 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700540 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700541 return new Future2Task<Account[]>(handler, callback) {
542 public void doWork() throws RemoteException {
543 mService.getAccountsByFeatures(mResponse, type, features);
544 }
545 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700546 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700547 throw new AuthenticatorException("no result in response");
548 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700549 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700550 Account[] descs = new Account[parcelables.length];
551 for (int i = 0; i < parcelables.length; i++) {
552 descs[i] = (Account) parcelables[i];
553 }
554 return descs;
555 }
556 }.start();
557 }
558
Fred Quintana756b7352009-10-21 13:43:10 -0700559 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800560 * Adds an account directly to the AccountManager. Normally used by sign-up
561 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700562 *
Dan Egnor661f0132010-02-19 11:23:00 -0800563 * <p>It is safe to call this method from the main thread.
564 *
565 * <p>This method requires the caller to hold the permission
566 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
567 * and to have the same UID as the added account's authenticator.
568 *
569 * @param account The {@link Account} to add
570 * @param password The password to associate with the account, null for none
571 * @param userdata String values to use for the account's userdata, null for none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700572 * @return True if the account was successfully added, false if the account
Dan Egnor661f0132010-02-19 11:23:00 -0800573 * already exists, the account is null, or another error occurs.
574 */
575 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700576 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800577 try {
578 return mService.addAccount(account, password, userdata);
579 } catch (RemoteException e) {
580 // won't ever happen
581 throw new RuntimeException(e);
582 }
583 }
584
585 /**
586 * Removes an account from the AccountManager. Does nothing if the account
587 * does not exist. Does not delete the account from the server.
588 * The authenticator may have its own policies preventing account
589 * deletion, in which case the account will not be deleted.
590 *
591 * <p>This method may be called from any thread, but the returned
592 * {@link AccountManagerFuture} must not be used on the main thread.
593 *
594 * <p>This method requires the caller to hold the permission
595 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
596 *
597 * @param account The {@link Account} to remove
598 * @param callback Callback to invoke when the request completes,
599 * null for no callback
600 * @param handler {@link Handler} identifying the callback thread,
601 * null for the main thread
602 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
603 * true if the account has been successfully removed,
604 * false if the authenticator forbids deleting this account.
605 */
606 public AccountManagerFuture<Boolean> removeAccount(final Account account,
607 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700608 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800609 return new Future2Task<Boolean>(handler, callback) {
610 public void doWork() throws RemoteException {
611 mService.removeAccount(mResponse, account);
612 }
613 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
614 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
615 throw new AuthenticatorException("no result in response");
616 }
617 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
618 }
619 }.start();
620 }
621
622 /**
623 * Removes an auth token from the AccountManager's cache. Does nothing if
624 * the auth token is not currently in the cache. Applications must call this
625 * method when the auth token is found to have expired or otherwise become
626 * invalid for authenticating requests. The AccountManager does not validate
627 * or expire cached auth tokens otherwise.
628 *
629 * <p>It is safe to call this method from the main thread.
630 *
631 * <p>This method requires the caller to hold the permission
Fred Quintanab38eb142010-02-24 13:40:54 -0800632 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
633 * {@link android.Manifest.permission#USE_CREDENTIALS}
Dan Egnor661f0132010-02-19 11:23:00 -0800634 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700635 * @param accountType The account type of the auth token to invalidate, must not be null
636 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800637 */
638 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700639 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800640 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700641 if (authToken != null) {
642 mService.invalidateAuthToken(accountType, authToken);
643 }
Dan Egnor661f0132010-02-19 11:23:00 -0800644 } catch (RemoteException e) {
645 // won't ever happen
646 throw new RuntimeException(e);
647 }
648 }
649
650 /**
651 * Gets an auth token from the AccountManager's cache. If no auth
652 * token is cached for this account, null will be returned -- a new
653 * auth token will not be generated, and the server will not be contacted.
654 * Intended for use by the authenticator, not directly by applications.
655 *
656 * <p>It is safe to call this method from the main thread.
657 *
658 * <p>This method requires the caller to hold the permission
659 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
660 * and to have the same UID as the account's authenticator.
661 *
662 * @param account The account to fetch an auth token for
663 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
664 * @return The cached auth token for this account and type, or null if
665 * no auth token is cached or the account does not exist.
666 */
667 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700668 if (account == null) throw new IllegalArgumentException("account is null");
669 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800670 try {
671 return mService.peekAuthToken(account, authTokenType);
672 } catch (RemoteException e) {
673 // won't ever happen
674 throw new RuntimeException(e);
675 }
676 }
677
678 /**
679 * Sets or forgets a saved password. This modifies the local copy of the
680 * password used to automatically authenticate the user; it does
681 * not change the user's account password on the server. Intended for use
682 * by the authenticator, not directly by applications.
683 *
684 * <p>It is safe to call this method from the main thread.
685 *
686 * <p>This method requires the caller to hold the permission
687 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
688 * and have the same UID as the account's authenticator.
689 *
690 * @param account The account to set a password for
691 * @param password The password to set, null to clear the password
692 */
693 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700694 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800695 try {
696 mService.setPassword(account, password);
697 } catch (RemoteException e) {
698 // won't ever happen
699 throw new RuntimeException(e);
700 }
701 }
702
703 /**
704 * Forgets a saved password. This erases the local copy of the password;
705 * it does not change the user's account password on the server.
706 * Has the same effect as setPassword(account, null) but requires fewer
707 * permissions, and may be used by applications or management interfaces
708 * to "sign out" from an account.
709 *
710 * <p>It is safe to call this method from the main thread.
711 *
712 * <p>This method requires the caller to hold the permission
713 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
714 *
715 * @param account The account whose password to clear
716 */
717 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700718 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800719 try {
720 mService.clearPassword(account);
721 } catch (RemoteException e) {
722 // won't ever happen
723 throw new RuntimeException(e);
724 }
725 }
726
727 /**
728 * Sets one userdata key for an account. Intended by use for the
729 * authenticator to stash state for itself, not directly by applications.
730 * The meaning of the keys and values is up to the authenticator.
731 *
732 * <p>It is safe to call this method from the main thread.
733 *
734 * <p>This method requires the caller to hold the permission
735 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
736 * and to have the same UID as the account's authenticator.
737 *
738 * @param account The account to set the userdata for
739 * @param key The userdata key to set. Must not be null
740 * @param value The value to set, null to clear this userdata key
741 */
742 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -0700743 if (account == null) throw new IllegalArgumentException("account is null");
744 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800745 try {
746 mService.setUserData(account, key, value);
747 } catch (RemoteException e) {
748 // won't ever happen
749 throw new RuntimeException(e);
750 }
751 }
752
753 /**
754 * Adds an auth token to the AccountManager cache for an account.
755 * If the account does not exist then this call has no effect.
756 * Replaces any previous auth token for this account and auth token type.
757 * Intended for use by the authenticator, not directly by applications.
758 *
759 * <p>It is safe to call this method from the main thread.
760 *
761 * <p>This method requires the caller to hold the permission
762 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
763 * and to have the same UID as the account's authenticator.
764 *
765 * @param account The account to set an auth token for
766 * @param authTokenType The type of the auth token, see {#getAuthToken}
767 * @param authToken The auth token to add to the cache
768 */
769 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700770 if (account == null) throw new IllegalArgumentException("account is null");
771 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800772 try {
773 mService.setAuthToken(account, authTokenType, authToken);
774 } catch (RemoteException e) {
775 // won't ever happen
776 throw new RuntimeException(e);
777 }
778 }
779
780 /**
781 * This convenience helper synchronously gets an auth token with
782 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
783 *
784 * <p>This method may block while a network request completes, and must
785 * never be made from the main thread.
786 *
787 * <p>This method requires the caller to hold the permission
788 * {@link android.Manifest.permission#USE_CREDENTIALS}.
789 *
790 * @param account The account to fetch an auth token for
791 * @param authTokenType The auth token type, see {#link getAuthToken}
792 * @param notifyAuthFailure If true, display a notification and return null
793 * if authentication fails; if false, prompt and wait for the user to
794 * re-enter correct credentials before returning
795 * @return An auth token of the specified type for this account, or null
796 * if authentication fails or none can be fetched.
797 * @throws AuthenticatorException if the authenticator failed to respond
798 * @throws OperationCanceledException if the request was canceled for any
799 * reason, including the user canceling a credential request
800 * @throws java.io.IOException if the authenticator experienced an I/O problem
801 * creating a new auth token, usually because of network trouble
802 */
803 public String blockingGetAuthToken(Account account, String authTokenType,
804 boolean notifyAuthFailure)
805 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -0700806 if (account == null) throw new IllegalArgumentException("account is null");
807 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800808 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
809 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -0800810 if (bundle == null) {
811 // This should never happen, but it does, occasionally. If it does return null to
812 // signify that we were not able to get the authtoken.
813 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
814 // returned
815 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
816 + account + ", authTokenType " + authTokenType);
817 return null;
818 }
Dan Egnor661f0132010-02-19 11:23:00 -0800819 return bundle.getString(KEY_AUTHTOKEN);
820 }
821
822 /**
823 * Gets an auth token of the specified type for a particular account,
824 * prompting the user for credentials if necessary. This method is
825 * intended for applications running in the foreground where it makes
826 * sense to ask the user directly for a password.
827 *
828 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700829 * type, then it is returned. Otherwise, if a saved password is
830 * available, it is sent to the server to generate a new auth token.
831 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -0800832 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700833 * <p>Some authenticators have auth token <em>types</em>, whose value
834 * is authenticator-dependent. Some services use different token types to
835 * access different functionality -- for example, Google uses different auth
836 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -0800837 *
838 * <p>This method may be called from any thread, but the returned
839 * {@link AccountManagerFuture} must not be used on the main thread.
840 *
841 * <p>This method requires the caller to hold the permission
842 * {@link android.Manifest.permission#USE_CREDENTIALS}.
843 *
844 * @param account The account to fetch an auth token for
845 * @param authTokenType The auth token type, an authenticator-dependent
846 * string token, must not be null
847 * @param options Authenticator-specific options for the request,
848 * may be null or empty
849 * @param activity The {@link Activity} context to use for launching a new
850 * authenticator-defined sub-Activity to prompt the user for a password
851 * if necessary; used only to call startActivity(); must not be null.
852 * @param callback Callback to invoke when the request completes,
853 * null for no callback
854 * @param handler {@link Handler} identifying the callback thread,
855 * null for the main thread
856 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
857 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -0700858 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800859 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
860 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
861 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -0700862 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800863 *
864 * (Other authenticator-specific values may be returned.) If an auth token
865 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
866 * <ul>
867 * <li> {@link AuthenticatorException} if the authenticator failed to respond
868 * <li> {@link OperationCanceledException} if the operation is canceled for
869 * any reason, incluidng the user canceling a credential request
870 * <li> {@link IOException} if the authenticator experienced an I/O problem
871 * creating a new auth token, usually because of network trouble
872 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -0700873 * If the account is no longer present on the device, the return value is
874 * authenticator-dependent. The caller should verify the validity of the
875 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -0800876 */
877 public AccountManagerFuture<Bundle> getAuthToken(
878 final Account account, final String authTokenType, final Bundle options,
879 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700880 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800881 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -0700882 final Bundle optionsIn = new Bundle();
883 if (options != null) {
884 optionsIn.putAll(options);
885 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700886 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -0800887 return new AmsTask(activity, handler, callback) {
888 public void doWork() throws RemoteException {
889 mService.getAuthToken(mResponse, account, authTokenType,
890 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700891 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -0800892 }
893 }.start();
894 }
895
896 /**
897 * Gets an auth token of the specified type for a particular account,
898 * optionally raising a notification if the user must enter credentials.
899 * This method is intended for background tasks and services where the
900 * user should not be immediately interrupted with a password prompt.
901 *
902 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700903 * type, then it is returned. Otherwise, if a saved password is
904 * available, it is sent to the server to generate a new auth token.
905 * Otherwise, an {@link Intent} is returned which, when started, will
906 * prompt the user for a password. If the notifyAuthFailure parameter is
907 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -0800908 * alerting the user that they need to enter a password at some point.
909 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700910 * <p>In that case, you may need to wait until the user responds, which
911 * could take hours or days or forever. When the user does respond and
912 * supply a new password, the account manager will broadcast the
913 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
914 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -0800915 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700916 * <p>If notifyAuthFailure is not set, it is the application's
917 * responsibility to launch the returned Intent at some point.
918 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -0800919 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700920 * <p>Some authenticators have auth token <em>types</em>, whose value
921 * is authenticator-dependent. Some services use different token types to
922 * access different functionality -- for example, Google uses different auth
923 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -0800924 *
925 * <p>This method may be called from any thread, but the returned
926 * {@link AccountManagerFuture} must not be used on the main thread.
927 *
928 * <p>This method requires the caller to hold the permission
929 * {@link android.Manifest.permission#USE_CREDENTIALS}.
930 *
931 * @param account The account to fetch an auth token for
932 * @param authTokenType The auth token type, an authenticator-dependent
933 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -0800934 * @param notifyAuthFailure True to add a notification to prompt the
935 * user for a password if necessary, false to leave that to the caller
936 * @param callback Callback to invoke when the request completes,
937 * null for no callback
938 * @param handler {@link Handler} identifying the callback thread,
939 * null for the main thread
940 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
941 * at least the following fields on success:
942 * <ul>
943 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
944 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
945 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
946 * </ul>
947 *
948 * (Other authenticator-specific values may be returned.) If the user
949 * must enter credentials, the returned Bundle contains only
950 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
951 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700952 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -0800953 * <ul>
954 * <li> {@link AuthenticatorException} if the authenticator failed to respond
955 * <li> {@link OperationCanceledException} if the operation is canceled for
956 * any reason, incluidng the user canceling a credential request
957 * <li> {@link IOException} if the authenticator experienced an I/O problem
958 * creating a new auth token, usually because of network trouble
959 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -0700960 * If the account is no longer present on the device, the return value is
961 * authenticator-dependent. The caller should verify the validity of the
962 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -0700963 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
964 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -0800965 */
Fred Quintanaad93a322011-09-08 13:21:01 -0700966 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800967 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700968 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700969 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -0800970 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700971 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700972 handler);
Dan Egnor661f0132010-02-19 11:23:00 -0800973 }
974
975 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700976 * Gets an auth token of the specified type for a particular account,
977 * optionally raising a notification if the user must enter credentials.
978 * This method is intended for background tasks and services where the
979 * user should not be immediately interrupted with a password prompt.
980 *
981 * <p>If a previously generated auth token is cached for this account and
982 * type, then it is returned. Otherwise, if a saved password is
983 * available, it is sent to the server to generate a new auth token.
984 * Otherwise, an {@link Intent} is returned which, when started, will
985 * prompt the user for a password. If the notifyAuthFailure parameter is
986 * set, a status bar notification is also created with the same Intent,
987 * alerting the user that they need to enter a password at some point.
988 *
989 * <p>In that case, you may need to wait until the user responds, which
990 * could take hours or days or forever. When the user does respond and
991 * supply a new password, the account manager will broadcast the
992 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
993 * use to try again.
994 *
995 * <p>If notifyAuthFailure is not set, it is the application's
996 * responsibility to launch the returned Intent at some point.
997 * Either way, the result from this call will not wait for user action.
998 *
999 * <p>Some authenticators have auth token <em>types</em>, whose value
1000 * is authenticator-dependent. Some services use different token types to
1001 * access different functionality -- for example, Google uses different auth
1002 * tokens to access Gmail and Google Calendar for the same account.
1003 *
1004 * <p>This method may be called from any thread, but the returned
1005 * {@link AccountManagerFuture} must not be used on the main thread.
1006 *
1007 * <p>This method requires the caller to hold the permission
1008 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1009 *
1010 * @param account The account to fetch an auth token for
1011 * @param authTokenType The auth token type, an authenticator-dependent
1012 * string token, must not be null
1013 * @param options Authenticator-specific options for the request,
1014 * may be null or empty
1015 * @param notifyAuthFailure True to add a notification to prompt the
1016 * user for a password if necessary, false to leave that to the caller
1017 * @param callback Callback to invoke when the request completes,
1018 * null for no callback
1019 * @param handler {@link Handler} identifying the callback thread,
1020 * null for the main thread
1021 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1022 * at least the following fields on success:
1023 * <ul>
1024 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1025 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1026 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1027 * </ul>
1028 *
1029 * (Other authenticator-specific values may be returned.) If the user
1030 * must enter credentials, the returned Bundle contains only
1031 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1032 *
1033 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1034 * <ul>
1035 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1036 * <li> {@link OperationCanceledException} if the operation is canceled for
1037 * any reason, incluidng the user canceling a credential request
1038 * <li> {@link IOException} if the authenticator experienced an I/O problem
1039 * creating a new auth token, usually because of network trouble
1040 * </ul>
1041 * If the account is no longer present on the device, the return value is
1042 * authenticator-dependent. The caller should verify the validity of the
1043 * account before requesting an auth token.
1044 */
1045 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001046 final Account account, final String authTokenType, final Bundle options,
1047 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001048 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001049
Fred Quintanaad93a322011-09-08 13:21:01 -07001050 if (account == null) throw new IllegalArgumentException("account is null");
1051 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001052 final Bundle optionsIn = new Bundle();
1053 if (options != null) {
1054 optionsIn.putAll(options);
1055 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001056 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001057 return new AmsTask(null, handler, callback) {
1058 public void doWork() throws RemoteException {
1059 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001060 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001061 }
1062 }.start();
1063 }
1064
1065 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001066 * Asks the user to add an account of a specified type. The authenticator
1067 * for this account type processes this request with the appropriate user
1068 * interface. If the user does elect to create a new account, the account
1069 * name is returned.
1070 *
1071 * <p>This method may be called from any thread, but the returned
1072 * {@link AccountManagerFuture} must not be used on the main thread.
1073 *
1074 * <p>This method requires the caller to hold the permission
1075 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1076 *
1077 * @param accountType The type of account to add; must not be null
1078 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1079 * this account will need to be able to generate, null for none
1080 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1081 * account must have, null for none
1082 * @param addAccountOptions Authenticator-specific options for the request,
1083 * may be null or empty
1084 * @param activity The {@link Activity} context to use for launching a new
1085 * authenticator-defined sub-Activity to prompt the user to create an
1086 * account; used only to call startActivity(); if null, the prompt
1087 * will not be launched directly, but the necessary {@link Intent}
1088 * will be returned to the caller instead
1089 * @param callback Callback to invoke when the request completes,
1090 * null for no callback
1091 * @param handler {@link Handler} identifying the callback thread,
1092 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001093 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001094 * these fields if activity was specified and an account was created:
1095 * <ul>
1096 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1097 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1098 * </ul>
1099 *
1100 * If no activity was specified, the returned Bundle contains only
1101 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001102 * actual account creation process. If an error occurred,
1103 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001104 * <ul>
1105 * <li> {@link AuthenticatorException} if no authenticator was registered for
1106 * this account type or the authenticator failed to respond
1107 * <li> {@link OperationCanceledException} if the operation was canceled for
1108 * any reason, including the user canceling the creation process
1109 * <li> {@link IOException} if the authenticator experienced an I/O problem
1110 * creating a new account, usually because of network trouble
1111 * </ul>
1112 */
1113 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1114 final String authTokenType, final String[] requiredFeatures,
1115 final Bundle addAccountOptions,
1116 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001117 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001118 final Bundle optionsIn = new Bundle();
1119 if (addAccountOptions != null) {
1120 optionsIn.putAll(addAccountOptions);
1121 }
1122 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001123
Dan Egnor661f0132010-02-19 11:23:00 -08001124 return new AmsTask(activity, handler, callback) {
1125 public void doWork() throws RemoteException {
Dan Egnor661f0132010-02-19 11:23:00 -08001126 mService.addAcount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001127 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001128 }
1129 }.start();
1130 }
1131
1132 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001133 * Adds a shared account from the primary user to a secondary user. Adding the shared account
1134 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1135 * are attempted to be copied to the target user from the primary via calls to the
1136 * authenticator.
1137 * @param account the account to share
1138 * @param user the target user
1139 * @return
1140 * @hide
1141 */
1142 public boolean addSharedAccount(final Account account, UserHandle user) {
1143 try {
1144 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1145 return val;
1146 } catch (RemoteException re) {
1147 // won't ever happen
1148 throw new RuntimeException(re);
1149 }
1150 }
1151
1152 /**
1153 * @hide
1154 * Removes the shared account.
1155 * @param account the account to remove
1156 * @param user the user to remove the account from
1157 * @return
1158 */
1159 public boolean removeSharedAccount(final Account account, UserHandle user) {
1160 try {
1161 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1162 return val;
1163 } catch (RemoteException re) {
1164 // won't ever happen
1165 throw new RuntimeException(re);
1166 }
1167 }
1168
1169 /**
1170 * @hide
1171 * @param user
1172 * @return
1173 */
1174 public Account[] getSharedAccounts(UserHandle user) {
1175 try {
1176 return mService.getSharedAccountsAsUser(user.getIdentifier());
1177 } catch (RemoteException re) {
1178 // won't ever happen
1179 throw new RuntimeException(re);
1180 }
1181 }
1182
1183 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001184 * Confirms that the user knows the password for an account to make extra
1185 * sure they are the owner of the account. The user-entered password can
1186 * be supplied directly, otherwise the authenticator for this account type
1187 * prompts the user with the appropriate interface. This method is
1188 * intended for applications which want extra assurance; for example, the
1189 * phone lock screen uses this to let the user unlock the phone with an
1190 * account password if they forget the lock pattern.
1191 *
1192 * <p>If the user-entered password matches a saved password for this
1193 * account, the request is considered valid; otherwise the authenticator
1194 * verifies the password (usually by contacting the server).
1195 *
1196 * <p>This method may be called from any thread, but the returned
1197 * {@link AccountManagerFuture} must not be used on the main thread.
1198 *
1199 * <p>This method requires the caller to hold the permission
1200 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1201 *
1202 * @param account The account to confirm password knowledge for
1203 * @param options Authenticator-specific options for the request;
1204 * if the {@link #KEY_PASSWORD} string field is present, the
1205 * authenticator may use it directly rather than prompting the user;
1206 * may be null or empty
1207 * @param activity The {@link Activity} context to use for launching a new
1208 * authenticator-defined sub-Activity to prompt the user to enter a
1209 * password; used only to call startActivity(); if null, the prompt
1210 * will not be launched directly, but the necessary {@link Intent}
1211 * will be returned to the caller instead
1212 * @param callback Callback to invoke when the request completes,
1213 * null for no callback
1214 * @param handler {@link Handler} identifying the callback thread,
1215 * null for the main thread
1216 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1217 * with these fields if activity or password was supplied and
1218 * the account was successfully verified:
1219 * <ul>
1220 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1221 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1222 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1223 * </ul>
1224 *
1225 * If no activity or password was specified, the returned Bundle contains
1226 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001227 * password prompt. If an error occurred,
1228 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001229 * <ul>
1230 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1231 * <li> {@link OperationCanceledException} if the operation was canceled for
1232 * any reason, including the user canceling the password prompt
1233 * <li> {@link IOException} if the authenticator experienced an I/O problem
1234 * verifying the password, usually because of network trouble
1235 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001236 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001237 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1238 final Bundle options,
1239 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001240 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001241 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001242 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1243 Process.myUserHandle());
1244 }
1245
1246 /**
1247 * @hide
1248 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1249 * but for the specified user.
1250 */
1251 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1252 final Bundle options,
1253 final Activity activity,
1254 final AccountManagerCallback<Bundle> callback,
1255 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001256 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001257 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001258 return new AmsTask(activity, handler, callback) {
1259 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001260 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1261 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001262 }
Fred Quintana33269202009-04-20 16:05:10 -07001263 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001264 }
1265
Fred Quintana756b7352009-10-21 13:43:10 -07001266 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001267 * Asks the user to enter a new password for an account, updating the
1268 * saved credentials for the account. Normally this happens automatically
1269 * when the server rejects credentials during an auth token fetch, but this
1270 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001271 *
Dan Egnor661f0132010-02-19 11:23:00 -08001272 * <p>This method may be called from any thread, but the returned
1273 * {@link AccountManagerFuture} must not be used on the main thread.
1274 *
1275 * <p>This method requires the caller to hold the permission
1276 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1277 *
1278 * @param account The account to update credentials for
1279 * @param authTokenType The credentials entered must allow an auth token
1280 * of this type to be created (but no actual auth token is returned);
1281 * may be null
1282 * @param options Authenticator-specific options for the request;
1283 * may be null or empty
1284 * @param activity The {@link Activity} context to use for launching a new
1285 * authenticator-defined sub-Activity to prompt the user to enter a
1286 * password; used only to call startActivity(); if null, the prompt
1287 * will not be launched directly, but the necessary {@link Intent}
1288 * will be returned to the caller instead
1289 * @param callback Callback to invoke when the request completes,
1290 * null for no callback
1291 * @param handler {@link Handler} identifying the callback thread,
1292 * null for the main thread
1293 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1294 * with these fields if an activity was supplied and the account
1295 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001296 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001297 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1298 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001299 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001300 *
1301 * If no activity was specified, the returned Bundle contains only
1302 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001303 * password prompt. If an error occurred,
1304 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001305 * <ul>
1306 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1307 * <li> {@link OperationCanceledException} if the operation was canceled for
1308 * any reason, including the user canceling the password prompt
1309 * <li> {@link IOException} if the authenticator experienced an I/O problem
1310 * verifying the password, usually because of network trouble
1311 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001312 */
1313 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1314 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001315 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001316 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001317 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001318 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001319 return new AmsTask(activity, handler, callback) {
1320 public void doWork() throws RemoteException {
1321 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001322 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001323 }
Fred Quintana33269202009-04-20 16:05:10 -07001324 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001325 }
1326
Fred Quintana756b7352009-10-21 13:43:10 -07001327 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001328 * Offers the user an opportunity to change an authenticator's settings.
1329 * These properties are for the authenticator in general, not a particular
1330 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001331 *
Dan Egnor661f0132010-02-19 11:23:00 -08001332 * <p>This method may be called from any thread, but the returned
1333 * {@link AccountManagerFuture} must not be used on the main thread.
1334 *
1335 * <p>This method requires the caller to hold the permission
1336 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1337 *
1338 * @param accountType The account type associated with the authenticator
1339 * to adjust
1340 * @param activity The {@link Activity} context to use for launching a new
1341 * authenticator-defined sub-Activity to adjust authenticator settings;
1342 * used only to call startActivity(); if null, the settings dialog will
1343 * not be launched directly, but the necessary {@link Intent} will be
1344 * returned to the caller instead
1345 * @param callback Callback to invoke when the request completes,
1346 * null for no callback
1347 * @param handler {@link Handler} identifying the callback thread,
1348 * null for the main thread
1349 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1350 * which is empty if properties were edited successfully, or
1351 * if no activity was specified, contains only {@link #KEY_INTENT}
1352 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001353 * If an error occurred, {@link AccountManagerFuture#getResult()}
1354 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001355 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001356 * <li> {@link AuthenticatorException} if no authenticator was registered for
1357 * this account type or the authenticator failed to respond
1358 * <li> {@link OperationCanceledException} if the operation was canceled for
1359 * any reason, including the user canceling the settings dialog
1360 * <li> {@link IOException} if the authenticator experienced an I/O problem
1361 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001362 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001363 */
1364 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1365 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001367 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001368 return new AmsTask(activity, handler, callback) {
1369 public void doWork() throws RemoteException {
1370 mService.editProperties(mResponse, accountType, activity != null);
1371 }
Fred Quintana33269202009-04-20 16:05:10 -07001372 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001373 }
1374
1375 private void ensureNotOnMainThread() {
1376 final Looper looper = Looper.myLooper();
1377 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001378 final IllegalStateException exception = new IllegalStateException(
1379 "calling this from your main thread can lead to deadlock");
1380 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1381 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001382 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1383 throw exception;
1384 }
Fred Quintana60307342009-03-24 22:48:12 -07001385 }
1386 }
1387
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001388 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1389 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001390 handler = handler == null ? mMainHandler : handler;
1391 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001392 public void run() {
1393 callback.run(future);
1394 }
1395 });
1396 }
Fred Quintana60307342009-03-24 22:48:12 -07001397
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001398 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001399 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001400 final Account[] accountsCopy = new Account[accounts.length];
1401 // send a copy to make sure that one doesn't
1402 // change what another sees
1403 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1404 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001405 handler.post(new Runnable() {
1406 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001407 try {
1408 listener.onAccountsUpdated(accountsCopy);
1409 } catch (SQLException e) {
1410 // Better luck next time. If the problem was disk-full,
1411 // the STORAGE_OK intent will re-trigger the update.
1412 Log.e(TAG, "Can't update accounts", e);
1413 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001414 }
1415 });
1416 }
1417
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001418 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001419 final IAccountManagerResponse mResponse;
1420 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001421 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001422 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001423 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001424 super(new Callable<Bundle>() {
1425 public Bundle call() throws Exception {
1426 throw new IllegalStateException("this should never be called");
1427 }
1428 });
1429
1430 mHandler = handler;
1431 mCallback = callback;
1432 mActivity = activity;
1433 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001434 }
1435
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001436 public final AccountManagerFuture<Bundle> start() {
1437 try {
1438 doWork();
1439 } catch (RemoteException e) {
1440 setException(e);
1441 }
Fred Quintana33269202009-04-20 16:05:10 -07001442 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001443 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001444
Fred Quintana96580e02010-03-04 13:42:42 -08001445 protected void set(Bundle bundle) {
1446 // TODO: somehow a null is being set as the result of the Future. Log this
1447 // case to help debug where this is occurring. When this bug is fixed this
1448 // condition statement should be removed.
1449 if (bundle == null) {
1450 Log.e(TAG, "the bundle must not be null", new Exception());
1451 }
1452 super.set(bundle);
1453 }
1454
Fred Quintanaa698f422009-04-08 19:14:54 -07001455 public abstract void doWork() throws RemoteException;
1456
1457 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1458 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001459 if (!isDone()) {
1460 ensureNotOnMainThread();
1461 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001462 try {
1463 if (timeout == null) {
1464 return get();
1465 } else {
1466 return get(timeout, unit);
1467 }
1468 } catch (CancellationException e) {
1469 throw new OperationCanceledException();
1470 } catch (TimeoutException e) {
1471 // fall through and cancel
1472 } catch (InterruptedException e) {
1473 // fall through and cancel
1474 } catch (ExecutionException e) {
1475 final Throwable cause = e.getCause();
1476 if (cause instanceof IOException) {
1477 throw (IOException) cause;
1478 } else if (cause instanceof UnsupportedOperationException) {
1479 throw new AuthenticatorException(cause);
1480 } else if (cause instanceof AuthenticatorException) {
1481 throw (AuthenticatorException) cause;
1482 } else if (cause instanceof RuntimeException) {
1483 throw (RuntimeException) cause;
1484 } else if (cause instanceof Error) {
1485 throw (Error) cause;
1486 } else {
1487 throw new IllegalStateException(cause);
1488 }
1489 } finally {
1490 cancel(true /* interrupt if running */);
1491 }
1492 throw new OperationCanceledException();
1493 }
1494
1495 public Bundle getResult()
1496 throws OperationCanceledException, IOException, AuthenticatorException {
1497 return internalGetResult(null, null);
1498 }
1499
1500 public Bundle getResult(long timeout, TimeUnit unit)
1501 throws OperationCanceledException, IOException, AuthenticatorException {
1502 return internalGetResult(timeout, unit);
1503 }
1504
1505 protected void done() {
1506 if (mCallback != null) {
1507 postToHandler(mHandler, mCallback, this);
1508 }
1509 }
1510
1511 /** Handles the responses from the AccountManager */
1512 private class Response extends IAccountManagerResponse.Stub {
1513 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07001514 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07001515 if (intent != null && mActivity != null) {
1516 // since the user provided an Activity we will silently start intents
1517 // that we see
1518 mActivity.startActivity(intent);
1519 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001520 } else if (bundle.getBoolean("retry")) {
1521 try {
1522 doWork();
1523 } catch (RemoteException e) {
1524 // this will only happen if the system process is dead, which means
1525 // we will be dying ourselves
1526 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001527 } else {
1528 set(bundle);
1529 }
1530 }
1531
1532 public void onError(int code, String message) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001533 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001534 // the authenticator indicated that this request was canceled, do so now
1535 cancel(true /* mayInterruptIfRunning */);
1536 return;
1537 }
1538 setException(convertErrorToException(code, message));
1539 }
1540 }
1541
Fred Quintana60307342009-03-24 22:48:12 -07001542 }
1543
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001544 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1545 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001546 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001547
1548 public BaseFutureTask(Handler handler) {
1549 super(new Callable<T>() {
1550 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001551 throw new IllegalStateException("this should never be called");
1552 }
1553 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001554 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001555 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001556 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001557
1558 public abstract void doWork() throws RemoteException;
1559
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001560 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001561
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001562 protected void postRunnableToHandler(Runnable runnable) {
1563 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1564 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001565 }
1566
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001567 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001568 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001569 doWork();
1570 } catch (RemoteException e) {
1571 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001572 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001573 }
1574
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001575 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001576 public void onResult(Bundle bundle) {
1577 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001578 T result = bundleToResult(bundle);
1579 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001580 return;
1581 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001582 set(result);
1583 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001584 } catch (ClassCastException e) {
1585 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001586 } catch (AuthenticatorException e) {
1587 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001588 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001589 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001590 }
1591
1592 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001593 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001594 cancel(true /* mayInterruptIfRunning */);
1595 return;
1596 }
1597 setException(convertErrorToException(code, message));
1598 }
1599 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001600 }
1601
1602 private abstract class Future2Task<T>
1603 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1604 final AccountManagerCallback<T> mCallback;
1605 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1606 super(handler);
1607 mCallback = callback;
1608 }
1609
1610 protected void done() {
1611 if (mCallback != null) {
1612 postRunnableToHandler(new Runnable() {
1613 public void run() {
1614 mCallback.run(Future2Task.this);
1615 }
1616 });
1617 }
1618 }
1619
1620 public Future2Task<T> start() {
1621 startTask();
1622 return this;
1623 }
1624
1625 private T internalGetResult(Long timeout, TimeUnit unit)
1626 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001627 if (!isDone()) {
1628 ensureNotOnMainThread();
1629 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001630 try {
1631 if (timeout == null) {
1632 return get();
1633 } else {
1634 return get(timeout, unit);
1635 }
1636 } catch (InterruptedException e) {
1637 // fall through and cancel
1638 } catch (TimeoutException e) {
1639 // fall through and cancel
1640 } catch (CancellationException e) {
1641 // fall through and cancel
1642 } catch (ExecutionException e) {
1643 final Throwable cause = e.getCause();
1644 if (cause instanceof IOException) {
1645 throw (IOException) cause;
1646 } else if (cause instanceof UnsupportedOperationException) {
1647 throw new AuthenticatorException(cause);
1648 } else if (cause instanceof AuthenticatorException) {
1649 throw (AuthenticatorException) cause;
1650 } else if (cause instanceof RuntimeException) {
1651 throw (RuntimeException) cause;
1652 } else if (cause instanceof Error) {
1653 throw (Error) cause;
1654 } else {
1655 throw new IllegalStateException(cause);
1656 }
1657 } finally {
1658 cancel(true /* interrupt if running */);
1659 }
1660 throw new OperationCanceledException();
1661 }
1662
1663 public T getResult()
1664 throws OperationCanceledException, IOException, AuthenticatorException {
1665 return internalGetResult(null, null);
1666 }
1667
1668 public T getResult(long timeout, TimeUnit unit)
1669 throws OperationCanceledException, IOException, AuthenticatorException {
1670 return internalGetResult(timeout, unit);
1671 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001672
Fred Quintana60307342009-03-24 22:48:12 -07001673 }
1674
Fred Quintanaa698f422009-04-08 19:14:54 -07001675 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001676 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001677 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001678 }
Fred Quintana60307342009-03-24 22:48:12 -07001679
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001680 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07001681 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001682 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001683
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001684 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07001685 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07001686 }
1687
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001688 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07001689 return new IllegalArgumentException(message);
1690 }
1691
1692 return new AuthenticatorException(message);
1693 }
1694
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001695 private class GetAuthTokenByTypeAndFeaturesTask
1696 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07001697 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1698 final String[] features, Activity activityForPrompting,
1699 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001700 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001701 super(activityForPrompting, handler, callback);
1702 if (accountType == null) throw new IllegalArgumentException("account type is null");
1703 mAccountType = accountType;
1704 mAuthTokenType = authTokenType;
1705 mFeatures = features;
1706 mAddAccountOptions = addAccountOptions;
1707 mLoginOptions = loginOptions;
1708 mMyCallback = this;
1709 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001710 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07001711 final String mAccountType;
1712 final String mAuthTokenType;
1713 final String[] mFeatures;
1714 final Bundle mAddAccountOptions;
1715 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001716 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001717 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07001718
1719 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001720 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1721 new AccountManagerCallback<Account[]>() {
1722 public void run(AccountManagerFuture<Account[]> future) {
1723 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07001724 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001725 accounts = future.getResult();
1726 } catch (OperationCanceledException e) {
1727 setException(e);
1728 return;
1729 } catch (IOException e) {
1730 setException(e);
1731 return;
1732 } catch (AuthenticatorException e) {
1733 setException(e);
1734 return;
Fred Quintana33269202009-04-20 16:05:10 -07001735 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001736
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001737 mNumAccounts = accounts.length;
1738
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001739 if (accounts.length == 0) {
1740 if (mActivity != null) {
1741 // no accounts, add one now. pretend that the user directly
1742 // made this request
1743 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1744 mAddAccountOptions, mActivity, mMyCallback, mHandler);
1745 } else {
1746 // send result since we can't prompt to add an account
1747 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001748 result.putString(KEY_ACCOUNT_NAME, null);
1749 result.putString(KEY_ACCOUNT_TYPE, null);
1750 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001751 try {
1752 mResponse.onResult(result);
1753 } catch (RemoteException e) {
1754 // this will never happen
1755 }
1756 // we are done
1757 }
1758 } else if (accounts.length == 1) {
1759 // have a single account, return an authtoken for it
1760 if (mActivity == null) {
1761 mFuture = getAuthToken(accounts[0], mAuthTokenType,
1762 false /* notifyAuthFailure */, mMyCallback, mHandler);
1763 } else {
1764 mFuture = getAuthToken(accounts[0],
1765 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07001766 mActivity, mMyCallback, mHandler);
1767 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001768 } else {
1769 if (mActivity != null) {
1770 IAccountManagerResponse chooseResponse =
1771 new IAccountManagerResponse.Stub() {
1772 public void onResult(Bundle value) throws RemoteException {
1773 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001774 value.getString(KEY_ACCOUNT_NAME),
1775 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001776 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1777 mActivity, mMyCallback, mHandler);
1778 }
Fred Quintana33269202009-04-20 16:05:10 -07001779
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001780 public void onError(int errorCode, String errorMessage)
1781 throws RemoteException {
1782 mResponse.onError(errorCode, errorMessage);
1783 }
1784 };
1785 // have many accounts, launch the chooser
1786 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07001787 ComponentName componentName = ComponentName.unflattenFromString(
1788 Resources.getSystem().getString(
1789 R.string.config_chooseAccountActivity));
1790 intent.setClassName(componentName.getPackageName(),
1791 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001792 intent.putExtra(KEY_ACCOUNTS, accounts);
1793 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001794 new AccountManagerResponse(chooseResponse));
1795 mActivity.startActivity(intent);
1796 // the result will arrive via the IAccountManagerResponse
1797 } else {
1798 // send result since we can't prompt to select an account
1799 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001800 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001801 try {
1802 mResponse.onResult(result);
1803 } catch (RemoteException e) {
1804 // this will never happen
1805 }
1806 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07001807 }
Fred Quintana33269202009-04-20 16:05:10 -07001808 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001809 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07001810 }
1811
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001812 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07001813 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001814 final Bundle result = future.getResult();
1815 if (mNumAccounts == 0) {
1816 final String accountName = result.getString(KEY_ACCOUNT_NAME);
1817 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
1818 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
1819 setException(new AuthenticatorException("account not in result"));
1820 return;
1821 }
1822 final Account account = new Account(accountName, accountType);
1823 mNumAccounts = 1;
1824 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
1825 mMyCallback, mHandler);
1826 return;
1827 }
1828 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001829 } catch (OperationCanceledException e) {
1830 cancel(true /* mayInterruptIfRUnning */);
1831 } catch (IOException e) {
1832 setException(e);
1833 } catch (AuthenticatorException e) {
1834 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07001835 }
1836 }
1837 }
1838
Fred Quintana756b7352009-10-21 13:43:10 -07001839 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001840 * This convenience helper combines the functionality of
1841 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1842 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07001843 *
Dan Egnor661f0132010-02-19 11:23:00 -08001844 * <p>This method gets a list of the accounts matching the
1845 * specified type and feature set; if there is exactly one, it is
1846 * used; if there are more than one, the user is prompted to pick one;
1847 * if there are none, the user is prompted to add one. Finally,
1848 * an auth token is acquired for the chosen account.
1849 *
1850 * <p>This method may be called from any thread, but the returned
1851 * {@link AccountManagerFuture} must not be used on the main thread.
1852 *
1853 * <p>This method requires the caller to hold the permission
1854 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1855 *
1856 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08001857 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001858 * @param authTokenType The desired auth token type
1859 * (see {@link #getAuthToken}), must not be null
1860 * @param features Required features for the account
1861 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1862 * @param activity The {@link Activity} context to use for launching new
1863 * sub-Activities to prompt to add an account, select an account,
1864 * and/or enter a password, as necessary; used only to call
1865 * startActivity(); should not be null
1866 * @param addAccountOptions Authenticator-specific options to use for
1867 * adding new accounts; may be null or empty
1868 * @param getAuthTokenOptions Authenticator-specific options to use for
1869 * getting auth tokens; may be null or empty
1870 * @param callback Callback to invoke when the request completes,
1871 * null for no callback
1872 * @param handler {@link Handler} identifying the callback thread,
1873 * null for the main thread
1874 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1875 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001876 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001877 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1878 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1879 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001880 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001881 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001882 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001883 * <ul>
1884 * <li> {@link AuthenticatorException} if no authenticator was registered for
1885 * this account type or the authenticator failed to respond
1886 * <li> {@link OperationCanceledException} if the operation was canceled for
1887 * any reason, including the user canceling any operation
1888 * <li> {@link IOException} if the authenticator experienced an I/O problem
1889 * updating settings, usually because of network trouble
1890 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001891 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001892 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07001893 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08001894 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07001895 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001896 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001897 if (accountType == null) throw new IllegalArgumentException("account type is null");
1898 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001899 final GetAuthTokenByTypeAndFeaturesTask task =
1900 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08001901 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001902 task.start();
1903 return task;
Fred Quintana60307342009-03-24 22:48:12 -07001904 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001905
Fred Quintana1121bb52011-09-14 23:19:35 -07001906 /**
1907 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
1908 * accounts.
1909 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04001910 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07001911 * <p>
1912 * On success the activity returns a Bundle with the account name and type specified using
1913 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
1914 * <p>
1915 * The most common case is to call this with one account type, e.g.:
1916 * <p>
Fred Quintanad88324d2011-09-19 11:43:05 -07001917 * <pre> newChooseAccountsIntent(null, null, new String[]{"com.google"}, false, null,
1918 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07001919 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
1920 * selected one, according to the caller's definition of selected.
1921 * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
1922 * shown. If not specified then this field will not limit the displayed accounts.
1923 * @param allowableAccountTypes an optional string array of account types. These are used
1924 * both to filter the shown accounts and to filter the list of account types that are shown
1925 * when adding an account.
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001926 * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
1927 * it is only shown when there is more than one account from which to choose
Fred Quintanad88324d2011-09-19 11:43:05 -07001928 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001929 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07001930 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
1931 * authTokenType parameter
1932 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
1933 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001934 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07001935 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001936 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07001937 */
1938 static public Intent newChooseAccountIntent(Account selectedAccount,
1939 ArrayList<Account> allowableAccounts,
1940 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001941 boolean alwaysPromptForAccount,
1942 String descriptionOverrideText,
1943 String addAccountAuthTokenType,
1944 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07001945 Bundle addAccountOptions) {
1946 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07001947 ComponentName componentName = ComponentName.unflattenFromString(
1948 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
1949 intent.setClassName(componentName.getPackageName(),
1950 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07001951 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
1952 allowableAccounts);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001953 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
1954 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07001955 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
1956 addAccountOptions);
1957 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001958 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
1959 alwaysPromptForAccount);
1960 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
1961 descriptionOverrideText);
1962 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
1963 addAccountAuthTokenType);
1964 intent.putExtra(
1965 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
1966 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07001967 return intent;
1968 }
1969
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001970 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07001971 Maps.newHashMap();
1972
Fred Quintanad9d2f112009-04-23 13:36:27 -07001973 /**
1974 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1975 * so that it can read the updated list of accounts and send them to the listener
1976 * in mAccountsUpdatedListeners.
1977 */
1978 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1979 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001980 final Account[] accounts = getAccounts();
1981 // send the result to the listeners
1982 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001983 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001984 mAccountsUpdatedListeners.entrySet()) {
1985 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001986 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001987 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001988 }
1989 };
1990
1991 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001992 * Adds an {@link OnAccountsUpdateListener} to this instance of the
1993 * {@link AccountManager}. This listener will be notified whenever the
1994 * list of accounts on the device changes.
1995 *
1996 * <p>As long as this listener is present, the AccountManager instance
1997 * will not be garbage-collected, and neither will the {@link Context}
1998 * used to retrieve it, which may be a large Activity instance. To avoid
1999 * memory leaks, you must remove this listener before then. Normally
2000 * listeners are added in an Activity or Service's {@link Activity#onCreate}
2001 * and removed in {@link Activity#onDestroy}.
2002 *
2003 * <p>It is safe to call this method from the main thread.
2004 *
Nicolas Falliere9530e3a2012-06-18 17:21:06 -07002005 * <p>This method requires the caller to hold the permission
2006 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Dan Egnor661f0132010-02-19 11:23:00 -08002007 *
2008 * @param listener The listener to send notifications to
2009 * @param handler {@link Handler} identifying the thread to use
2010 * for notifications, null for the main thread
2011 * @param updateImmediately If true, the listener will be invoked
2012 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002013 * @throws IllegalArgumentException if listener is null
2014 * @throws IllegalStateException if listener was already added
2015 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002016 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002017 Handler handler, boolean updateImmediately) {
2018 if (listener == null) {
2019 throw new IllegalArgumentException("the listener is null");
2020 }
2021 synchronized (mAccountsUpdatedListeners) {
2022 if (mAccountsUpdatedListeners.containsKey(listener)) {
2023 throw new IllegalStateException("this listener is already added");
2024 }
2025 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2026
2027 mAccountsUpdatedListeners.put(listener, handler);
2028
2029 if (wasEmpty) {
2030 // Register a broadcast receiver to monitor account changes
2031 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002032 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002033 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002034 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002035 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2036 }
2037 }
2038
2039 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002040 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002041 }
2042 }
2043
2044 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002045 * Removes an {@link OnAccountsUpdateListener} previously registered with
2046 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2047 * receive notifications of account changes.
2048 *
2049 * <p>It is safe to call this method from the main thread.
2050 *
2051 * <p>No permission is required to call this method.
2052 *
2053 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002054 * @throws IllegalArgumentException if listener is null
2055 * @throws IllegalStateException if listener was not already added
2056 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002057 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002058 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002059 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002060 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002061 Log.e(TAG, "Listener was not previously added");
2062 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002063 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002064 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002065 if (mAccountsUpdatedListeners.isEmpty()) {
2066 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2067 }
2068 }
2069 }
Fred Quintana60307342009-03-24 22:48:12 -07002070}