blob: 6aac72332b1fcd256c7c44eb44c60960084f0cb2 [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;
21import android.content.Context;
Fred Quintanad9d2f112009-04-23 13:36:27 -070022import android.content.IntentFilter;
23import android.content.BroadcastReceiver;
Costin Manolacheb6437242009-09-10 16:14:12 -070024import android.database.SQLException;
Fred Quintanaa698f422009-04-08 19:14:54 -070025import android.os.Bundle;
26import android.os.Handler;
27import android.os.Looper;
28import android.os.RemoteException;
Fred Quintana33269202009-04-20 16:05:10 -070029import android.os.Parcelable;
Fred Quintana751fdc02010-02-09 14:13:18 -080030import android.os.Build;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080031import android.os.Process;
32import android.os.UserHandle;
Costin Manolacheb6437242009-09-10 16:14:12 -070033import android.util.Log;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080034import android.text.TextUtils;
Fred Quintana60307342009-03-24 22:48:12 -070035
Fred Quintanaa698f422009-04-08 19:14:54 -070036import java.io.IOException;
Fred Quintana1121bb52011-09-14 23:19:35 -070037import java.util.ArrayList;
Fred Quintanaa698f422009-04-08 19:14:54 -070038import java.util.concurrent.Callable;
39import java.util.concurrent.CancellationException;
40import java.util.concurrent.ExecutionException;
41import java.util.concurrent.FutureTask;
42import java.util.concurrent.TimeoutException;
43import java.util.concurrent.TimeUnit;
Fred Quintanad9d2f112009-04-23 13:36:27 -070044import java.util.HashMap;
45import java.util.Map;
46
47import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070048
49/**
Dan Egnor661f0132010-02-19 11:23:00 -080050 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070051 * online accounts. The user enters credentials (username and password) once
52 * per account, granting applications access to online resources with
53 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070054 *
Dan Egnor661f0132010-02-19 11:23:00 -080055 * <p>Different online services have different ways of handling accounts and
56 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070057 * modules for different <em>account types</em>. Authenticators (which may be
58 * written by third parties) handle the actual details of validating account
59 * credentials and storing account information. For example, Google, Facebook,
60 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080061 *
62 * <p>Many servers support some notion of an <em>authentication token</em>,
63 * which can be used to authenticate a request to the server without sending
64 * the user's actual password. (Auth tokens are normally created with a
65 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070066 * can generate auth tokens for applications, so the application doesn't need to
67 * handle passwords directly. Auth tokens are normally reusable and cached by
68 * AccountManager, but must be refreshed periodically. It's the responsibility
69 * of applications to <em>invalidate</em> auth tokens when they stop working so
70 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080071 *
72 * <p>Applications accessing a server normally go through these steps:
73 *
74 * <ul>
75 * <li>Get an instance of AccountManager using {@link #get(Context)}.
76 *
77 * <li>List the available accounts using {@link #getAccountsByType} or
78 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
79 * be interested in accounts with one particular <em>type</em>, which
80 * identifies the authenticator. Account <em>features</em> are used to
81 * identify particular account subtypes and capabilities. Both the account
82 * type and features are authenticator-specific strings, and must be known by
83 * the application in coordination with its preferred authenticators.
84 *
85 * <li>Select one or more of the available accounts, possibly by asking the
86 * user for their preference. If no suitable accounts are available,
87 * {@link #addAccount} may be called to prompt the user to create an
88 * account of the appropriate type.
89 *
Dan Egnor8e4378b2010-08-02 18:22:09 -070090 * <li><b>Important:</b> If the application is using a previously remembered
91 * account selection, it must make sure the account is still in the list
92 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
93 * for an account no longer on the device results in an undefined failure.
94 *
Dan Egnor661f0132010-02-19 11:23:00 -080095 * <li>Request an auth token for the selected account(s) using one of the
96 * {@link #getAuthToken} methods or related helpers. Refer to the description
97 * of each method for exact usage and error handling details.
98 *
99 * <li>Make the request using the auth token. The form of the auth token,
100 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700101 * service you are accessing. The application may use whatever network and
102 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800103 *
104 * <li><b>Important:</b> If the request fails with an authentication error,
105 * it could be that a cached auth token is stale and no longer honored by
106 * the server. The application must call {@link #invalidateAuthToken} to remove
107 * the token from the cache, otherwise requests will continue failing! After
108 * invalidating the auth token, immediately go back to the "Request an auth
109 * token" step above. If the process fails the second time, then it can be
110 * treated as a "genuine" authentication failure and the user notified or other
111 * appropriate actions taken.
112 * </ul>
113 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700114 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800115 * prompt for credentials, present options, or ask the user to add an account.
116 * The caller may choose whether to allow AccountManager to directly launch the
117 * necessary user interface and wait for the user, or to return an Intent which
118 * the caller may use to launch the interface, or (in some cases) to install a
119 * notification which the user can select at any time to launch the interface.
120 * To have AccountManager launch the interface directly, the caller must supply
121 * the current foreground {@link Activity} context.
122 *
123 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700124 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800125 * run asynchronously. If a callback is provided then
126 * {@link AccountManagerCallback#run} will be invoked on the Handler's
127 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700128 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
129 * on the {@link AccountManagerFuture} returned by the method (and also passed
130 * to the callback). This method waits for the operation to complete (if
131 * necessary) and either returns the result or throws an exception if an error
132 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800133 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700134 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800135 *
136 * <p>Requests which may block, including
137 * {@link AccountManagerFuture#getResult()}, must never be called on
138 * the application's main event thread. These operations throw
139 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700140 */
141public class AccountManager {
142 private static final String TAG = "AccountManager";
143
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700144 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
145 public static final int ERROR_CODE_NETWORK_ERROR = 3;
146 public static final int ERROR_CODE_CANCELED = 4;
147 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
148 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
149 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
150 public static final int ERROR_CODE_BAD_REQUEST = 8;
Fred Quintana756b7352009-10-21 13:43:10 -0700151
Dan Egnor661f0132010-02-19 11:23:00 -0800152 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700153 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800154 * from methods which return information about a particular account.
155 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700156 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800157
158 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700159 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800160 * from methods which return information about a particular account.
161 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700162 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800163
164 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700165 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800166 * from {@link #getAuthToken} and friends.
167 */
168 public static final String KEY_AUTHTOKEN = "authtoken";
169
170 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700171 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800172 * may require the caller to interact with the user. The Intent can
173 * be used to start the corresponding user interface activity.
174 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700175 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800176
177 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700178 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800179 * {@link #confirmCredentials}, rather than prompting the user with
180 * the standard password prompt.
181 */
182 public static final String KEY_PASSWORD = "password";
183
184 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700185
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700186 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
187 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800188 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700189 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
190 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800191 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
192 public static final String KEY_ERROR_CODE = "errorCode";
193 public static final String KEY_ERROR_MESSAGE = "errorMessage";
194 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700195
Costin Manolachea40c6302010-12-13 14:50:45 -0800196 /**
197 * Authenticators using 'customTokens' option will also get the UID of the
198 * caller
199 */
200 public static final String KEY_CALLER_UID = "callerUid";
201 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800202
Costin Manolached6060452011-01-24 16:11:36 -0800203 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700204 * The Android package of the caller will be set in the options bundle by the
205 * {@link AccountManager} and will be passed to the AccountManagerService and
206 * to the AccountAuthenticators. The uid of the caller will be known by the
207 * AccountManagerService as well as the AccountAuthenticators so they will be able to
208 * verify that the package is consistent with the uid (a uid might be shared by many
209 * packages).
210 */
211 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
212
213 /**
Costin Manolached6060452011-01-24 16:11:36 -0800214 * Boolean, if set and 'customTokens' the authenticator is responsible for
215 * notifications.
216 * @hide
217 */
218 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
219
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700220 public static final String ACTION_AUTHENTICATOR_INTENT =
221 "android.accounts.AccountAuthenticator";
222 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800223 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700224 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
225
Fred Quintana60307342009-03-24 22:48:12 -0700226 private final Context mContext;
227 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700228 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800229
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700230 /**
231 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800232 * when accounts are added, accounts are removed, or an
233 * account's credentials (saved password, etc) are changed.
234 *
235 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700236 */
237 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
238 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700239
Fred Quintana33269202009-04-20 16:05:10 -0700240 /**
241 * @hide
242 */
Fred Quintana60307342009-03-24 22:48:12 -0700243 public AccountManager(Context context, IAccountManager service) {
244 mContext = context;
245 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700246 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700247 }
248
Fred Quintana0eabf022009-04-27 15:08:17 -0700249 /**
250 * @hide used for testing only
251 */
252 public AccountManager(Context context, IAccountManager service, Handler handler) {
253 mContext = context;
254 mService = service;
255 mMainHandler = handler;
256 }
257
Fred Quintana756b7352009-10-21 13:43:10 -0700258 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800259 * @hide for internal use only
260 */
261 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700262 if (result != null) {
263 if (result.containsKey(KEY_AUTHTOKEN)
264 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
265 final Bundle newResult = new Bundle(result);
266 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
267 return newResult;
268 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800269 }
270 return result;
271 }
272
273 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800274 * Gets an AccountManager instance associated with a Context.
275 * The {@link Context} will be used as long as the AccountManager is
276 * active, so make sure to use a {@link Context} whose lifetime is
277 * commensurate with any listeners registered to
278 * {@link #addOnAccountsUpdatedListener} or similar methods.
279 *
280 * <p>It is safe to call this method from the main thread.
281 *
282 * <p>No permission is required to call this method.
283 *
Fred Quintana756b7352009-10-21 13:43:10 -0700284 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800285 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700286 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700287 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700288 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700289 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
290 }
291
Fred Quintana756b7352009-10-21 13:43:10 -0700292 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800293 * Gets the saved password associated with the account.
294 * This is intended for authenticators and related code; applications
295 * should get an auth token instead.
296 *
297 * <p>It is safe to call this method from the main thread.
298 *
299 * <p>This method requires the caller to hold the permission
300 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
301 * and to have the same UID as the account's authenticator.
302 *
303 * @param account The account to query for a password
304 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700305 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700306 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700307 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700308 try {
309 return mService.getPassword(account);
310 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700311 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700312 throw new RuntimeException(e);
313 }
314 }
315
Fred Quintana756b7352009-10-21 13:43:10 -0700316 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800317 * Gets the user data named by "key" associated with the account.
318 * This is intended for authenticators and related code to store
319 * arbitrary metadata along with accounts. The meaning of the keys
320 * and values is up to the authenticator for the account.
321 *
322 * <p>It is safe to call this method from the main thread.
323 *
324 * <p>This method requires the caller to hold the permission
325 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
326 * and to have the same UID as the account's authenticator.
327 *
328 * @param account The account to query for user data
329 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700330 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700331 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700332 if (account == null) throw new IllegalArgumentException("account is null");
333 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700334 try {
335 return mService.getUserData(account, key);
336 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700337 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700338 throw new RuntimeException(e);
339 }
340 }
341
Fred Quintana756b7352009-10-21 13:43:10 -0700342 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800343 * Lists the currently registered authenticators.
344 *
345 * <p>It is safe to call this method from the main thread.
346 *
347 * <p>No permission is required to call this method.
348 *
349 * @return An array of {@link AuthenticatorDescription} for every
350 * authenticator known to the AccountManager service. Empty (never
351 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700352 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700353 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700354 try {
355 return mService.getAuthenticatorTypes();
356 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700357 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700358 throw new RuntimeException(e);
359 }
360 }
361
Fred Quintana756b7352009-10-21 13:43:10 -0700362 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800363 * Lists all accounts of any type registered on the device.
364 * Equivalent to getAccountsByType(null).
365 *
366 * <p>It is safe to call this method from the main thread.
367 *
368 * <p>This method requires the caller to hold the permission
369 * {@link android.Manifest.permission#GET_ACCOUNTS}.
370 *
371 * @return An array of {@link Account}, one for each account. Empty
372 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700373 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700374 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700375 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700376 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700377 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700378 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700379 throw new RuntimeException(e);
380 }
381 }
382
Fred Quintana756b7352009-10-21 13:43:10 -0700383 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800384 * Lists all accounts of a particular type. The account type is a
385 * string token corresponding to the authenticator and useful domain
386 * of the account. For example, there are types corresponding to Google
387 * and Facebook. The exact string token to use will be published somewhere
388 * associated with the authenticator in question.
389 *
390 * <p>It is safe to call this method from the main thread.
391 *
392 * <p>This method requires the caller to hold the permission
393 * {@link android.Manifest.permission#GET_ACCOUNTS}.
394 *
395 * @param type The type of accounts to return, null to retrieve all accounts
396 * @return An array of {@link Account}, one per matching account. Empty
397 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700398 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700399 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800400 return getAccountsByTypeAsUser(type, Process.myUserHandle());
401 }
402
403 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
404 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700405 try {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800406 return mService.getAccountsAsUser(type, userHandle.getIdentifier());
Fred Quintana60307342009-03-24 22:48:12 -0700407 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700408 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700409 throw new RuntimeException(e);
410 }
411 }
412
Fred Quintana756b7352009-10-21 13:43:10 -0700413 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700414 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
415 * for an account.
416 * <p>
417 * This is only meant to be used by system activities and is not in the SDK.
418 * @param account The account whose permissions are being modified
419 * @param authTokenType The type of token whose permissions are being modified
420 * @param uid The uid that identifies the app which is being granted or revoked permission.
421 * @param value true is permission is being granted, false for revoked
422 * @hide
423 */
424 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
425 try {
426 mService.updateAppPermission(account, authTokenType, uid, value);
427 } catch (RemoteException e) {
428 // won't ever happen
429 throw new RuntimeException(e);
430 }
431 }
432
433 /**
434 * Get the user-friendly label associated with an authenticator's auth token.
435 * @param accountType the type of the authenticator. must not be null.
436 * @param authTokenType the token type. must not be null.
437 * @param callback callback to invoke when the result is available. may be null.
438 * @param handler the handler on which to invoke the callback, or null for the main thread
439 * @return a future containing the label string
440 * @hide
441 */
442 public AccountManagerFuture<String> getAuthTokenLabel(
443 final String accountType, final String authTokenType,
444 AccountManagerCallback<String> callback, Handler handler) {
445 if (accountType == null) throw new IllegalArgumentException("accountType is null");
446 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
447 return new Future2Task<String>(handler, callback) {
448 public void doWork() throws RemoteException {
449 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
450 }
451
452 @Override
453 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
454 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
455 throw new AuthenticatorException("no result in response");
456 }
457 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
458 }
459 }.start();
460 }
461
462 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800463 * Finds out whether a particular account has all the specified features.
464 * Account features are authenticator-specific string tokens identifying
465 * boolean account properties. For example, features are used to tell
466 * whether Google accounts have a particular service (such as Google
467 * Calendar or Google Talk) enabled. The feature names and their meanings
468 * are published somewhere associated with the authenticator in question.
469 *
470 * <p>This method may be called from any thread, but the returned
471 * {@link AccountManagerFuture} must not be used on the main thread.
472 *
473 * <p>This method requires the caller to hold the permission
474 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800475 *
476 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800477 * @param features An array of the account features to check
478 * @param callback Callback to invoke when the request completes,
479 * null for no callback
480 * @param handler {@link Handler} identifying the callback thread,
481 * null for the main thread
482 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
483 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800484 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800485 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800486 final String[] features,
487 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700488 if (account == null) throw new IllegalArgumentException("account is null");
489 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800490 return new Future2Task<Boolean>(handler, callback) {
491 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800492 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800493 }
494 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
495 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
496 throw new AuthenticatorException("no result in response");
497 }
498 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
499 }
500 }.start();
501 }
502
503 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800504 * Lists all accounts of a type which have certain features. The account
505 * type identifies the authenticator (see {@link #getAccountsByType}).
506 * Account features are authenticator-specific string tokens identifying
507 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700508 *
Dan Egnor661f0132010-02-19 11:23:00 -0800509 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
510 * which may contact the server or do other work to check account features,
511 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700512 *
Dan Egnor661f0132010-02-19 11:23:00 -0800513 * <p>This method may be called from any thread, but the returned
514 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700515 *
Dan Egnor661f0132010-02-19 11:23:00 -0800516 * <p>This method requires the caller to hold the permission
517 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700518 *
Dan Egnor661f0132010-02-19 11:23:00 -0800519 * @param type The type of accounts to return, must not be null
520 * @param features An array of the account features to require,
521 * may be null or empty
522 * @param callback Callback to invoke when the request completes,
523 * null for no callback
524 * @param handler {@link Handler} identifying the callback thread,
525 * null for the main thread
526 * @return An {@link AccountManagerFuture} which resolves to an array of
527 * {@link Account}, one per account of the specified type which
528 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800529 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700530 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
531 final String type, final String[] features,
532 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700533 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700534 return new Future2Task<Account[]>(handler, callback) {
535 public void doWork() throws RemoteException {
536 mService.getAccountsByFeatures(mResponse, type, features);
537 }
538 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700539 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700540 throw new AuthenticatorException("no result in response");
541 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700542 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700543 Account[] descs = new Account[parcelables.length];
544 for (int i = 0; i < parcelables.length; i++) {
545 descs[i] = (Account) parcelables[i];
546 }
547 return descs;
548 }
549 }.start();
550 }
551
Fred Quintana756b7352009-10-21 13:43:10 -0700552 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800553 * Adds an account directly to the AccountManager. Normally used by sign-up
554 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700555 *
Dan Egnor661f0132010-02-19 11:23:00 -0800556 * <p>It is safe to call this method from the main thread.
557 *
558 * <p>This method requires the caller to hold the permission
559 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
560 * and to have the same UID as the added account's authenticator.
561 *
562 * @param account The {@link Account} to add
563 * @param password The password to associate with the account, null for none
564 * @param userdata String values to use for the account's userdata, null for none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700565 * @return True if the account was successfully added, false if the account
Dan Egnor661f0132010-02-19 11:23:00 -0800566 * already exists, the account is null, or another error occurs.
567 */
568 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700569 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800570 try {
571 return mService.addAccount(account, password, userdata);
572 } catch (RemoteException e) {
573 // won't ever happen
574 throw new RuntimeException(e);
575 }
576 }
577
578 /**
579 * Removes an account from the AccountManager. Does nothing if the account
580 * does not exist. Does not delete the account from the server.
581 * The authenticator may have its own policies preventing account
582 * deletion, in which case the account will not be deleted.
583 *
584 * <p>This method may be called from any thread, but the returned
585 * {@link AccountManagerFuture} must not be used on the main thread.
586 *
587 * <p>This method requires the caller to hold the permission
588 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
589 *
590 * @param account The {@link Account} to remove
591 * @param callback Callback to invoke when the request completes,
592 * null for no callback
593 * @param handler {@link Handler} identifying the callback thread,
594 * null for the main thread
595 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
596 * true if the account has been successfully removed,
597 * false if the authenticator forbids deleting this account.
598 */
599 public AccountManagerFuture<Boolean> removeAccount(final Account account,
600 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700601 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800602 return new Future2Task<Boolean>(handler, callback) {
603 public void doWork() throws RemoteException {
604 mService.removeAccount(mResponse, account);
605 }
606 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
607 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
608 throw new AuthenticatorException("no result in response");
609 }
610 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
611 }
612 }.start();
613 }
614
615 /**
616 * Removes an auth token from the AccountManager's cache. Does nothing if
617 * the auth token is not currently in the cache. Applications must call this
618 * method when the auth token is found to have expired or otherwise become
619 * invalid for authenticating requests. The AccountManager does not validate
620 * or expire cached auth tokens otherwise.
621 *
622 * <p>It is safe to call this method from the main thread.
623 *
624 * <p>This method requires the caller to hold the permission
Fred Quintanab38eb142010-02-24 13:40:54 -0800625 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
626 * {@link android.Manifest.permission#USE_CREDENTIALS}
Dan Egnor661f0132010-02-19 11:23:00 -0800627 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700628 * @param accountType The account type of the auth token to invalidate, must not be null
629 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800630 */
631 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700632 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800633 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700634 if (authToken != null) {
635 mService.invalidateAuthToken(accountType, authToken);
636 }
Dan Egnor661f0132010-02-19 11:23:00 -0800637 } catch (RemoteException e) {
638 // won't ever happen
639 throw new RuntimeException(e);
640 }
641 }
642
643 /**
644 * Gets an auth token from the AccountManager's cache. If no auth
645 * token is cached for this account, null will be returned -- a new
646 * auth token will not be generated, and the server will not be contacted.
647 * Intended for use by the authenticator, not directly by applications.
648 *
649 * <p>It is safe to call this method from the main thread.
650 *
651 * <p>This method requires the caller to hold the permission
652 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
653 * and to have the same UID as the account's authenticator.
654 *
655 * @param account The account to fetch an auth token for
656 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
657 * @return The cached auth token for this account and type, or null if
658 * no auth token is cached or the account does not exist.
659 */
660 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700661 if (account == null) throw new IllegalArgumentException("account is null");
662 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800663 try {
664 return mService.peekAuthToken(account, authTokenType);
665 } catch (RemoteException e) {
666 // won't ever happen
667 throw new RuntimeException(e);
668 }
669 }
670
671 /**
672 * Sets or forgets a saved password. This modifies the local copy of the
673 * password used to automatically authenticate the user; it does
674 * not change the user's account password on the server. Intended for use
675 * by the authenticator, not directly by applications.
676 *
677 * <p>It is safe to call this method from the main thread.
678 *
679 * <p>This method requires the caller to hold the permission
680 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
681 * and have the same UID as the account's authenticator.
682 *
683 * @param account The account to set a password for
684 * @param password The password to set, null to clear the password
685 */
686 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700687 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800688 try {
689 mService.setPassword(account, password);
690 } catch (RemoteException e) {
691 // won't ever happen
692 throw new RuntimeException(e);
693 }
694 }
695
696 /**
697 * Forgets a saved password. This erases the local copy of the password;
698 * it does not change the user's account password on the server.
699 * Has the same effect as setPassword(account, null) but requires fewer
700 * permissions, and may be used by applications or management interfaces
701 * to "sign out" from an account.
702 *
703 * <p>It is safe to call this method from the main thread.
704 *
705 * <p>This method requires the caller to hold the permission
706 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
707 *
708 * @param account The account whose password to clear
709 */
710 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700711 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800712 try {
713 mService.clearPassword(account);
714 } catch (RemoteException e) {
715 // won't ever happen
716 throw new RuntimeException(e);
717 }
718 }
719
720 /**
721 * Sets one userdata key for an account. Intended by use for the
722 * authenticator to stash state for itself, not directly by applications.
723 * The meaning of the keys and values is up to the authenticator.
724 *
725 * <p>It is safe to call this method from the main thread.
726 *
727 * <p>This method requires the caller to hold the permission
728 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
729 * and to have the same UID as the account's authenticator.
730 *
731 * @param account The account to set the userdata for
732 * @param key The userdata key to set. Must not be null
733 * @param value The value to set, null to clear this userdata key
734 */
735 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -0700736 if (account == null) throw new IllegalArgumentException("account is null");
737 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800738 try {
739 mService.setUserData(account, key, value);
740 } catch (RemoteException e) {
741 // won't ever happen
742 throw new RuntimeException(e);
743 }
744 }
745
746 /**
747 * Adds an auth token to the AccountManager cache for an account.
748 * If the account does not exist then this call has no effect.
749 * Replaces any previous auth token for this account and auth token type.
750 * Intended for use by the authenticator, not directly by applications.
751 *
752 * <p>It is safe to call this method from the main thread.
753 *
754 * <p>This method requires the caller to hold the permission
755 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
756 * and to have the same UID as the account's authenticator.
757 *
758 * @param account The account to set an auth token for
759 * @param authTokenType The type of the auth token, see {#getAuthToken}
760 * @param authToken The auth token to add to the cache
761 */
762 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700763 if (account == null) throw new IllegalArgumentException("account is null");
764 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800765 try {
766 mService.setAuthToken(account, authTokenType, authToken);
767 } catch (RemoteException e) {
768 // won't ever happen
769 throw new RuntimeException(e);
770 }
771 }
772
773 /**
774 * This convenience helper synchronously gets an auth token with
775 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
776 *
777 * <p>This method may block while a network request completes, and must
778 * never be made from the main thread.
779 *
780 * <p>This method requires the caller to hold the permission
781 * {@link android.Manifest.permission#USE_CREDENTIALS}.
782 *
783 * @param account The account to fetch an auth token for
784 * @param authTokenType The auth token type, see {#link getAuthToken}
785 * @param notifyAuthFailure If true, display a notification and return null
786 * if authentication fails; if false, prompt and wait for the user to
787 * re-enter correct credentials before returning
788 * @return An auth token of the specified type for this account, or null
789 * if authentication fails or none can be fetched.
790 * @throws AuthenticatorException if the authenticator failed to respond
791 * @throws OperationCanceledException if the request was canceled for any
792 * reason, including the user canceling a credential request
793 * @throws java.io.IOException if the authenticator experienced an I/O problem
794 * creating a new auth token, usually because of network trouble
795 */
796 public String blockingGetAuthToken(Account account, String authTokenType,
797 boolean notifyAuthFailure)
798 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -0700799 if (account == null) throw new IllegalArgumentException("account is null");
800 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800801 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
802 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -0800803 if (bundle == null) {
804 // This should never happen, but it does, occasionally. If it does return null to
805 // signify that we were not able to get the authtoken.
806 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
807 // returned
808 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
809 + account + ", authTokenType " + authTokenType);
810 return null;
811 }
Dan Egnor661f0132010-02-19 11:23:00 -0800812 return bundle.getString(KEY_AUTHTOKEN);
813 }
814
815 /**
816 * Gets an auth token of the specified type for a particular account,
817 * prompting the user for credentials if necessary. This method is
818 * intended for applications running in the foreground where it makes
819 * sense to ask the user directly for a password.
820 *
821 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700822 * type, then it is returned. Otherwise, if a saved password is
823 * available, it is sent to the server to generate a new auth token.
824 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -0800825 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700826 * <p>Some authenticators have auth token <em>types</em>, whose value
827 * is authenticator-dependent. Some services use different token types to
828 * access different functionality -- for example, Google uses different auth
829 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -0800830 *
831 * <p>This method may be called from any thread, but the returned
832 * {@link AccountManagerFuture} must not be used on the main thread.
833 *
834 * <p>This method requires the caller to hold the permission
835 * {@link android.Manifest.permission#USE_CREDENTIALS}.
836 *
837 * @param account The account to fetch an auth token for
838 * @param authTokenType The auth token type, an authenticator-dependent
839 * string token, must not be null
840 * @param options Authenticator-specific options for the request,
841 * may be null or empty
842 * @param activity The {@link Activity} context to use for launching a new
843 * authenticator-defined sub-Activity to prompt the user for a password
844 * if necessary; used only to call startActivity(); must not be null.
845 * @param callback Callback to invoke when the request completes,
846 * null for no callback
847 * @param handler {@link Handler} identifying the callback thread,
848 * null for the main thread
849 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
850 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -0700851 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800852 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
853 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
854 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -0700855 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800856 *
857 * (Other authenticator-specific values may be returned.) If an auth token
858 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
859 * <ul>
860 * <li> {@link AuthenticatorException} if the authenticator failed to respond
861 * <li> {@link OperationCanceledException} if the operation is canceled for
862 * any reason, incluidng the user canceling a credential request
863 * <li> {@link IOException} if the authenticator experienced an I/O problem
864 * creating a new auth token, usually because of network trouble
865 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -0700866 * If the account is no longer present on the device, the return value is
867 * authenticator-dependent. The caller should verify the validity of the
868 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -0800869 */
870 public AccountManagerFuture<Bundle> getAuthToken(
871 final Account account, final String authTokenType, final Bundle options,
872 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700873 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800874 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -0700875 final Bundle optionsIn = new Bundle();
876 if (options != null) {
877 optionsIn.putAll(options);
878 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700879 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -0800880 return new AmsTask(activity, handler, callback) {
881 public void doWork() throws RemoteException {
882 mService.getAuthToken(mResponse, account, authTokenType,
883 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700884 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -0800885 }
886 }.start();
887 }
888
889 /**
890 * Gets an auth token of the specified type for a particular account,
891 * optionally raising a notification if the user must enter credentials.
892 * This method is intended for background tasks and services where the
893 * user should not be immediately interrupted with a password prompt.
894 *
895 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700896 * type, then it is returned. Otherwise, if a saved password is
897 * available, it is sent to the server to generate a new auth token.
898 * Otherwise, an {@link Intent} is returned which, when started, will
899 * prompt the user for a password. If the notifyAuthFailure parameter is
900 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -0800901 * alerting the user that they need to enter a password at some point.
902 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700903 * <p>In that case, you may need to wait until the user responds, which
904 * could take hours or days or forever. When the user does respond and
905 * supply a new password, the account manager will broadcast the
906 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
907 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -0800908 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700909 * <p>If notifyAuthFailure is not set, it is the application's
910 * responsibility to launch the returned Intent at some point.
911 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -0800912 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700913 * <p>Some authenticators have auth token <em>types</em>, whose value
914 * is authenticator-dependent. Some services use different token types to
915 * access different functionality -- for example, Google uses different auth
916 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -0800917 *
918 * <p>This method may be called from any thread, but the returned
919 * {@link AccountManagerFuture} must not be used on the main thread.
920 *
921 * <p>This method requires the caller to hold the permission
922 * {@link android.Manifest.permission#USE_CREDENTIALS}.
923 *
924 * @param account The account to fetch an auth token for
925 * @param authTokenType The auth token type, an authenticator-dependent
926 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -0800927 * @param notifyAuthFailure True to add a notification to prompt the
928 * user for a password if necessary, false to leave that to the caller
929 * @param callback Callback to invoke when the request completes,
930 * null for no callback
931 * @param handler {@link Handler} identifying the callback thread,
932 * null for the main thread
933 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
934 * at least the following fields on success:
935 * <ul>
936 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
937 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
938 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
939 * </ul>
940 *
941 * (Other authenticator-specific values may be returned.) If the user
942 * must enter credentials, the returned Bundle contains only
943 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
944 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700945 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -0800946 * <ul>
947 * <li> {@link AuthenticatorException} if the authenticator failed to respond
948 * <li> {@link OperationCanceledException} if the operation is canceled for
949 * any reason, incluidng the user canceling a credential request
950 * <li> {@link IOException} if the authenticator experienced an I/O problem
951 * creating a new auth token, usually because of network trouble
952 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -0700953 * If the account is no longer present on the device, the return value is
954 * authenticator-dependent. The caller should verify the validity of the
955 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -0700956 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
957 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -0800958 */
Fred Quintanaad93a322011-09-08 13:21:01 -0700959 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800960 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700961 final Account account, final String authTokenType,
962 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -0800963 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700964 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
965 handler);
Dan Egnor661f0132010-02-19 11:23:00 -0800966 }
967
968 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700969 * Gets an auth token of the specified type for a particular account,
970 * optionally raising a notification if the user must enter credentials.
971 * This method is intended for background tasks and services where the
972 * user should not be immediately interrupted with a password prompt.
973 *
974 * <p>If a previously generated auth token is cached for this account and
975 * type, then it is returned. Otherwise, if a saved password is
976 * available, it is sent to the server to generate a new auth token.
977 * Otherwise, an {@link Intent} is returned which, when started, will
978 * prompt the user for a password. If the notifyAuthFailure parameter is
979 * set, a status bar notification is also created with the same Intent,
980 * alerting the user that they need to enter a password at some point.
981 *
982 * <p>In that case, you may need to wait until the user responds, which
983 * could take hours or days or forever. When the user does respond and
984 * supply a new password, the account manager will broadcast the
985 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
986 * use to try again.
987 *
988 * <p>If notifyAuthFailure is not set, it is the application's
989 * responsibility to launch the returned Intent at some point.
990 * Either way, the result from this call will not wait for user action.
991 *
992 * <p>Some authenticators have auth token <em>types</em>, whose value
993 * is authenticator-dependent. Some services use different token types to
994 * access different functionality -- for example, Google uses different auth
995 * tokens to access Gmail and Google Calendar for the same account.
996 *
997 * <p>This method may be called from any thread, but the returned
998 * {@link AccountManagerFuture} must not be used on the main thread.
999 *
1000 * <p>This method requires the caller to hold the permission
1001 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1002 *
1003 * @param account The account to fetch an auth token for
1004 * @param authTokenType The auth token type, an authenticator-dependent
1005 * string token, must not be null
1006 * @param options Authenticator-specific options for the request,
1007 * may be null or empty
1008 * @param notifyAuthFailure True to add a notification to prompt the
1009 * user for a password if necessary, false to leave that to the caller
1010 * @param callback Callback to invoke when the request completes,
1011 * null for no callback
1012 * @param handler {@link Handler} identifying the callback thread,
1013 * null for the main thread
1014 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1015 * at least the following fields on success:
1016 * <ul>
1017 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1018 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1019 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1020 * </ul>
1021 *
1022 * (Other authenticator-specific values may be returned.) If the user
1023 * must enter credentials, the returned Bundle contains only
1024 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1025 *
1026 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1027 * <ul>
1028 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1029 * <li> {@link OperationCanceledException} if the operation is canceled for
1030 * any reason, incluidng the user canceling a credential request
1031 * <li> {@link IOException} if the authenticator experienced an I/O problem
1032 * creating a new auth token, usually because of network trouble
1033 * </ul>
1034 * If the account is no longer present on the device, the return value is
1035 * authenticator-dependent. The caller should verify the validity of the
1036 * account before requesting an auth token.
1037 */
1038 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001039 final Account account, final String authTokenType, final Bundle options,
1040 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001041 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001042
Fred Quintanaad93a322011-09-08 13:21:01 -07001043 if (account == null) throw new IllegalArgumentException("account is null");
1044 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001045 final Bundle optionsIn = new Bundle();
1046 if (options != null) {
1047 optionsIn.putAll(options);
1048 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001049 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001050 return new AmsTask(null, handler, callback) {
1051 public void doWork() throws RemoteException {
1052 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001053 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001054 }
1055 }.start();
1056 }
1057
1058 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001059 * Asks the user to add an account of a specified type. The authenticator
1060 * for this account type processes this request with the appropriate user
1061 * interface. If the user does elect to create a new account, the account
1062 * name is returned.
1063 *
1064 * <p>This method may be called from any thread, but the returned
1065 * {@link AccountManagerFuture} must not be used on the main thread.
1066 *
1067 * <p>This method requires the caller to hold the permission
1068 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1069 *
1070 * @param accountType The type of account to add; must not be null
1071 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1072 * this account will need to be able to generate, null for none
1073 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1074 * account must have, null for none
1075 * @param addAccountOptions Authenticator-specific options for the request,
1076 * may be null or empty
1077 * @param activity The {@link Activity} context to use for launching a new
1078 * authenticator-defined sub-Activity to prompt the user to create an
1079 * account; used only to call startActivity(); if null, the prompt
1080 * will not be launched directly, but the necessary {@link Intent}
1081 * will be returned to the caller instead
1082 * @param callback Callback to invoke when the request completes,
1083 * null for no callback
1084 * @param handler {@link Handler} identifying the callback thread,
1085 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001086 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001087 * these fields if activity was specified and an account was created:
1088 * <ul>
1089 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1090 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1091 * </ul>
1092 *
1093 * If no activity was specified, the returned Bundle contains only
1094 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001095 * actual account creation process. If an error occurred,
1096 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001097 * <ul>
1098 * <li> {@link AuthenticatorException} if no authenticator was registered for
1099 * this account type or the authenticator failed to respond
1100 * <li> {@link OperationCanceledException} if the operation was canceled for
1101 * any reason, including the user canceling the creation process
1102 * <li> {@link IOException} if the authenticator experienced an I/O problem
1103 * creating a new account, usually because of network trouble
1104 * </ul>
1105 */
1106 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1107 final String authTokenType, final String[] requiredFeatures,
1108 final Bundle addAccountOptions,
1109 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001110 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001111 final Bundle optionsIn = new Bundle();
1112 if (addAccountOptions != null) {
1113 optionsIn.putAll(addAccountOptions);
1114 }
1115 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001116
Dan Egnor661f0132010-02-19 11:23:00 -08001117 return new AmsTask(activity, handler, callback) {
1118 public void doWork() throws RemoteException {
Dan Egnor661f0132010-02-19 11:23:00 -08001119 mService.addAcount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001120 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001121 }
1122 }.start();
1123 }
1124
1125 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001126 * Adds a shared account from the primary user to a secondary user. Adding the shared account
1127 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1128 * are attempted to be copied to the target user from the primary via calls to the
1129 * authenticator.
1130 * @param account the account to share
1131 * @param user the target user
1132 * @return
1133 * @hide
1134 */
1135 public boolean addSharedAccount(final Account account, UserHandle user) {
1136 try {
1137 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1138 return val;
1139 } catch (RemoteException re) {
1140 // won't ever happen
1141 throw new RuntimeException(re);
1142 }
1143 }
1144
1145 /**
1146 * @hide
1147 * Removes the shared account.
1148 * @param account the account to remove
1149 * @param user the user to remove the account from
1150 * @return
1151 */
1152 public boolean removeSharedAccount(final Account account, UserHandle user) {
1153 try {
1154 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1155 return val;
1156 } catch (RemoteException re) {
1157 // won't ever happen
1158 throw new RuntimeException(re);
1159 }
1160 }
1161
1162 /**
1163 * @hide
1164 * @param user
1165 * @return
1166 */
1167 public Account[] getSharedAccounts(UserHandle user) {
1168 try {
1169 return mService.getSharedAccountsAsUser(user.getIdentifier());
1170 } catch (RemoteException re) {
1171 // won't ever happen
1172 throw new RuntimeException(re);
1173 }
1174 }
1175
1176 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001177 * Confirms that the user knows the password for an account to make extra
1178 * sure they are the owner of the account. The user-entered password can
1179 * be supplied directly, otherwise the authenticator for this account type
1180 * prompts the user with the appropriate interface. This method is
1181 * intended for applications which want extra assurance; for example, the
1182 * phone lock screen uses this to let the user unlock the phone with an
1183 * account password if they forget the lock pattern.
1184 *
1185 * <p>If the user-entered password matches a saved password for this
1186 * account, the request is considered valid; otherwise the authenticator
1187 * verifies the password (usually by contacting the server).
1188 *
1189 * <p>This method may be called from any thread, but the returned
1190 * {@link AccountManagerFuture} must not be used on the main thread.
1191 *
1192 * <p>This method requires the caller to hold the permission
1193 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1194 *
1195 * @param account The account to confirm password knowledge for
1196 * @param options Authenticator-specific options for the request;
1197 * if the {@link #KEY_PASSWORD} string field is present, the
1198 * authenticator may use it directly rather than prompting the user;
1199 * may be null or empty
1200 * @param activity The {@link Activity} context to use for launching a new
1201 * authenticator-defined sub-Activity to prompt the user to enter a
1202 * password; used only to call startActivity(); if null, the prompt
1203 * will not be launched directly, but the necessary {@link Intent}
1204 * will be returned to the caller instead
1205 * @param callback Callback to invoke when the request completes,
1206 * null for no callback
1207 * @param handler {@link Handler} identifying the callback thread,
1208 * null for the main thread
1209 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1210 * with these fields if activity or password was supplied and
1211 * the account was successfully verified:
1212 * <ul>
1213 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1214 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1215 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1216 * </ul>
1217 *
1218 * If no activity or password was specified, the returned Bundle contains
1219 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001220 * password prompt. If an error occurred,
1221 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001222 * <ul>
1223 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1224 * <li> {@link OperationCanceledException} if the operation was canceled for
1225 * any reason, including the user canceling the password prompt
1226 * <li> {@link IOException} if the authenticator experienced an I/O problem
1227 * verifying the password, usually because of network trouble
1228 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001229 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001230 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1231 final Bundle options,
1232 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001233 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001234 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001235 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1236 Process.myUserHandle());
1237 }
1238
1239 /**
1240 * @hide
1241 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1242 * but for the specified user.
1243 */
1244 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1245 final Bundle options,
1246 final Activity activity,
1247 final AccountManagerCallback<Bundle> callback,
1248 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001249 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001250 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001251 return new AmsTask(activity, handler, callback) {
1252 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001253 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1254 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001255 }
Fred Quintana33269202009-04-20 16:05:10 -07001256 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001257 }
1258
Fred Quintana756b7352009-10-21 13:43:10 -07001259 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001260 * Asks the user to enter a new password for an account, updating the
1261 * saved credentials for the account. Normally this happens automatically
1262 * when the server rejects credentials during an auth token fetch, but this
1263 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001264 *
Dan Egnor661f0132010-02-19 11:23:00 -08001265 * <p>This method may be called from any thread, but the returned
1266 * {@link AccountManagerFuture} must not be used on the main thread.
1267 *
1268 * <p>This method requires the caller to hold the permission
1269 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1270 *
1271 * @param account The account to update credentials for
1272 * @param authTokenType The credentials entered must allow an auth token
1273 * of this type to be created (but no actual auth token is returned);
1274 * may be null
1275 * @param options Authenticator-specific options for the request;
1276 * may be null or empty
1277 * @param activity The {@link Activity} context to use for launching a new
1278 * authenticator-defined sub-Activity to prompt the user to enter a
1279 * password; used only to call startActivity(); if null, the prompt
1280 * will not be launched directly, but the necessary {@link Intent}
1281 * will be returned to the caller instead
1282 * @param callback Callback to invoke when the request completes,
1283 * null for no callback
1284 * @param handler {@link Handler} identifying the callback thread,
1285 * null for the main thread
1286 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1287 * with these fields if an activity was supplied and the account
1288 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001289 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001290 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1291 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001292 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001293 *
1294 * If no activity was specified, the returned Bundle contains only
1295 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001296 * password prompt. If an error occurred,
1297 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001298 * <ul>
1299 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1300 * <li> {@link OperationCanceledException} if the operation was canceled for
1301 * any reason, including the user canceling the password prompt
1302 * <li> {@link IOException} if the authenticator experienced an I/O problem
1303 * verifying the password, usually because of network trouble
1304 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001305 */
1306 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1307 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001308 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001309 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001310 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001311 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001312 return new AmsTask(activity, handler, callback) {
1313 public void doWork() throws RemoteException {
1314 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001315 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001316 }
Fred Quintana33269202009-04-20 16:05:10 -07001317 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001318 }
1319
Fred Quintana756b7352009-10-21 13:43:10 -07001320 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001321 * Offers the user an opportunity to change an authenticator's settings.
1322 * These properties are for the authenticator in general, not a particular
1323 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001324 *
Dan Egnor661f0132010-02-19 11:23:00 -08001325 * <p>This method may be called from any thread, but the returned
1326 * {@link AccountManagerFuture} must not be used on the main thread.
1327 *
1328 * <p>This method requires the caller to hold the permission
1329 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1330 *
1331 * @param accountType The account type associated with the authenticator
1332 * to adjust
1333 * @param activity The {@link Activity} context to use for launching a new
1334 * authenticator-defined sub-Activity to adjust authenticator settings;
1335 * used only to call startActivity(); if null, the settings dialog will
1336 * not be launched directly, but the necessary {@link Intent} will be
1337 * returned to the caller instead
1338 * @param callback Callback to invoke when the request completes,
1339 * null for no callback
1340 * @param handler {@link Handler} identifying the callback thread,
1341 * null for the main thread
1342 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1343 * which is empty if properties were edited successfully, or
1344 * if no activity was specified, contains only {@link #KEY_INTENT}
1345 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001346 * If an error occurred, {@link AccountManagerFuture#getResult()}
1347 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001348 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001349 * <li> {@link AuthenticatorException} if no authenticator was registered for
1350 * this account type or the authenticator failed to respond
1351 * <li> {@link OperationCanceledException} if the operation was canceled for
1352 * any reason, including the user canceling the settings dialog
1353 * <li> {@link IOException} if the authenticator experienced an I/O problem
1354 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001355 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001356 */
1357 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1358 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001359 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001360 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001361 return new AmsTask(activity, handler, callback) {
1362 public void doWork() throws RemoteException {
1363 mService.editProperties(mResponse, accountType, activity != null);
1364 }
Fred Quintana33269202009-04-20 16:05:10 -07001365 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 }
1367
1368 private void ensureNotOnMainThread() {
1369 final Looper looper = Looper.myLooper();
1370 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001371 final IllegalStateException exception = new IllegalStateException(
1372 "calling this from your main thread can lead to deadlock");
1373 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1374 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001375 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1376 throw exception;
1377 }
Fred Quintana60307342009-03-24 22:48:12 -07001378 }
1379 }
1380
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001381 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1382 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001383 handler = handler == null ? mMainHandler : handler;
1384 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001385 public void run() {
1386 callback.run(future);
1387 }
1388 });
1389 }
Fred Quintana60307342009-03-24 22:48:12 -07001390
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001391 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001392 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001393 final Account[] accountsCopy = new Account[accounts.length];
1394 // send a copy to make sure that one doesn't
1395 // change what another sees
1396 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1397 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001398 handler.post(new Runnable() {
1399 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001400 try {
1401 listener.onAccountsUpdated(accountsCopy);
1402 } catch (SQLException e) {
1403 // Better luck next time. If the problem was disk-full,
1404 // the STORAGE_OK intent will re-trigger the update.
1405 Log.e(TAG, "Can't update accounts", e);
1406 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001407 }
1408 });
1409 }
1410
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001411 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001412 final IAccountManagerResponse mResponse;
1413 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001414 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001415 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001416 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001417 super(new Callable<Bundle>() {
1418 public Bundle call() throws Exception {
1419 throw new IllegalStateException("this should never be called");
1420 }
1421 });
1422
1423 mHandler = handler;
1424 mCallback = callback;
1425 mActivity = activity;
1426 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001427 }
1428
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001429 public final AccountManagerFuture<Bundle> start() {
1430 try {
1431 doWork();
1432 } catch (RemoteException e) {
1433 setException(e);
1434 }
Fred Quintana33269202009-04-20 16:05:10 -07001435 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001436 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001437
Fred Quintana96580e02010-03-04 13:42:42 -08001438 protected void set(Bundle bundle) {
1439 // TODO: somehow a null is being set as the result of the Future. Log this
1440 // case to help debug where this is occurring. When this bug is fixed this
1441 // condition statement should be removed.
1442 if (bundle == null) {
1443 Log.e(TAG, "the bundle must not be null", new Exception());
1444 }
1445 super.set(bundle);
1446 }
1447
Fred Quintanaa698f422009-04-08 19:14:54 -07001448 public abstract void doWork() throws RemoteException;
1449
1450 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1451 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001452 if (!isDone()) {
1453 ensureNotOnMainThread();
1454 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001455 try {
1456 if (timeout == null) {
1457 return get();
1458 } else {
1459 return get(timeout, unit);
1460 }
1461 } catch (CancellationException e) {
1462 throw new OperationCanceledException();
1463 } catch (TimeoutException e) {
1464 // fall through and cancel
1465 } catch (InterruptedException e) {
1466 // fall through and cancel
1467 } catch (ExecutionException e) {
1468 final Throwable cause = e.getCause();
1469 if (cause instanceof IOException) {
1470 throw (IOException) cause;
1471 } else if (cause instanceof UnsupportedOperationException) {
1472 throw new AuthenticatorException(cause);
1473 } else if (cause instanceof AuthenticatorException) {
1474 throw (AuthenticatorException) cause;
1475 } else if (cause instanceof RuntimeException) {
1476 throw (RuntimeException) cause;
1477 } else if (cause instanceof Error) {
1478 throw (Error) cause;
1479 } else {
1480 throw new IllegalStateException(cause);
1481 }
1482 } finally {
1483 cancel(true /* interrupt if running */);
1484 }
1485 throw new OperationCanceledException();
1486 }
1487
1488 public Bundle getResult()
1489 throws OperationCanceledException, IOException, AuthenticatorException {
1490 return internalGetResult(null, null);
1491 }
1492
1493 public Bundle getResult(long timeout, TimeUnit unit)
1494 throws OperationCanceledException, IOException, AuthenticatorException {
1495 return internalGetResult(timeout, unit);
1496 }
1497
1498 protected void done() {
1499 if (mCallback != null) {
1500 postToHandler(mHandler, mCallback, this);
1501 }
1502 }
1503
1504 /** Handles the responses from the AccountManager */
1505 private class Response extends IAccountManagerResponse.Stub {
1506 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07001507 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07001508 if (intent != null && mActivity != null) {
1509 // since the user provided an Activity we will silently start intents
1510 // that we see
1511 mActivity.startActivity(intent);
1512 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001513 } else if (bundle.getBoolean("retry")) {
1514 try {
1515 doWork();
1516 } catch (RemoteException e) {
1517 // this will only happen if the system process is dead, which means
1518 // we will be dying ourselves
1519 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001520 } else {
1521 set(bundle);
1522 }
1523 }
1524
1525 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001526 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001527 // the authenticator indicated that this request was canceled, do so now
1528 cancel(true /* mayInterruptIfRunning */);
1529 return;
1530 }
1531 setException(convertErrorToException(code, message));
1532 }
1533 }
1534
Fred Quintana60307342009-03-24 22:48:12 -07001535 }
1536
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001537 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1538 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001539 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001540
1541 public BaseFutureTask(Handler handler) {
1542 super(new Callable<T>() {
1543 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001544 throw new IllegalStateException("this should never be called");
1545 }
1546 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001547 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001548 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001549 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001550
1551 public abstract void doWork() throws RemoteException;
1552
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001553 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001554
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001555 protected void postRunnableToHandler(Runnable runnable) {
1556 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1557 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001558 }
1559
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001560 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001561 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001562 doWork();
1563 } catch (RemoteException e) {
1564 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001565 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001566 }
1567
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001568 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001569 public void onResult(Bundle bundle) {
1570 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001571 T result = bundleToResult(bundle);
1572 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001573 return;
1574 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001575 set(result);
1576 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001577 } catch (ClassCastException e) {
1578 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001579 } catch (AuthenticatorException e) {
1580 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001581 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001582 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001583 }
1584
1585 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001586 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001587 cancel(true /* mayInterruptIfRunning */);
1588 return;
1589 }
1590 setException(convertErrorToException(code, message));
1591 }
1592 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001593 }
1594
1595 private abstract class Future2Task<T>
1596 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1597 final AccountManagerCallback<T> mCallback;
1598 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1599 super(handler);
1600 mCallback = callback;
1601 }
1602
1603 protected void done() {
1604 if (mCallback != null) {
1605 postRunnableToHandler(new Runnable() {
1606 public void run() {
1607 mCallback.run(Future2Task.this);
1608 }
1609 });
1610 }
1611 }
1612
1613 public Future2Task<T> start() {
1614 startTask();
1615 return this;
1616 }
1617
1618 private T internalGetResult(Long timeout, TimeUnit unit)
1619 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001620 if (!isDone()) {
1621 ensureNotOnMainThread();
1622 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001623 try {
1624 if (timeout == null) {
1625 return get();
1626 } else {
1627 return get(timeout, unit);
1628 }
1629 } catch (InterruptedException e) {
1630 // fall through and cancel
1631 } catch (TimeoutException e) {
1632 // fall through and cancel
1633 } catch (CancellationException e) {
1634 // fall through and cancel
1635 } catch (ExecutionException e) {
1636 final Throwable cause = e.getCause();
1637 if (cause instanceof IOException) {
1638 throw (IOException) cause;
1639 } else if (cause instanceof UnsupportedOperationException) {
1640 throw new AuthenticatorException(cause);
1641 } else if (cause instanceof AuthenticatorException) {
1642 throw (AuthenticatorException) cause;
1643 } else if (cause instanceof RuntimeException) {
1644 throw (RuntimeException) cause;
1645 } else if (cause instanceof Error) {
1646 throw (Error) cause;
1647 } else {
1648 throw new IllegalStateException(cause);
1649 }
1650 } finally {
1651 cancel(true /* interrupt if running */);
1652 }
1653 throw new OperationCanceledException();
1654 }
1655
1656 public T getResult()
1657 throws OperationCanceledException, IOException, AuthenticatorException {
1658 return internalGetResult(null, null);
1659 }
1660
1661 public T getResult(long timeout, TimeUnit unit)
1662 throws OperationCanceledException, IOException, AuthenticatorException {
1663 return internalGetResult(timeout, unit);
1664 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001665
Fred Quintana60307342009-03-24 22:48:12 -07001666 }
1667
Fred Quintanaa698f422009-04-08 19:14:54 -07001668 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001669 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001670 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001671 }
Fred Quintana60307342009-03-24 22:48:12 -07001672
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001673 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07001674 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001675 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001676
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001677 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07001678 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 }
1680
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001681 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07001682 return new IllegalArgumentException(message);
1683 }
1684
1685 return new AuthenticatorException(message);
1686 }
1687
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001688 private class GetAuthTokenByTypeAndFeaturesTask
1689 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07001690 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1691 final String[] features, Activity activityForPrompting,
1692 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001693 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001694 super(activityForPrompting, handler, callback);
1695 if (accountType == null) throw new IllegalArgumentException("account type is null");
1696 mAccountType = accountType;
1697 mAuthTokenType = authTokenType;
1698 mFeatures = features;
1699 mAddAccountOptions = addAccountOptions;
1700 mLoginOptions = loginOptions;
1701 mMyCallback = this;
1702 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001703 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07001704 final String mAccountType;
1705 final String mAuthTokenType;
1706 final String[] mFeatures;
1707 final Bundle mAddAccountOptions;
1708 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001709 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001710 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07001711
1712 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001713 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1714 new AccountManagerCallback<Account[]>() {
1715 public void run(AccountManagerFuture<Account[]> future) {
1716 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07001717 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001718 accounts = future.getResult();
1719 } catch (OperationCanceledException e) {
1720 setException(e);
1721 return;
1722 } catch (IOException e) {
1723 setException(e);
1724 return;
1725 } catch (AuthenticatorException e) {
1726 setException(e);
1727 return;
Fred Quintana33269202009-04-20 16:05:10 -07001728 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001729
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001730 mNumAccounts = accounts.length;
1731
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001732 if (accounts.length == 0) {
1733 if (mActivity != null) {
1734 // no accounts, add one now. pretend that the user directly
1735 // made this request
1736 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1737 mAddAccountOptions, mActivity, mMyCallback, mHandler);
1738 } else {
1739 // send result since we can't prompt to add an account
1740 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001741 result.putString(KEY_ACCOUNT_NAME, null);
1742 result.putString(KEY_ACCOUNT_TYPE, null);
1743 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001744 try {
1745 mResponse.onResult(result);
1746 } catch (RemoteException e) {
1747 // this will never happen
1748 }
1749 // we are done
1750 }
1751 } else if (accounts.length == 1) {
1752 // have a single account, return an authtoken for it
1753 if (mActivity == null) {
1754 mFuture = getAuthToken(accounts[0], mAuthTokenType,
1755 false /* notifyAuthFailure */, mMyCallback, mHandler);
1756 } else {
1757 mFuture = getAuthToken(accounts[0],
1758 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07001759 mActivity, mMyCallback, mHandler);
1760 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001761 } else {
1762 if (mActivity != null) {
1763 IAccountManagerResponse chooseResponse =
1764 new IAccountManagerResponse.Stub() {
1765 public void onResult(Bundle value) throws RemoteException {
1766 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001767 value.getString(KEY_ACCOUNT_NAME),
1768 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001769 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1770 mActivity, mMyCallback, mHandler);
1771 }
Fred Quintana33269202009-04-20 16:05:10 -07001772
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001773 public void onError(int errorCode, String errorMessage)
1774 throws RemoteException {
1775 mResponse.onError(errorCode, errorMessage);
1776 }
1777 };
1778 // have many accounts, launch the chooser
1779 Intent intent = new Intent();
1780 intent.setClassName("android",
1781 "android.accounts.ChooseAccountActivity");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001782 intent.putExtra(KEY_ACCOUNTS, accounts);
1783 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001784 new AccountManagerResponse(chooseResponse));
1785 mActivity.startActivity(intent);
1786 // the result will arrive via the IAccountManagerResponse
1787 } else {
1788 // send result since we can't prompt to select an account
1789 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001790 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001791 try {
1792 mResponse.onResult(result);
1793 } catch (RemoteException e) {
1794 // this will never happen
1795 }
1796 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07001797 }
Fred Quintana33269202009-04-20 16:05:10 -07001798 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001799 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07001800 }
1801
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001802 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07001803 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001804 final Bundle result = future.getResult();
1805 if (mNumAccounts == 0) {
1806 final String accountName = result.getString(KEY_ACCOUNT_NAME);
1807 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
1808 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
1809 setException(new AuthenticatorException("account not in result"));
1810 return;
1811 }
1812 final Account account = new Account(accountName, accountType);
1813 mNumAccounts = 1;
1814 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
1815 mMyCallback, mHandler);
1816 return;
1817 }
1818 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001819 } catch (OperationCanceledException e) {
1820 cancel(true /* mayInterruptIfRUnning */);
1821 } catch (IOException e) {
1822 setException(e);
1823 } catch (AuthenticatorException e) {
1824 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07001825 }
1826 }
1827 }
1828
Fred Quintana756b7352009-10-21 13:43:10 -07001829 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001830 * This convenience helper combines the functionality of
1831 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1832 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07001833 *
Dan Egnor661f0132010-02-19 11:23:00 -08001834 * <p>This method gets a list of the accounts matching the
1835 * specified type and feature set; if there is exactly one, it is
1836 * used; if there are more than one, the user is prompted to pick one;
1837 * if there are none, the user is prompted to add one. Finally,
1838 * an auth token is acquired for the chosen account.
1839 *
1840 * <p>This method may be called from any thread, but the returned
1841 * {@link AccountManagerFuture} must not be used on the main thread.
1842 *
1843 * <p>This method requires the caller to hold the permission
1844 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1845 *
1846 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08001847 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001848 * @param authTokenType The desired auth token type
1849 * (see {@link #getAuthToken}), must not be null
1850 * @param features Required features for the account
1851 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1852 * @param activity The {@link Activity} context to use for launching new
1853 * sub-Activities to prompt to add an account, select an account,
1854 * and/or enter a password, as necessary; used only to call
1855 * startActivity(); should not be null
1856 * @param addAccountOptions Authenticator-specific options to use for
1857 * adding new accounts; may be null or empty
1858 * @param getAuthTokenOptions Authenticator-specific options to use for
1859 * getting auth tokens; may be null or empty
1860 * @param callback Callback to invoke when the request completes,
1861 * null for no callback
1862 * @param handler {@link Handler} identifying the callback thread,
1863 * null for the main thread
1864 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1865 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001866 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001867 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1868 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1869 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001870 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001871 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001872 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001873 * <ul>
1874 * <li> {@link AuthenticatorException} if no authenticator was registered for
1875 * this account type or the authenticator failed to respond
1876 * <li> {@link OperationCanceledException} if the operation was canceled for
1877 * any reason, including the user canceling any operation
1878 * <li> {@link IOException} if the authenticator experienced an I/O problem
1879 * updating settings, usually because of network trouble
1880 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001881 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001882 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07001883 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08001884 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07001885 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001886 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001887 if (accountType == null) throw new IllegalArgumentException("account type is null");
1888 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001889 final GetAuthTokenByTypeAndFeaturesTask task =
1890 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08001891 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001892 task.start();
1893 return task;
Fred Quintana60307342009-03-24 22:48:12 -07001894 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001895
Fred Quintana1121bb52011-09-14 23:19:35 -07001896 /**
1897 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
1898 * accounts.
1899 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04001900 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07001901 * <p>
1902 * On success the activity returns a Bundle with the account name and type specified using
1903 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
1904 * <p>
1905 * The most common case is to call this with one account type, e.g.:
1906 * <p>
Fred Quintanad88324d2011-09-19 11:43:05 -07001907 * <pre> newChooseAccountsIntent(null, null, new String[]{"com.google"}, false, null,
1908 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07001909 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
1910 * selected one, according to the caller's definition of selected.
1911 * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
1912 * shown. If not specified then this field will not limit the displayed accounts.
1913 * @param allowableAccountTypes an optional string array of account types. These are used
1914 * both to filter the shown accounts and to filter the list of account types that are shown
1915 * when adding an account.
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001916 * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
1917 * it is only shown when there is more than one account from which to choose
Fred Quintanad88324d2011-09-19 11:43:05 -07001918 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001919 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07001920 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
1921 * authTokenType parameter
1922 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
1923 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001924 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07001925 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001926 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07001927 */
1928 static public Intent newChooseAccountIntent(Account selectedAccount,
1929 ArrayList<Account> allowableAccounts,
1930 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001931 boolean alwaysPromptForAccount,
1932 String descriptionOverrideText,
1933 String addAccountAuthTokenType,
1934 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07001935 Bundle addAccountOptions) {
1936 Intent intent = new Intent();
1937 intent.setClassName("android", "android.accounts.ChooseTypeAndAccountActivity");
1938 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
1939 allowableAccounts);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001940 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
1941 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07001942 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
1943 addAccountOptions);
1944 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07001945 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
1946 alwaysPromptForAccount);
1947 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
1948 descriptionOverrideText);
1949 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
1950 addAccountAuthTokenType);
1951 intent.putExtra(
1952 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
1953 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07001954 return intent;
1955 }
1956
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001957 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07001958 Maps.newHashMap();
1959
Fred Quintanad9d2f112009-04-23 13:36:27 -07001960 /**
1961 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1962 * so that it can read the updated list of accounts and send them to the listener
1963 * in mAccountsUpdatedListeners.
1964 */
1965 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1966 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001967 final Account[] accounts = getAccounts();
1968 // send the result to the listeners
1969 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001970 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001971 mAccountsUpdatedListeners.entrySet()) {
1972 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001973 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001974 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001975 }
1976 };
1977
1978 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001979 * Adds an {@link OnAccountsUpdateListener} to this instance of the
1980 * {@link AccountManager}. This listener will be notified whenever the
1981 * list of accounts on the device changes.
1982 *
1983 * <p>As long as this listener is present, the AccountManager instance
1984 * will not be garbage-collected, and neither will the {@link Context}
1985 * used to retrieve it, which may be a large Activity instance. To avoid
1986 * memory leaks, you must remove this listener before then. Normally
1987 * listeners are added in an Activity or Service's {@link Activity#onCreate}
1988 * and removed in {@link Activity#onDestroy}.
1989 *
1990 * <p>It is safe to call this method from the main thread.
1991 *
Nicolas Falliere9530e3a2012-06-18 17:21:06 -07001992 * <p>This method requires the caller to hold the permission
1993 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Dan Egnor661f0132010-02-19 11:23:00 -08001994 *
1995 * @param listener The listener to send notifications to
1996 * @param handler {@link Handler} identifying the thread to use
1997 * for notifications, null for the main thread
1998 * @param updateImmediately If true, the listener will be invoked
1999 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002000 * @throws IllegalArgumentException if listener is null
2001 * @throws IllegalStateException if listener was already added
2002 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002003 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002004 Handler handler, boolean updateImmediately) {
2005 if (listener == null) {
2006 throw new IllegalArgumentException("the listener is null");
2007 }
2008 synchronized (mAccountsUpdatedListeners) {
2009 if (mAccountsUpdatedListeners.containsKey(listener)) {
2010 throw new IllegalStateException("this listener is already added");
2011 }
2012 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2013
2014 mAccountsUpdatedListeners.put(listener, handler);
2015
2016 if (wasEmpty) {
2017 // Register a broadcast receiver to monitor account changes
2018 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002019 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002020 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002021 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002022 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2023 }
2024 }
2025
2026 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002027 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002028 }
2029 }
2030
2031 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002032 * Removes an {@link OnAccountsUpdateListener} previously registered with
2033 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2034 * receive notifications of account changes.
2035 *
2036 * <p>It is safe to call this method from the main thread.
2037 *
2038 * <p>No permission is required to call this method.
2039 *
2040 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002041 * @throws IllegalArgumentException if listener is null
2042 * @throws IllegalStateException if listener was not already added
2043 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002044 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002045 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002046 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002047 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002048 Log.e(TAG, "Listener was not previously added");
2049 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002050 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002051 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002052 if (mAccountsUpdatedListeners.isEmpty()) {
2053 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2054 }
2055 }
2056 }
Fred Quintana60307342009-03-24 22:48:12 -07002057}