blob: 5bdc79d054b1110dae0d39dc7f8550f081a58143 [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;
Costin Manolacheb6437242009-09-10 16:14:12 -070031import android.util.Log;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080032import android.text.TextUtils;
Fred Quintana60307342009-03-24 22:48:12 -070033
Fred Quintanaa698f422009-04-08 19:14:54 -070034import java.io.IOException;
35import java.util.concurrent.Callable;
36import java.util.concurrent.CancellationException;
37import java.util.concurrent.ExecutionException;
38import java.util.concurrent.FutureTask;
39import java.util.concurrent.TimeoutException;
40import java.util.concurrent.TimeUnit;
Fred Quintanad9d2f112009-04-23 13:36:27 -070041import java.util.HashMap;
42import java.util.Map;
43
44import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070045
46/**
Dan Egnor661f0132010-02-19 11:23:00 -080047 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070048 * online accounts. The user enters credentials (username and password) once
49 * per account, granting applications access to online resources with
50 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070051 *
Dan Egnor661f0132010-02-19 11:23:00 -080052 * <p>Different online services have different ways of handling accounts and
53 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070054 * modules for different <em>account types</em>. Authenticators (which may be
55 * written by third parties) handle the actual details of validating account
56 * credentials and storing account information. For example, Google, Facebook,
57 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080058 *
59 * <p>Many servers support some notion of an <em>authentication token</em>,
60 * which can be used to authenticate a request to the server without sending
61 * the user's actual password. (Auth tokens are normally created with a
62 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070063 * can generate auth tokens for applications, so the application doesn't need to
64 * handle passwords directly. Auth tokens are normally reusable and cached by
65 * AccountManager, but must be refreshed periodically. It's the responsibility
66 * of applications to <em>invalidate</em> auth tokens when they stop working so
67 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080068 *
69 * <p>Applications accessing a server normally go through these steps:
70 *
71 * <ul>
72 * <li>Get an instance of AccountManager using {@link #get(Context)}.
73 *
74 * <li>List the available accounts using {@link #getAccountsByType} or
75 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
76 * be interested in accounts with one particular <em>type</em>, which
77 * identifies the authenticator. Account <em>features</em> are used to
78 * identify particular account subtypes and capabilities. Both the account
79 * type and features are authenticator-specific strings, and must be known by
80 * the application in coordination with its preferred authenticators.
81 *
82 * <li>Select one or more of the available accounts, possibly by asking the
83 * user for their preference. If no suitable accounts are available,
84 * {@link #addAccount} may be called to prompt the user to create an
85 * account of the appropriate type.
86 *
Dan Egnor8e4378b2010-08-02 18:22:09 -070087 * <li><b>Important:</b> If the application is using a previously remembered
88 * account selection, it must make sure the account is still in the list
89 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
90 * for an account no longer on the device results in an undefined failure.
91 *
Dan Egnor661f0132010-02-19 11:23:00 -080092 * <li>Request an auth token for the selected account(s) using one of the
93 * {@link #getAuthToken} methods or related helpers. Refer to the description
94 * of each method for exact usage and error handling details.
95 *
96 * <li>Make the request using the auth token. The form of the auth token,
97 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -070098 * service you are accessing. The application may use whatever network and
99 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800100 *
101 * <li><b>Important:</b> If the request fails with an authentication error,
102 * it could be that a cached auth token is stale and no longer honored by
103 * the server. The application must call {@link #invalidateAuthToken} to remove
104 * the token from the cache, otherwise requests will continue failing! After
105 * invalidating the auth token, immediately go back to the "Request an auth
106 * token" step above. If the process fails the second time, then it can be
107 * treated as a "genuine" authentication failure and the user notified or other
108 * appropriate actions taken.
109 * </ul>
110 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700111 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800112 * prompt for credentials, present options, or ask the user to add an account.
113 * The caller may choose whether to allow AccountManager to directly launch the
114 * necessary user interface and wait for the user, or to return an Intent which
115 * the caller may use to launch the interface, or (in some cases) to install a
116 * notification which the user can select at any time to launch the interface.
117 * To have AccountManager launch the interface directly, the caller must supply
118 * the current foreground {@link Activity} context.
119 *
120 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700121 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800122 * run asynchronously. If a callback is provided then
123 * {@link AccountManagerCallback#run} will be invoked on the Handler's
124 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700125 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
126 * on the {@link AccountManagerFuture} returned by the method (and also passed
127 * to the callback). This method waits for the operation to complete (if
128 * necessary) and either returns the result or throws an exception if an error
129 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800130 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700131 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800132 *
133 * <p>Requests which may block, including
134 * {@link AccountManagerFuture#getResult()}, must never be called on
135 * the application's main event thread. These operations throw
136 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700137 */
138public class AccountManager {
139 private static final String TAG = "AccountManager";
140
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700141 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
142 public static final int ERROR_CODE_NETWORK_ERROR = 3;
143 public static final int ERROR_CODE_CANCELED = 4;
144 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
145 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
146 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
147 public static final int ERROR_CODE_BAD_REQUEST = 8;
Fred Quintana756b7352009-10-21 13:43:10 -0700148
Dan Egnor661f0132010-02-19 11:23:00 -0800149 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700150 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800151 * from methods which return information about a particular account.
152 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700153 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800154
155 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700156 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800157 * from methods which return information about a particular account.
158 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700159 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800160
161 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700162 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800163 * from {@link #getAuthToken} and friends.
164 */
165 public static final String KEY_AUTHTOKEN = "authtoken";
166
167 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700168 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800169 * may require the caller to interact with the user. The Intent can
170 * be used to start the corresponding user interface activity.
171 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700172 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800173
174 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700175 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800176 * {@link #confirmCredentials}, rather than prompting the user with
177 * the standard password prompt.
178 */
179 public static final String KEY_PASSWORD = "password";
180
181 public static final String KEY_ACCOUNTS = "accounts";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700182 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
183 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800184 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700185 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
186 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800187 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
188 public static final String KEY_ERROR_CODE = "errorCode";
189 public static final String KEY_ERROR_MESSAGE = "errorMessage";
190 public static final String KEY_USERDATA = "userdata";
Costin Manolachea40c6302010-12-13 14:50:45 -0800191 /**
192 * Authenticators using 'customTokens' option will also get the UID of the
193 * caller
194 */
195 public static final String KEY_CALLER_UID = "callerUid";
196 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800197
Costin Manolached6060452011-01-24 16:11:36 -0800198 /**
199 * Boolean, if set and 'customTokens' the authenticator is responsible for
200 * notifications.
201 * @hide
202 */
203 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
204
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700205 public static final String ACTION_AUTHENTICATOR_INTENT =
206 "android.accounts.AccountAuthenticator";
207 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800208 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700209 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
210
Fred Quintana60307342009-03-24 22:48:12 -0700211 private final Context mContext;
212 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700213 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800214
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700215 /**
216 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800217 * when accounts are added, accounts are removed, or an
218 * account's credentials (saved password, etc) are changed.
219 *
220 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700221 */
222 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
223 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700224
Fred Quintana33269202009-04-20 16:05:10 -0700225 /**
226 * @hide
227 */
Fred Quintana60307342009-03-24 22:48:12 -0700228 public AccountManager(Context context, IAccountManager service) {
229 mContext = context;
230 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700231 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700232 }
233
Fred Quintana0eabf022009-04-27 15:08:17 -0700234 /**
235 * @hide used for testing only
236 */
237 public AccountManager(Context context, IAccountManager service, Handler handler) {
238 mContext = context;
239 mService = service;
240 mMainHandler = handler;
241 }
242
Fred Quintana756b7352009-10-21 13:43:10 -0700243 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800244 * @hide for internal use only
245 */
246 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700247 if (result != null) {
248 if (result.containsKey(KEY_AUTHTOKEN)
249 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
250 final Bundle newResult = new Bundle(result);
251 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
252 return newResult;
253 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800254 }
255 return result;
256 }
257
258 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800259 * Gets an AccountManager instance associated with a Context.
260 * The {@link Context} will be used as long as the AccountManager is
261 * active, so make sure to use a {@link Context} whose lifetime is
262 * commensurate with any listeners registered to
263 * {@link #addOnAccountsUpdatedListener} or similar methods.
264 *
265 * <p>It is safe to call this method from the main thread.
266 *
267 * <p>No permission is required to call this method.
268 *
Fred Quintana756b7352009-10-21 13:43:10 -0700269 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800270 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700271 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700272 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700273 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700274 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
275 }
276
Fred Quintana756b7352009-10-21 13:43:10 -0700277 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800278 * Gets the saved password associated with the account.
279 * This is intended for authenticators and related code; applications
280 * should get an auth token instead.
281 *
282 * <p>It is safe to call this method from the main thread.
283 *
284 * <p>This method requires the caller to hold the permission
285 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
286 * and to have the same UID as the account's authenticator.
287 *
288 * @param account The account to query for a password
289 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700290 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700291 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700292 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700293 try {
294 return mService.getPassword(account);
295 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700296 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700297 throw new RuntimeException(e);
298 }
299 }
300
Fred Quintana756b7352009-10-21 13:43:10 -0700301 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800302 * Gets the user data named by "key" associated with the account.
303 * This is intended for authenticators and related code to store
304 * arbitrary metadata along with accounts. The meaning of the keys
305 * and values is up to the authenticator for the account.
306 *
307 * <p>It is safe to call this method from the main thread.
308 *
309 * <p>This method requires the caller to hold the permission
310 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
311 * and to have the same UID as the account's authenticator.
312 *
313 * @param account The account to query for user data
314 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700315 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700316 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700317 if (account == null) throw new IllegalArgumentException("account is null");
318 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700319 try {
320 return mService.getUserData(account, key);
321 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700322 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700323 throw new RuntimeException(e);
324 }
325 }
326
Fred Quintana756b7352009-10-21 13:43:10 -0700327 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800328 * Lists the currently registered authenticators.
329 *
330 * <p>It is safe to call this method from the main thread.
331 *
332 * <p>No permission is required to call this method.
333 *
334 * @return An array of {@link AuthenticatorDescription} for every
335 * authenticator known to the AccountManager service. Empty (never
336 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700337 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700338 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700339 try {
340 return mService.getAuthenticatorTypes();
341 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700342 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700343 throw new RuntimeException(e);
344 }
345 }
346
Fred Quintana756b7352009-10-21 13:43:10 -0700347 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800348 * Lists all accounts of any type registered on the device.
349 * Equivalent to getAccountsByType(null).
350 *
351 * <p>It is safe to call this method from the main thread.
352 *
353 * <p>This method requires the caller to hold the permission
354 * {@link android.Manifest.permission#GET_ACCOUNTS}.
355 *
356 * @return An array of {@link Account}, one for each account. Empty
357 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700358 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700359 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700360 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700361 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700362 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700363 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700364 throw new RuntimeException(e);
365 }
366 }
367
Fred Quintana756b7352009-10-21 13:43:10 -0700368 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800369 * Lists all accounts of a particular type. The account type is a
370 * string token corresponding to the authenticator and useful domain
371 * of the account. For example, there are types corresponding to Google
372 * and Facebook. The exact string token to use will be published somewhere
373 * associated with the authenticator in question.
374 *
375 * <p>It is safe to call this method from the main thread.
376 *
377 * <p>This method requires the caller to hold the permission
378 * {@link android.Manifest.permission#GET_ACCOUNTS}.
379 *
380 * @param type The type of accounts to return, null to retrieve all accounts
381 * @return An array of {@link Account}, one per matching account. Empty
382 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700383 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700384 public Account[] getAccountsByType(String type) {
Fred Quintana60307342009-03-24 22:48:12 -0700385 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700386 return mService.getAccounts(type);
Fred Quintana60307342009-03-24 22:48:12 -0700387 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700388 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700389 throw new RuntimeException(e);
390 }
391 }
392
Fred Quintana756b7352009-10-21 13:43:10 -0700393 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800394 * Finds out whether a particular account has all the specified features.
395 * Account features are authenticator-specific string tokens identifying
396 * boolean account properties. For example, features are used to tell
397 * whether Google accounts have a particular service (such as Google
398 * Calendar or Google Talk) enabled. The feature names and their meanings
399 * are published somewhere associated with the authenticator in question.
400 *
401 * <p>This method may be called from any thread, but the returned
402 * {@link AccountManagerFuture} must not be used on the main thread.
403 *
404 * <p>This method requires the caller to hold the permission
405 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800406 *
407 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800408 * @param features An array of the account features to check
409 * @param callback Callback to invoke when the request completes,
410 * null for no callback
411 * @param handler {@link Handler} identifying the callback thread,
412 * null for the main thread
413 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
414 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800415 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800416 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800417 final String[] features,
418 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700419 if (account == null) throw new IllegalArgumentException("account is null");
420 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800421 return new Future2Task<Boolean>(handler, callback) {
422 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800423 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800424 }
425 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
426 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
427 throw new AuthenticatorException("no result in response");
428 }
429 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
430 }
431 }.start();
432 }
433
434 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800435 * Lists all accounts of a type which have certain features. The account
436 * type identifies the authenticator (see {@link #getAccountsByType}).
437 * Account features are authenticator-specific string tokens identifying
438 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700439 *
Dan Egnor661f0132010-02-19 11:23:00 -0800440 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
441 * which may contact the server or do other work to check account features,
442 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700443 *
Dan Egnor661f0132010-02-19 11:23:00 -0800444 * <p>This method may be called from any thread, but the returned
445 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700446 *
Dan Egnor661f0132010-02-19 11:23:00 -0800447 * <p>This method requires the caller to hold the permission
448 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700449 *
Dan Egnor661f0132010-02-19 11:23:00 -0800450 * @param type The type of accounts to return, must not be null
451 * @param features An array of the account features to require,
452 * may be null or empty
453 * @param callback Callback to invoke when the request completes,
454 * null for no callback
455 * @param handler {@link Handler} identifying the callback thread,
456 * null for the main thread
457 * @return An {@link AccountManagerFuture} which resolves to an array of
458 * {@link Account}, one per account of the specified type which
459 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800460 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700461 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
462 final String type, final String[] features,
463 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700464 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700465 return new Future2Task<Account[]>(handler, callback) {
466 public void doWork() throws RemoteException {
467 mService.getAccountsByFeatures(mResponse, type, features);
468 }
469 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700470 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700471 throw new AuthenticatorException("no result in response");
472 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700473 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700474 Account[] descs = new Account[parcelables.length];
475 for (int i = 0; i < parcelables.length; i++) {
476 descs[i] = (Account) parcelables[i];
477 }
478 return descs;
479 }
480 }.start();
481 }
482
Fred Quintana756b7352009-10-21 13:43:10 -0700483 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800484 * Adds an account directly to the AccountManager. Normally used by sign-up
485 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700486 *
Dan Egnor661f0132010-02-19 11:23:00 -0800487 * <p>It is safe to call this method from the main thread.
488 *
489 * <p>This method requires the caller to hold the permission
490 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
491 * and to have the same UID as the added account's authenticator.
492 *
493 * @param account The {@link Account} to add
494 * @param password The password to associate with the account, null for none
495 * @param userdata String values to use for the account's userdata, null for none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700496 * @return True if the account was successfully added, false if the account
Dan Egnor661f0132010-02-19 11:23:00 -0800497 * already exists, the account is null, or another error occurs.
498 */
499 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700500 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800501 try {
502 return mService.addAccount(account, password, userdata);
503 } catch (RemoteException e) {
504 // won't ever happen
505 throw new RuntimeException(e);
506 }
507 }
508
509 /**
510 * Removes an account from the AccountManager. Does nothing if the account
511 * does not exist. Does not delete the account from the server.
512 * The authenticator may have its own policies preventing account
513 * deletion, in which case the account will not be deleted.
514 *
515 * <p>This method may be called from any thread, but the returned
516 * {@link AccountManagerFuture} must not be used on the main thread.
517 *
518 * <p>This method requires the caller to hold the permission
519 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
520 *
521 * @param account The {@link Account} to remove
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 a Boolean,
527 * true if the account has been successfully removed,
528 * false if the authenticator forbids deleting this account.
529 */
530 public AccountManagerFuture<Boolean> removeAccount(final Account account,
531 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700532 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800533 return new Future2Task<Boolean>(handler, callback) {
534 public void doWork() throws RemoteException {
535 mService.removeAccount(mResponse, account);
536 }
537 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
538 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
539 throw new AuthenticatorException("no result in response");
540 }
541 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
542 }
543 }.start();
544 }
545
546 /**
547 * Removes an auth token from the AccountManager's cache. Does nothing if
548 * the auth token is not currently in the cache. Applications must call this
549 * method when the auth token is found to have expired or otherwise become
550 * invalid for authenticating requests. The AccountManager does not validate
551 * or expire cached auth tokens otherwise.
552 *
553 * <p>It is safe to call this method from the main thread.
554 *
555 * <p>This method requires the caller to hold the permission
Fred Quintanab38eb142010-02-24 13:40:54 -0800556 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
557 * {@link android.Manifest.permission#USE_CREDENTIALS}
Dan Egnor661f0132010-02-19 11:23:00 -0800558 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700559 * @param accountType The account type of the auth token to invalidate, must not be null
560 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800561 */
562 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700563 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800564 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700565 if (authToken != null) {
566 mService.invalidateAuthToken(accountType, authToken);
567 }
Dan Egnor661f0132010-02-19 11:23:00 -0800568 } catch (RemoteException e) {
569 // won't ever happen
570 throw new RuntimeException(e);
571 }
572 }
573
574 /**
575 * Gets an auth token from the AccountManager's cache. If no auth
576 * token is cached for this account, null will be returned -- a new
577 * auth token will not be generated, and the server will not be contacted.
578 * Intended for use by the authenticator, not directly by applications.
579 *
580 * <p>It is safe to call this method from the main thread.
581 *
582 * <p>This method requires the caller to hold the permission
583 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
584 * and to have the same UID as the account's authenticator.
585 *
586 * @param account The account to fetch an auth token for
587 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
588 * @return The cached auth token for this account and type, or null if
589 * no auth token is cached or the account does not exist.
590 */
591 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700592 if (account == null) throw new IllegalArgumentException("account is null");
593 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800594 try {
595 return mService.peekAuthToken(account, authTokenType);
596 } catch (RemoteException e) {
597 // won't ever happen
598 throw new RuntimeException(e);
599 }
600 }
601
602 /**
603 * Sets or forgets a saved password. This modifies the local copy of the
604 * password used to automatically authenticate the user; it does
605 * not change the user's account password on the server. Intended for use
606 * by the authenticator, not directly by applications.
607 *
608 * <p>It is safe to call this method from the main thread.
609 *
610 * <p>This method requires the caller to hold the permission
611 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
612 * and have the same UID as the account's authenticator.
613 *
614 * @param account The account to set a password for
615 * @param password The password to set, null to clear the password
616 */
617 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700618 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800619 try {
620 mService.setPassword(account, password);
621 } catch (RemoteException e) {
622 // won't ever happen
623 throw new RuntimeException(e);
624 }
625 }
626
627 /**
628 * Forgets a saved password. This erases the local copy of the password;
629 * it does not change the user's account password on the server.
630 * Has the same effect as setPassword(account, null) but requires fewer
631 * permissions, and may be used by applications or management interfaces
632 * to "sign out" from an account.
633 *
634 * <p>It is safe to call this method from the main thread.
635 *
636 * <p>This method requires the caller to hold the permission
637 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
638 *
639 * @param account The account whose password to clear
640 */
641 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700642 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800643 try {
644 mService.clearPassword(account);
645 } catch (RemoteException e) {
646 // won't ever happen
647 throw new RuntimeException(e);
648 }
649 }
650
651 /**
652 * Sets one userdata key for an account. Intended by use for the
653 * authenticator to stash state for itself, not directly by applications.
654 * The meaning of the keys and values is up to the authenticator.
655 *
656 * <p>It is safe to call this method from the main thread.
657 *
658 * <p>This method requires the caller to hold the permission
659 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
660 * and to have the same UID as the account's authenticator.
661 *
662 * @param account The account to set the userdata for
663 * @param key The userdata key to set. Must not be null
664 * @param value The value to set, null to clear this userdata key
665 */
666 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -0700667 if (account == null) throw new IllegalArgumentException("account is null");
668 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800669 try {
670 mService.setUserData(account, key, value);
671 } catch (RemoteException e) {
672 // won't ever happen
673 throw new RuntimeException(e);
674 }
675 }
676
677 /**
678 * Adds an auth token to the AccountManager cache for an account.
679 * If the account does not exist then this call has no effect.
680 * Replaces any previous auth token for this account and auth token type.
681 * Intended for use by the authenticator, not directly by applications.
682 *
683 * <p>It is safe to call this method from the main thread.
684 *
685 * <p>This method requires the caller to hold the permission
686 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
687 * and to have the same UID as the account's authenticator.
688 *
689 * @param account The account to set an auth token for
690 * @param authTokenType The type of the auth token, see {#getAuthToken}
691 * @param authToken The auth token to add to the cache
692 */
693 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700694 if (account == null) throw new IllegalArgumentException("account is null");
695 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800696 try {
697 mService.setAuthToken(account, authTokenType, authToken);
698 } catch (RemoteException e) {
699 // won't ever happen
700 throw new RuntimeException(e);
701 }
702 }
703
704 /**
705 * This convenience helper synchronously gets an auth token with
706 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
707 *
708 * <p>This method may block while a network request completes, and must
709 * never be made from the main thread.
710 *
711 * <p>This method requires the caller to hold the permission
712 * {@link android.Manifest.permission#USE_CREDENTIALS}.
713 *
714 * @param account The account to fetch an auth token for
715 * @param authTokenType The auth token type, see {#link getAuthToken}
716 * @param notifyAuthFailure If true, display a notification and return null
717 * if authentication fails; if false, prompt and wait for the user to
718 * re-enter correct credentials before returning
719 * @return An auth token of the specified type for this account, or null
720 * if authentication fails or none can be fetched.
721 * @throws AuthenticatorException if the authenticator failed to respond
722 * @throws OperationCanceledException if the request was canceled for any
723 * reason, including the user canceling a credential request
724 * @throws java.io.IOException if the authenticator experienced an I/O problem
725 * creating a new auth token, usually because of network trouble
726 */
727 public String blockingGetAuthToken(Account account, String authTokenType,
728 boolean notifyAuthFailure)
729 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -0700730 if (account == null) throw new IllegalArgumentException("account is null");
731 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800732 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
733 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -0800734 if (bundle == null) {
735 // This should never happen, but it does, occasionally. If it does return null to
736 // signify that we were not able to get the authtoken.
737 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
738 // returned
739 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
740 + account + ", authTokenType " + authTokenType);
741 return null;
742 }
Dan Egnor661f0132010-02-19 11:23:00 -0800743 return bundle.getString(KEY_AUTHTOKEN);
744 }
745
746 /**
747 * Gets an auth token of the specified type for a particular account,
748 * prompting the user for credentials if necessary. This method is
749 * intended for applications running in the foreground where it makes
750 * sense to ask the user directly for a password.
751 *
752 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700753 * type, then it is returned. Otherwise, if a saved password is
754 * available, it is sent to the server to generate a new auth token.
755 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -0800756 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700757 * <p>Some authenticators have auth token <em>types</em>, whose value
758 * is authenticator-dependent. Some services use different token types to
759 * access different functionality -- for example, Google uses different auth
760 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -0800761 *
762 * <p>This method may be called from any thread, but the returned
763 * {@link AccountManagerFuture} must not be used on the main thread.
764 *
765 * <p>This method requires the caller to hold the permission
766 * {@link android.Manifest.permission#USE_CREDENTIALS}.
767 *
768 * @param account The account to fetch an auth token for
769 * @param authTokenType The auth token type, an authenticator-dependent
770 * string token, must not be null
771 * @param options Authenticator-specific options for the request,
772 * may be null or empty
773 * @param activity The {@link Activity} context to use for launching a new
774 * authenticator-defined sub-Activity to prompt the user for a password
775 * if necessary; used only to call startActivity(); must not be null.
776 * @param callback Callback to invoke when the request completes,
777 * null for no callback
778 * @param handler {@link Handler} identifying the callback thread,
779 * null for the main thread
780 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
781 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -0700782 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800783 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
784 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
785 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -0700786 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800787 *
788 * (Other authenticator-specific values may be returned.) If an auth token
789 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
790 * <ul>
791 * <li> {@link AuthenticatorException} if the authenticator failed to respond
792 * <li> {@link OperationCanceledException} if the operation is canceled for
793 * any reason, incluidng the user canceling a credential request
794 * <li> {@link IOException} if the authenticator experienced an I/O problem
795 * creating a new auth token, usually because of network trouble
796 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -0700797 * If the account is no longer present on the device, the return value is
798 * authenticator-dependent. The caller should verify the validity of the
799 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -0800800 */
801 public AccountManagerFuture<Bundle> getAuthToken(
802 final Account account, final String authTokenType, final Bundle options,
803 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700804 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800805 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
806 return new AmsTask(activity, handler, callback) {
807 public void doWork() throws RemoteException {
808 mService.getAuthToken(mResponse, account, authTokenType,
809 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
810 options);
811 }
812 }.start();
813 }
814
815 /**
816 * Gets an auth token of the specified type for a particular account,
817 * optionally raising a notification if the user must enter credentials.
818 * This method is intended for background tasks and services where the
819 * user should not be immediately interrupted with a password prompt.
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, an {@link Intent} is returned which, when started, will
825 * prompt the user for a password. If the notifyAuthFailure parameter is
826 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -0800827 * alerting the user that they need to enter a password at some point.
828 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700829 * <p>In that case, you may need to wait until the user responds, which
830 * could take hours or days or forever. When the user does respond and
831 * supply a new password, the account manager will broadcast the
832 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
833 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -0800834 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700835 * <p>If notifyAuthFailure is not set, it is the application's
836 * responsibility to launch the returned Intent at some point.
837 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -0800838 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700839 * <p>Some authenticators have auth token <em>types</em>, whose value
840 * is authenticator-dependent. Some services use different token types to
841 * access different functionality -- for example, Google uses different auth
842 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -0800843 *
844 * <p>This method may be called from any thread, but the returned
845 * {@link AccountManagerFuture} must not be used on the main thread.
846 *
847 * <p>This method requires the caller to hold the permission
848 * {@link android.Manifest.permission#USE_CREDENTIALS}.
849 *
850 * @param account The account to fetch an auth token for
851 * @param authTokenType The auth token type, an authenticator-dependent
852 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -0800853 * @param notifyAuthFailure True to add a notification to prompt the
854 * user for a password if necessary, false to leave that to the caller
855 * @param callback Callback to invoke when the request completes,
856 * null for no callback
857 * @param handler {@link Handler} identifying the callback thread,
858 * null for the main thread
859 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
860 * at least the following fields on success:
861 * <ul>
862 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
863 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
864 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
865 * </ul>
866 *
867 * (Other authenticator-specific values may be returned.) If the user
868 * must enter credentials, the returned Bundle contains only
869 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
870 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700871 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -0800872 * <ul>
873 * <li> {@link AuthenticatorException} if the authenticator failed to respond
874 * <li> {@link OperationCanceledException} if the operation is canceled for
875 * any reason, incluidng the user canceling a credential request
876 * <li> {@link IOException} if the authenticator experienced an I/O problem
877 * creating a new auth token, usually because of network trouble
878 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -0700879 * If the account is no longer present on the device, the return value is
880 * authenticator-dependent. The caller should verify the validity of the
881 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -0800882 */
883 public AccountManagerFuture<Bundle> getAuthToken(
884 final Account account, final String authTokenType, final boolean notifyAuthFailure,
885 AccountManagerCallback<Bundle> callback, Handler handler) {
886 if (account == null) throw new IllegalArgumentException("account is null");
887 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
888 return new AmsTask(null, handler, callback) {
889 public void doWork() throws RemoteException {
890 mService.getAuthToken(mResponse, account, authTokenType,
891 notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
892 }
893 }.start();
894 }
895
896 /**
897 * Asks the user to add an account of a specified type. The authenticator
898 * for this account type processes this request with the appropriate user
899 * interface. If the user does elect to create a new account, the account
900 * name is returned.
901 *
902 * <p>This method may be called from any thread, but the returned
903 * {@link AccountManagerFuture} must not be used on the main thread.
904 *
905 * <p>This method requires the caller to hold the permission
906 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
907 *
908 * @param accountType The type of account to add; must not be null
909 * @param authTokenType The type of auth token (see {@link #getAuthToken})
910 * this account will need to be able to generate, null for none
911 * @param requiredFeatures The features (see {@link #hasFeatures}) this
912 * account must have, null for none
913 * @param addAccountOptions Authenticator-specific options for the request,
914 * may be null or empty
915 * @param activity The {@link Activity} context to use for launching a new
916 * authenticator-defined sub-Activity to prompt the user to create an
917 * account; used only to call startActivity(); if null, the prompt
918 * will not be launched directly, but the necessary {@link Intent}
919 * will be returned to the caller instead
920 * @param callback Callback to invoke when the request completes,
921 * null for no callback
922 * @param handler {@link Handler} identifying the callback thread,
923 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -0800924 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -0800925 * these fields if activity was specified and an account was created:
926 * <ul>
927 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
928 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
929 * </ul>
930 *
931 * If no activity was specified, the returned Bundle contains only
932 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700933 * actual account creation process. If an error occurred,
934 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -0800935 * <ul>
936 * <li> {@link AuthenticatorException} if no authenticator was registered for
937 * this account type or the authenticator failed to respond
938 * <li> {@link OperationCanceledException} if the operation was canceled for
939 * any reason, including the user canceling the creation process
940 * <li> {@link IOException} if the authenticator experienced an I/O problem
941 * creating a new account, usually because of network trouble
942 * </ul>
943 */
944 public AccountManagerFuture<Bundle> addAccount(final String accountType,
945 final String authTokenType, final String[] requiredFeatures,
946 final Bundle addAccountOptions,
947 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700948 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800949 return new AmsTask(activity, handler, callback) {
950 public void doWork() throws RemoteException {
Dan Egnor661f0132010-02-19 11:23:00 -0800951 mService.addAcount(mResponse, accountType, authTokenType,
952 requiredFeatures, activity != null, addAccountOptions);
953 }
954 }.start();
955 }
956
957 /**
958 * Confirms that the user knows the password for an account to make extra
959 * sure they are the owner of the account. The user-entered password can
960 * be supplied directly, otherwise the authenticator for this account type
961 * prompts the user with the appropriate interface. This method is
962 * intended for applications which want extra assurance; for example, the
963 * phone lock screen uses this to let the user unlock the phone with an
964 * account password if they forget the lock pattern.
965 *
966 * <p>If the user-entered password matches a saved password for this
967 * account, the request is considered valid; otherwise the authenticator
968 * verifies the password (usually by contacting the server).
969 *
970 * <p>This method may be called from any thread, but the returned
971 * {@link AccountManagerFuture} must not be used on the main thread.
972 *
973 * <p>This method requires the caller to hold the permission
974 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
975 *
976 * @param account The account to confirm password knowledge for
977 * @param options Authenticator-specific options for the request;
978 * if the {@link #KEY_PASSWORD} string field is present, the
979 * authenticator may use it directly rather than prompting the user;
980 * may be null or empty
981 * @param activity The {@link Activity} context to use for launching a new
982 * authenticator-defined sub-Activity to prompt the user to enter a
983 * password; used only to call startActivity(); if null, the prompt
984 * will not be launched directly, but the necessary {@link Intent}
985 * will be returned to the caller instead
986 * @param callback Callback to invoke when the request completes,
987 * null for no callback
988 * @param handler {@link Handler} identifying the callback thread,
989 * null for the main thread
990 * @return An {@link AccountManagerFuture} which resolves to a Bundle
991 * with these fields if activity or password was supplied and
992 * the account was successfully verified:
993 * <ul>
994 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
995 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
996 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
997 * </ul>
998 *
999 * If no activity or password was specified, the returned Bundle contains
1000 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001001 * password prompt. If an error occurred,
1002 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001003 * <ul>
1004 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1005 * <li> {@link OperationCanceledException} if the operation was canceled for
1006 * any reason, including the user canceling the password prompt
1007 * <li> {@link IOException} if the authenticator experienced an I/O problem
1008 * verifying the password, usually because of network trouble
1009 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001010 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001011 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1012 final Bundle options,
1013 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001014 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001015 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001016 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001017 return new AmsTask(activity, handler, callback) {
1018 public void doWork() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001019 mService.confirmCredentials(mResponse, account, options, activity != null);
Fred Quintanaa698f422009-04-08 19:14:54 -07001020 }
Fred Quintana33269202009-04-20 16:05:10 -07001021 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001022 }
1023
Fred Quintana756b7352009-10-21 13:43:10 -07001024 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001025 * Asks the user to enter a new password for an account, updating the
1026 * saved credentials for the account. Normally this happens automatically
1027 * when the server rejects credentials during an auth token fetch, but this
1028 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001029 *
Dan Egnor661f0132010-02-19 11:23:00 -08001030 * <p>This method may be called from any thread, but the returned
1031 * {@link AccountManagerFuture} must not be used on the main thread.
1032 *
1033 * <p>This method requires the caller to hold the permission
1034 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1035 *
1036 * @param account The account to update credentials for
1037 * @param authTokenType The credentials entered must allow an auth token
1038 * of this type to be created (but no actual auth token is returned);
1039 * may be null
1040 * @param options Authenticator-specific options for the request;
1041 * may be null or empty
1042 * @param activity The {@link Activity} context to use for launching a new
1043 * authenticator-defined sub-Activity to prompt the user to enter a
1044 * password; used only to call startActivity(); if null, the prompt
1045 * will not be launched directly, but the necessary {@link Intent}
1046 * will be returned to the caller instead
1047 * @param callback Callback to invoke when the request completes,
1048 * null for no callback
1049 * @param handler {@link Handler} identifying the callback thread,
1050 * null for the main thread
1051 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1052 * with these fields if an activity was supplied and the account
1053 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001054 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001055 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1056 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001057 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001058 *
1059 * If no activity was specified, the returned Bundle contains only
1060 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001061 * password prompt. If an error occurred,
1062 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001063 * <ul>
1064 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1065 * <li> {@link OperationCanceledException} if the operation was canceled for
1066 * any reason, including the user canceling the password prompt
1067 * <li> {@link IOException} if the authenticator experienced an I/O problem
1068 * verifying the password, usually because of network trouble
1069 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001070 */
1071 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1072 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001073 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001074 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001075 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001076 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001077 return new AmsTask(activity, handler, callback) {
1078 public void doWork() throws RemoteException {
1079 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001080 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001081 }
Fred Quintana33269202009-04-20 16:05:10 -07001082 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001083 }
1084
Fred Quintana756b7352009-10-21 13:43:10 -07001085 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001086 * Offers the user an opportunity to change an authenticator's settings.
1087 * These properties are for the authenticator in general, not a particular
1088 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001089 *
Dan Egnor661f0132010-02-19 11:23:00 -08001090 * <p>This method may be called from any thread, but the returned
1091 * {@link AccountManagerFuture} must not be used on the main thread.
1092 *
1093 * <p>This method requires the caller to hold the permission
1094 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1095 *
1096 * @param accountType The account type associated with the authenticator
1097 * to adjust
1098 * @param activity The {@link Activity} context to use for launching a new
1099 * authenticator-defined sub-Activity to adjust authenticator settings;
1100 * used only to call startActivity(); if null, the settings dialog will
1101 * not be launched directly, but the necessary {@link Intent} will be
1102 * returned to the caller instead
1103 * @param callback Callback to invoke when the request completes,
1104 * null for no callback
1105 * @param handler {@link Handler} identifying the callback thread,
1106 * null for the main thread
1107 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1108 * which is empty if properties were edited successfully, or
1109 * if no activity was specified, contains only {@link #KEY_INTENT}
1110 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001111 * If an error occurred, {@link AccountManagerFuture#getResult()}
1112 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001113 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001114 * <li> {@link AuthenticatorException} if no authenticator was registered for
1115 * this account type or the authenticator failed to respond
1116 * <li> {@link OperationCanceledException} if the operation was canceled for
1117 * any reason, including the user canceling the settings dialog
1118 * <li> {@link IOException} if the authenticator experienced an I/O problem
1119 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001120 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001121 */
1122 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1123 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001124 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001125 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001126 return new AmsTask(activity, handler, callback) {
1127 public void doWork() throws RemoteException {
1128 mService.editProperties(mResponse, accountType, activity != null);
1129 }
Fred Quintana33269202009-04-20 16:05:10 -07001130 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001131 }
1132
1133 private void ensureNotOnMainThread() {
1134 final Looper looper = Looper.myLooper();
1135 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001136 final IllegalStateException exception = new IllegalStateException(
1137 "calling this from your main thread can lead to deadlock");
1138 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1139 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001140 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1141 throw exception;
1142 }
Fred Quintana60307342009-03-24 22:48:12 -07001143 }
1144 }
1145
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001146 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1147 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001148 handler = handler == null ? mMainHandler : handler;
1149 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001150 public void run() {
1151 callback.run(future);
1152 }
1153 });
1154 }
Fred Quintana60307342009-03-24 22:48:12 -07001155
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001156 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001157 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001158 final Account[] accountsCopy = new Account[accounts.length];
1159 // send a copy to make sure that one doesn't
1160 // change what another sees
1161 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1162 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001163 handler.post(new Runnable() {
1164 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001165 try {
1166 listener.onAccountsUpdated(accountsCopy);
1167 } catch (SQLException e) {
1168 // Better luck next time. If the problem was disk-full,
1169 // the STORAGE_OK intent will re-trigger the update.
1170 Log.e(TAG, "Can't update accounts", e);
1171 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001172 }
1173 });
1174 }
1175
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001176 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001177 final IAccountManagerResponse mResponse;
1178 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001179 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001180 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001181 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001182 super(new Callable<Bundle>() {
1183 public Bundle call() throws Exception {
1184 throw new IllegalStateException("this should never be called");
1185 }
1186 });
1187
1188 mHandler = handler;
1189 mCallback = callback;
1190 mActivity = activity;
1191 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001192 }
1193
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001194 public final AccountManagerFuture<Bundle> start() {
1195 try {
1196 doWork();
1197 } catch (RemoteException e) {
1198 setException(e);
1199 }
Fred Quintana33269202009-04-20 16:05:10 -07001200 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001201 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001202
Fred Quintana96580e02010-03-04 13:42:42 -08001203 protected void set(Bundle bundle) {
1204 // TODO: somehow a null is being set as the result of the Future. Log this
1205 // case to help debug where this is occurring. When this bug is fixed this
1206 // condition statement should be removed.
1207 if (bundle == null) {
1208 Log.e(TAG, "the bundle must not be null", new Exception());
1209 }
1210 super.set(bundle);
1211 }
1212
Fred Quintanaa698f422009-04-08 19:14:54 -07001213 public abstract void doWork() throws RemoteException;
1214
1215 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1216 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001217 if (!isDone()) {
1218 ensureNotOnMainThread();
1219 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001220 try {
1221 if (timeout == null) {
1222 return get();
1223 } else {
1224 return get(timeout, unit);
1225 }
1226 } catch (CancellationException e) {
1227 throw new OperationCanceledException();
1228 } catch (TimeoutException e) {
1229 // fall through and cancel
1230 } catch (InterruptedException e) {
1231 // fall through and cancel
1232 } catch (ExecutionException e) {
1233 final Throwable cause = e.getCause();
1234 if (cause instanceof IOException) {
1235 throw (IOException) cause;
1236 } else if (cause instanceof UnsupportedOperationException) {
1237 throw new AuthenticatorException(cause);
1238 } else if (cause instanceof AuthenticatorException) {
1239 throw (AuthenticatorException) cause;
1240 } else if (cause instanceof RuntimeException) {
1241 throw (RuntimeException) cause;
1242 } else if (cause instanceof Error) {
1243 throw (Error) cause;
1244 } else {
1245 throw new IllegalStateException(cause);
1246 }
1247 } finally {
1248 cancel(true /* interrupt if running */);
1249 }
1250 throw new OperationCanceledException();
1251 }
1252
1253 public Bundle getResult()
1254 throws OperationCanceledException, IOException, AuthenticatorException {
1255 return internalGetResult(null, null);
1256 }
1257
1258 public Bundle getResult(long timeout, TimeUnit unit)
1259 throws OperationCanceledException, IOException, AuthenticatorException {
1260 return internalGetResult(timeout, unit);
1261 }
1262
1263 protected void done() {
1264 if (mCallback != null) {
1265 postToHandler(mHandler, mCallback, this);
1266 }
1267 }
1268
1269 /** Handles the responses from the AccountManager */
1270 private class Response extends IAccountManagerResponse.Stub {
1271 public void onResult(Bundle bundle) {
1272 Intent intent = bundle.getParcelable("intent");
1273 if (intent != null && mActivity != null) {
1274 // since the user provided an Activity we will silently start intents
1275 // that we see
1276 mActivity.startActivity(intent);
1277 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001278 } else if (bundle.getBoolean("retry")) {
1279 try {
1280 doWork();
1281 } catch (RemoteException e) {
1282 // this will only happen if the system process is dead, which means
1283 // we will be dying ourselves
1284 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001285 } else {
1286 set(bundle);
1287 }
1288 }
1289
1290 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001291 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001292 // the authenticator indicated that this request was canceled, do so now
1293 cancel(true /* mayInterruptIfRunning */);
1294 return;
1295 }
1296 setException(convertErrorToException(code, message));
1297 }
1298 }
1299
Fred Quintana60307342009-03-24 22:48:12 -07001300 }
1301
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001302 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1303 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001304 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001305
1306 public BaseFutureTask(Handler handler) {
1307 super(new Callable<T>() {
1308 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001309 throw new IllegalStateException("this should never be called");
1310 }
1311 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001312 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001313 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001314 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001315
1316 public abstract void doWork() throws RemoteException;
1317
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001318 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001319
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001320 protected void postRunnableToHandler(Runnable runnable) {
1321 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1322 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001323 }
1324
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001325 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001326 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001327 doWork();
1328 } catch (RemoteException e) {
1329 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001330 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001331 }
1332
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001333 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001334 public void onResult(Bundle bundle) {
1335 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001336 T result = bundleToResult(bundle);
1337 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001338 return;
1339 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001340 set(result);
1341 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001342 } catch (ClassCastException e) {
1343 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001344 } catch (AuthenticatorException e) {
1345 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001346 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001347 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001348 }
1349
1350 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001351 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001352 cancel(true /* mayInterruptIfRunning */);
1353 return;
1354 }
1355 setException(convertErrorToException(code, message));
1356 }
1357 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001358 }
1359
1360 private abstract class Future2Task<T>
1361 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1362 final AccountManagerCallback<T> mCallback;
1363 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1364 super(handler);
1365 mCallback = callback;
1366 }
1367
1368 protected void done() {
1369 if (mCallback != null) {
1370 postRunnableToHandler(new Runnable() {
1371 public void run() {
1372 mCallback.run(Future2Task.this);
1373 }
1374 });
1375 }
1376 }
1377
1378 public Future2Task<T> start() {
1379 startTask();
1380 return this;
1381 }
1382
1383 private T internalGetResult(Long timeout, TimeUnit unit)
1384 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001385 if (!isDone()) {
1386 ensureNotOnMainThread();
1387 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001388 try {
1389 if (timeout == null) {
1390 return get();
1391 } else {
1392 return get(timeout, unit);
1393 }
1394 } catch (InterruptedException e) {
1395 // fall through and cancel
1396 } catch (TimeoutException e) {
1397 // fall through and cancel
1398 } catch (CancellationException e) {
1399 // fall through and cancel
1400 } catch (ExecutionException e) {
1401 final Throwable cause = e.getCause();
1402 if (cause instanceof IOException) {
1403 throw (IOException) cause;
1404 } else if (cause instanceof UnsupportedOperationException) {
1405 throw new AuthenticatorException(cause);
1406 } else if (cause instanceof AuthenticatorException) {
1407 throw (AuthenticatorException) cause;
1408 } else if (cause instanceof RuntimeException) {
1409 throw (RuntimeException) cause;
1410 } else if (cause instanceof Error) {
1411 throw (Error) cause;
1412 } else {
1413 throw new IllegalStateException(cause);
1414 }
1415 } finally {
1416 cancel(true /* interrupt if running */);
1417 }
1418 throw new OperationCanceledException();
1419 }
1420
1421 public T getResult()
1422 throws OperationCanceledException, IOException, AuthenticatorException {
1423 return internalGetResult(null, null);
1424 }
1425
1426 public T getResult(long timeout, TimeUnit unit)
1427 throws OperationCanceledException, IOException, AuthenticatorException {
1428 return internalGetResult(timeout, unit);
1429 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001430
Fred Quintana60307342009-03-24 22:48:12 -07001431 }
1432
Fred Quintanaa698f422009-04-08 19:14:54 -07001433 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001434 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001435 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001436 }
Fred Quintana60307342009-03-24 22:48:12 -07001437
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001438 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07001439 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001440 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001441
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001442 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07001443 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07001444 }
1445
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001446 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07001447 return new IllegalArgumentException(message);
1448 }
1449
1450 return new AuthenticatorException(message);
1451 }
1452
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001453 private class GetAuthTokenByTypeAndFeaturesTask
1454 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07001455 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1456 final String[] features, Activity activityForPrompting,
1457 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001458 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001459 super(activityForPrompting, handler, callback);
1460 if (accountType == null) throw new IllegalArgumentException("account type is null");
1461 mAccountType = accountType;
1462 mAuthTokenType = authTokenType;
1463 mFeatures = features;
1464 mAddAccountOptions = addAccountOptions;
1465 mLoginOptions = loginOptions;
1466 mMyCallback = this;
1467 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001468 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07001469 final String mAccountType;
1470 final String mAuthTokenType;
1471 final String[] mFeatures;
1472 final Bundle mAddAccountOptions;
1473 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001474 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001475 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07001476
1477 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001478 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1479 new AccountManagerCallback<Account[]>() {
1480 public void run(AccountManagerFuture<Account[]> future) {
1481 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07001482 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001483 accounts = future.getResult();
1484 } catch (OperationCanceledException e) {
1485 setException(e);
1486 return;
1487 } catch (IOException e) {
1488 setException(e);
1489 return;
1490 } catch (AuthenticatorException e) {
1491 setException(e);
1492 return;
Fred Quintana33269202009-04-20 16:05:10 -07001493 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001494
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001495 mNumAccounts = accounts.length;
1496
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001497 if (accounts.length == 0) {
1498 if (mActivity != null) {
1499 // no accounts, add one now. pretend that the user directly
1500 // made this request
1501 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1502 mAddAccountOptions, mActivity, mMyCallback, mHandler);
1503 } else {
1504 // send result since we can't prompt to add an account
1505 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001506 result.putString(KEY_ACCOUNT_NAME, null);
1507 result.putString(KEY_ACCOUNT_TYPE, null);
1508 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001509 try {
1510 mResponse.onResult(result);
1511 } catch (RemoteException e) {
1512 // this will never happen
1513 }
1514 // we are done
1515 }
1516 } else if (accounts.length == 1) {
1517 // have a single account, return an authtoken for it
1518 if (mActivity == null) {
1519 mFuture = getAuthToken(accounts[0], mAuthTokenType,
1520 false /* notifyAuthFailure */, mMyCallback, mHandler);
1521 } else {
1522 mFuture = getAuthToken(accounts[0],
1523 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07001524 mActivity, mMyCallback, mHandler);
1525 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001526 } else {
1527 if (mActivity != null) {
1528 IAccountManagerResponse chooseResponse =
1529 new IAccountManagerResponse.Stub() {
1530 public void onResult(Bundle value) throws RemoteException {
1531 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001532 value.getString(KEY_ACCOUNT_NAME),
1533 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001534 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1535 mActivity, mMyCallback, mHandler);
1536 }
Fred Quintana33269202009-04-20 16:05:10 -07001537
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001538 public void onError(int errorCode, String errorMessage)
1539 throws RemoteException {
1540 mResponse.onError(errorCode, errorMessage);
1541 }
1542 };
1543 // have many accounts, launch the chooser
1544 Intent intent = new Intent();
1545 intent.setClassName("android",
1546 "android.accounts.ChooseAccountActivity");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001547 intent.putExtra(KEY_ACCOUNTS, accounts);
1548 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001549 new AccountManagerResponse(chooseResponse));
1550 mActivity.startActivity(intent);
1551 // the result will arrive via the IAccountManagerResponse
1552 } else {
1553 // send result since we can't prompt to select an account
1554 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001555 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001556 try {
1557 mResponse.onResult(result);
1558 } catch (RemoteException e) {
1559 // this will never happen
1560 }
1561 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07001562 }
Fred Quintana33269202009-04-20 16:05:10 -07001563 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001564 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07001565 }
1566
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001567 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07001568 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08001569 final Bundle result = future.getResult();
1570 if (mNumAccounts == 0) {
1571 final String accountName = result.getString(KEY_ACCOUNT_NAME);
1572 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
1573 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
1574 setException(new AuthenticatorException("account not in result"));
1575 return;
1576 }
1577 final Account account = new Account(accountName, accountType);
1578 mNumAccounts = 1;
1579 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
1580 mMyCallback, mHandler);
1581 return;
1582 }
1583 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001584 } catch (OperationCanceledException e) {
1585 cancel(true /* mayInterruptIfRUnning */);
1586 } catch (IOException e) {
1587 setException(e);
1588 } catch (AuthenticatorException e) {
1589 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07001590 }
1591 }
1592 }
1593
Fred Quintana756b7352009-10-21 13:43:10 -07001594 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001595 * This convenience helper combines the functionality of
1596 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1597 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07001598 *
Dan Egnor661f0132010-02-19 11:23:00 -08001599 * <p>This method gets a list of the accounts matching the
1600 * specified type and feature set; if there is exactly one, it is
1601 * used; if there are more than one, the user is prompted to pick one;
1602 * if there are none, the user is prompted to add one. Finally,
1603 * an auth token is acquired for the chosen account.
1604 *
1605 * <p>This method may be called from any thread, but the returned
1606 * {@link AccountManagerFuture} must not be used on the main thread.
1607 *
1608 * <p>This method requires the caller to hold the permission
1609 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1610 *
1611 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08001612 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001613 * @param authTokenType The desired auth token type
1614 * (see {@link #getAuthToken}), must not be null
1615 * @param features Required features for the account
1616 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1617 * @param activity The {@link Activity} context to use for launching new
1618 * sub-Activities to prompt to add an account, select an account,
1619 * and/or enter a password, as necessary; used only to call
1620 * startActivity(); should not be null
1621 * @param addAccountOptions Authenticator-specific options to use for
1622 * adding new accounts; may be null or empty
1623 * @param getAuthTokenOptions Authenticator-specific options to use for
1624 * getting auth tokens; may be null or empty
1625 * @param callback Callback to invoke when the request completes,
1626 * null for no callback
1627 * @param handler {@link Handler} identifying the callback thread,
1628 * null for the main thread
1629 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1630 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001631 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001632 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1633 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1634 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001635 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001636 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001637 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001638 * <ul>
1639 * <li> {@link AuthenticatorException} if no authenticator was registered for
1640 * this account type or the authenticator failed to respond
1641 * <li> {@link OperationCanceledException} if the operation was canceled for
1642 * any reason, including the user canceling any operation
1643 * <li> {@link IOException} if the authenticator experienced an I/O problem
1644 * updating settings, usually because of network trouble
1645 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001646 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001647 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07001648 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08001649 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07001650 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001651 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001652 if (accountType == null) throw new IllegalArgumentException("account type is null");
1653 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001654 final GetAuthTokenByTypeAndFeaturesTask task =
1655 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08001656 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001657 task.start();
1658 return task;
Fred Quintana60307342009-03-24 22:48:12 -07001659 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001660
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001661 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07001662 Maps.newHashMap();
1663
Fred Quintanad9d2f112009-04-23 13:36:27 -07001664 /**
1665 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1666 * so that it can read the updated list of accounts and send them to the listener
1667 * in mAccountsUpdatedListeners.
1668 */
1669 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1670 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001671 final Account[] accounts = getAccounts();
1672 // send the result to the listeners
1673 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001674 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001675 mAccountsUpdatedListeners.entrySet()) {
1676 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001677 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001678 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001679 }
1680 };
1681
1682 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001683 * Adds an {@link OnAccountsUpdateListener} to this instance of the
1684 * {@link AccountManager}. This listener will be notified whenever the
1685 * list of accounts on the device changes.
1686 *
1687 * <p>As long as this listener is present, the AccountManager instance
1688 * will not be garbage-collected, and neither will the {@link Context}
1689 * used to retrieve it, which may be a large Activity instance. To avoid
1690 * memory leaks, you must remove this listener before then. Normally
1691 * listeners are added in an Activity or Service's {@link Activity#onCreate}
1692 * and removed in {@link Activity#onDestroy}.
1693 *
1694 * <p>It is safe to call this method from the main thread.
1695 *
1696 * <p>No permission is required to call this method.
1697 *
1698 * @param listener The listener to send notifications to
1699 * @param handler {@link Handler} identifying the thread to use
1700 * for notifications, null for the main thread
1701 * @param updateImmediately If true, the listener will be invoked
1702 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07001703 * @throws IllegalArgumentException if listener is null
1704 * @throws IllegalStateException if listener was already added
1705 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001706 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001707 Handler handler, boolean updateImmediately) {
1708 if (listener == null) {
1709 throw new IllegalArgumentException("the listener is null");
1710 }
1711 synchronized (mAccountsUpdatedListeners) {
1712 if (mAccountsUpdatedListeners.containsKey(listener)) {
1713 throw new IllegalStateException("this listener is already added");
1714 }
1715 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
1716
1717 mAccountsUpdatedListeners.put(listener, handler);
1718
1719 if (wasEmpty) {
1720 // Register a broadcast receiver to monitor account changes
1721 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001722 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07001723 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001724 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001725 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
1726 }
1727 }
1728
1729 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001730 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07001731 }
1732 }
1733
1734 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001735 * Removes an {@link OnAccountsUpdateListener} previously registered with
1736 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
1737 * receive notifications of account changes.
1738 *
1739 * <p>It is safe to call this method from the main thread.
1740 *
1741 * <p>No permission is required to call this method.
1742 *
1743 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07001744 * @throws IllegalArgumentException if listener is null
1745 * @throws IllegalStateException if listener was not already added
1746 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001747 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07001748 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07001749 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01001750 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07001751 Log.e(TAG, "Listener was not previously added");
1752 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001753 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01001754 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001755 if (mAccountsUpdatedListeners.isEmpty()) {
1756 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
1757 }
1758 }
1759 }
Fred Quintana60307342009-03-24 22:48:12 -07001760}