blob: 1bb1d0f3054e9313f2458777db79f6f9ce700725 [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 Quintana60307342009-03-24 22:48:12 -070032
Fred Quintanaa698f422009-04-08 19:14:54 -070033import java.io.IOException;
34import java.util.concurrent.Callable;
35import java.util.concurrent.CancellationException;
36import java.util.concurrent.ExecutionException;
37import java.util.concurrent.FutureTask;
38import java.util.concurrent.TimeoutException;
39import java.util.concurrent.TimeUnit;
Fred Quintanad9d2f112009-04-23 13:36:27 -070040import java.util.HashMap;
41import java.util.Map;
42
43import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070044
45/**
Dan Egnor661f0132010-02-19 11:23:00 -080046 * This class provides access to a centralized registry of the user's
47 * online accounts. With this service, users only need to enter their
48 * credentials (username and password) once for any account, granting
49 * applications access to online resources with "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070050 *
Dan Egnor661f0132010-02-19 11:23:00 -080051 * <p>Different online services have different ways of handling accounts and
52 * authentication, so the account manager uses pluggable <em>authenticator</em>
53 * modules for different <em>account types</em>. The authenticators (which
54 * may be written by third parties) handle the actual details of validating
55 * account credentials and storing account information. For example, Google,
56 * Facebook, and Microsoft Exchange each have their own authenticator.
57 *
58 * <p>Many servers support some notion of an <em>authentication token</em>,
59 * which can be used to authenticate a request to the server without sending
60 * the user's actual password. (Auth tokens are normally created with a
61 * separate request which does include the user's credentials.) AccountManager
62 * can generate these auth tokens for applications, so the application doesn't
63 * need to handle passwords directly. Auth tokens are normally reusable, and
64 * cached by AccountManager, but must be refreshed periodically. It's the
65 * responsibility of applications to <em>invalidate</em> auth tokens when they
66 * stop working so the AccountManager knows it needs to regenerate them.
67 *
68 * <p>Applications accessing a server normally go through these steps:
69 *
70 * <ul>
71 * <li>Get an instance of AccountManager using {@link #get(Context)}.
72 *
73 * <li>List the available accounts using {@link #getAccountsByType} or
74 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
75 * be interested in accounts with one particular <em>type</em>, which
76 * identifies the authenticator. Account <em>features</em> are used to
77 * identify particular account subtypes and capabilities. Both the account
78 * type and features are authenticator-specific strings, and must be known by
79 * the application in coordination with its preferred authenticators.
80 *
81 * <li>Select one or more of the available accounts, possibly by asking the
82 * user for their preference. If no suitable accounts are available,
83 * {@link #addAccount} may be called to prompt the user to create an
84 * account of the appropriate type.
85 *
86 * <li>Request an auth token for the selected account(s) using one of the
87 * {@link #getAuthToken} methods or related helpers. Refer to the description
88 * of each method for exact usage and error handling details.
89 *
90 * <li>Make the request using the auth token. The form of the auth token,
91 * the format of the request, and the protocol used are all specific to the
92 * service you are accessing. The application makes the request itself, using
93 * whatever network and protocol libraries are useful.
94 *
95 * <li><b>Important:</b> If the request fails with an authentication error,
96 * it could be that a cached auth token is stale and no longer honored by
97 * the server. The application must call {@link #invalidateAuthToken} to remove
98 * the token from the cache, otherwise requests will continue failing! After
99 * invalidating the auth token, immediately go back to the "Request an auth
100 * token" step above. If the process fails the second time, then it can be
101 * treated as a "genuine" authentication failure and the user notified or other
102 * appropriate actions taken.
103 * </ul>
104 *
105 * <p>Some AccountManager methods may require interaction with the user to
106 * prompt for credentials, present options, or ask the user to add an account.
107 * The caller may choose whether to allow AccountManager to directly launch the
108 * necessary user interface and wait for the user, or to return an Intent which
109 * the caller may use to launch the interface, or (in some cases) to install a
110 * notification which the user can select at any time to launch the interface.
111 * To have AccountManager launch the interface directly, the caller must supply
112 * the current foreground {@link Activity} context.
113 *
114 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
115 * {@link Handler} as parameters. These methods return immediately but
116 * run asynchronously. If a callback is provided then
117 * {@link AccountManagerCallback#run} will be invoked on the Handler's
118 * thread when the request completes, successfully or not.
119 * An {@link AccountManagerFuture} is returned by these requests and also
120 * supplied to the callback (if any). The result is retrieved by calling
121 * {@link AccountManagerFuture#getResult()} which waits for the operation
122 * to complete (if necessary) and either returns the result or throws an
123 * exception if an error occurred during the operation.
124 * To make the request synchronously, call
125 * {@link AccountManagerFuture#getResult()} immediately on receiving the
126 * future from the method. No callback need be supplied.
127 *
128 * <p>Requests which may block, including
129 * {@link AccountManagerFuture#getResult()}, must never be called on
130 * the application's main event thread. These operations throw
131 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700132 */
133public class AccountManager {
134 private static final String TAG = "AccountManager";
135
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700136 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
137 public static final int ERROR_CODE_NETWORK_ERROR = 3;
138 public static final int ERROR_CODE_CANCELED = 4;
139 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
140 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
141 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
142 public static final int ERROR_CODE_BAD_REQUEST = 8;
Fred Quintana756b7352009-10-21 13:43:10 -0700143
Dan Egnor661f0132010-02-19 11:23:00 -0800144 /**
145 * The Bundle key used for the {@link String} account name in results
146 * from methods which return information about a particular account.
147 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700148 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800149
150 /**
151 * The Bundle key used for the {@link String} account type in results
152 * from methods which return information about a particular account.
153 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700154 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800155
156 /**
157 * The Bundle key used for the auth token value in results
158 * from {@link #getAuthToken} and friends.
159 */
160 public static final String KEY_AUTHTOKEN = "authtoken";
161
162 /**
163 * The Bundle key used for an {@link Intent} in results from methods that
164 * may require the caller to interact with the user. The Intent can
165 * be used to start the corresponding user interface activity.
166 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700167 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800168
169 /**
170 * The Bundle key used to supply the password directly in options to
171 * {@link #confirmCredentials}, rather than prompting the user with
172 * the standard password prompt.
173 */
174 public static final String KEY_PASSWORD = "password";
175
176 public static final String KEY_ACCOUNTS = "accounts";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700177 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
178 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800179 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700180 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
181 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800182 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
183 public static final String KEY_ERROR_CODE = "errorCode";
184 public static final String KEY_ERROR_MESSAGE = "errorMessage";
185 public static final String KEY_USERDATA = "userdata";
186
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700187 public static final String ACTION_AUTHENTICATOR_INTENT =
188 "android.accounts.AccountAuthenticator";
189 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800190 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700191 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
192
Fred Quintana60307342009-03-24 22:48:12 -0700193 private final Context mContext;
194 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700195 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800196
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700197 /**
198 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800199 * when accounts are added, accounts are removed, or an
200 * account's credentials (saved password, etc) are changed.
201 *
202 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700203 */
204 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
205 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700206
Fred Quintana33269202009-04-20 16:05:10 -0700207 /**
208 * @hide
209 */
Fred Quintana60307342009-03-24 22:48:12 -0700210 public AccountManager(Context context, IAccountManager service) {
211 mContext = context;
212 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700213 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700214 }
215
Fred Quintana0eabf022009-04-27 15:08:17 -0700216 /**
217 * @hide used for testing only
218 */
219 public AccountManager(Context context, IAccountManager service, Handler handler) {
220 mContext = context;
221 mService = service;
222 mMainHandler = handler;
223 }
224
Fred Quintana756b7352009-10-21 13:43:10 -0700225 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800226 * Gets an AccountManager instance associated with a Context.
227 * The {@link Context} will be used as long as the AccountManager is
228 * active, so make sure to use a {@link Context} whose lifetime is
229 * commensurate with any listeners registered to
230 * {@link #addOnAccountsUpdatedListener} or similar methods.
231 *
232 * <p>It is safe to call this method from the main thread.
233 *
234 * <p>No permission is required to call this method.
235 *
Fred Quintana756b7352009-10-21 13:43:10 -0700236 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800237 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700238 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700239 public static AccountManager get(Context context) {
240 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
241 }
242
Fred Quintana756b7352009-10-21 13:43:10 -0700243 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800244 * Gets the saved password associated with the account.
245 * This is intended for authenticators and related code; applications
246 * should get an auth token instead.
247 *
248 * <p>It is safe to call this method from the main thread.
249 *
250 * <p>This method requires the caller to hold the permission
251 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
252 * and to have the same UID as the account's authenticator.
253 *
254 * @param account The account to query for a password
255 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700256 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700257 public String getPassword(final Account account) {
Fred Quintana60307342009-03-24 22:48:12 -0700258 try {
259 return mService.getPassword(account);
260 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700261 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700262 throw new RuntimeException(e);
263 }
264 }
265
Fred Quintana756b7352009-10-21 13:43:10 -0700266 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800267 * Gets the user data named by "key" associated with the account.
268 * This is intended for authenticators and related code to store
269 * arbitrary metadata along with accounts. The meaning of the keys
270 * and values is up to the authenticator for the account.
271 *
272 * <p>It is safe to call this method from the main thread.
273 *
274 * <p>This method requires the caller to hold the permission
275 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
276 * and to have the same UID as the account's authenticator.
277 *
278 * @param account The account to query for user data
279 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700280 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700281 public String getUserData(final Account account, final String key) {
Fred Quintana60307342009-03-24 22:48:12 -0700282 try {
283 return mService.getUserData(account, key);
284 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700285 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700286 throw new RuntimeException(e);
287 }
288 }
289
Fred Quintana756b7352009-10-21 13:43:10 -0700290 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800291 * Lists the currently registered authenticators.
292 *
293 * <p>It is safe to call this method from the main thread.
294 *
295 * <p>No permission is required to call this method.
296 *
297 * @return An array of {@link AuthenticatorDescription} for every
298 * authenticator known to the AccountManager service. Empty (never
299 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700300 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700301 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700302 try {
303 return mService.getAuthenticatorTypes();
304 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700305 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700306 throw new RuntimeException(e);
307 }
308 }
309
Fred Quintana756b7352009-10-21 13:43:10 -0700310 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800311 * Lists all accounts of any type registered on the device.
312 * Equivalent to getAccountsByType(null).
313 *
314 * <p>It is safe to call this method from the main thread.
315 *
316 * <p>This method requires the caller to hold the permission
317 * {@link android.Manifest.permission#GET_ACCOUNTS}.
318 *
319 * @return An array of {@link Account}, one for each account. Empty
320 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700321 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700322 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700323 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700324 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700325 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700326 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700327 throw new RuntimeException(e);
328 }
329 }
330
Fred Quintana756b7352009-10-21 13:43:10 -0700331 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800332 * Lists all accounts of a particular type. The account type is a
333 * string token corresponding to the authenticator and useful domain
334 * of the account. For example, there are types corresponding to Google
335 * and Facebook. The exact string token to use will be published somewhere
336 * associated with the authenticator in question.
337 *
338 * <p>It is safe to call this method from the main thread.
339 *
340 * <p>This method requires the caller to hold the permission
341 * {@link android.Manifest.permission#GET_ACCOUNTS}.
342 *
343 * @param type The type of accounts to return, null to retrieve all accounts
344 * @return An array of {@link Account}, one per matching account. Empty
345 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700346 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700347 public Account[] getAccountsByType(String type) {
Fred Quintana60307342009-03-24 22:48:12 -0700348 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700349 return mService.getAccounts(type);
Fred Quintana60307342009-03-24 22:48:12 -0700350 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700351 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700352 throw new RuntimeException(e);
353 }
354 }
355
Fred Quintana756b7352009-10-21 13:43:10 -0700356 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800357 * Finds out whether a particular account has all the specified features.
358 * Account features are authenticator-specific string tokens identifying
359 * boolean account properties. For example, features are used to tell
360 * whether Google accounts have a particular service (such as Google
361 * Calendar or Google Talk) enabled. The feature names and their meanings
362 * are published somewhere associated with the authenticator in question.
363 *
364 * <p>This method may be called from any thread, but the returned
365 * {@link AccountManagerFuture} must not be used on the main thread.
366 *
367 * <p>This method requires the caller to hold the permission
368 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800369 *
370 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800371 * @param features An array of the account features to check
372 * @param callback Callback to invoke when the request completes,
373 * null for no callback
374 * @param handler {@link Handler} identifying the callback thread,
375 * null for the main thread
376 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
377 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800378 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800379 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800380 final String[] features,
381 AccountManagerCallback<Boolean> callback, Handler handler) {
382 return new Future2Task<Boolean>(handler, callback) {
383 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800384 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800385 }
386 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
387 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
388 throw new AuthenticatorException("no result in response");
389 }
390 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
391 }
392 }.start();
393 }
394
395 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800396 * Lists all accounts of a type which have certain features. The account
397 * type identifies the authenticator (see {@link #getAccountsByType}).
398 * Account features are authenticator-specific string tokens identifying
399 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700400 *
Dan Egnor661f0132010-02-19 11:23:00 -0800401 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
402 * which may contact the server or do other work to check account features,
403 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700404 *
Dan Egnor661f0132010-02-19 11:23:00 -0800405 * <p>This method may be called from any thread, but the returned
406 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700407 *
Dan Egnor661f0132010-02-19 11:23:00 -0800408 * <p>This method requires the caller to hold the permission
409 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700410 *
Dan Egnor661f0132010-02-19 11:23:00 -0800411 * @param type The type of accounts to return, must not be null
412 * @param features An array of the account features to require,
413 * may be null or empty
414 * @param callback Callback to invoke when the request completes,
415 * null for no callback
416 * @param handler {@link Handler} identifying the callback thread,
417 * null for the main thread
418 * @return An {@link AccountManagerFuture} which resolves to an array of
419 * {@link Account}, one per account of the specified type which
420 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800421 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700422 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
423 final String type, final String[] features,
424 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700425 return new Future2Task<Account[]>(handler, callback) {
426 public void doWork() throws RemoteException {
Costin Manolache88a211b2009-10-29 11:30:11 -0700427 if (type == null) {
428 Log.e(TAG, "Type is null");
429 set(new Account[0]);
430 return;
431 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700432 mService.getAccountsByFeatures(mResponse, type, features);
433 }
434 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700435 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700436 throw new AuthenticatorException("no result in response");
437 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700438 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700439 Account[] descs = new Account[parcelables.length];
440 for (int i = 0; i < parcelables.length; i++) {
441 descs[i] = (Account) parcelables[i];
442 }
443 return descs;
444 }
445 }.start();
446 }
447
Fred Quintana756b7352009-10-21 13:43:10 -0700448 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800449 * Adds an account directly to the AccountManager. Normally used by sign-up
450 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700451 *
Dan Egnor661f0132010-02-19 11:23:00 -0800452 * <p>It is safe to call this method from the main thread.
453 *
454 * <p>This method requires the caller to hold the permission
455 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
456 * and to have the same UID as the added account's authenticator.
457 *
458 * @param account The {@link Account} to add
459 * @param password The password to associate with the account, null for none
460 * @param userdata String values to use for the account's userdata, null for none
461 * @return Whether the account was successfully added. False if the account
462 * already exists, the account is null, or another error occurs.
463 */
464 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
465 try {
466 return mService.addAccount(account, password, userdata);
467 } catch (RemoteException e) {
468 // won't ever happen
469 throw new RuntimeException(e);
470 }
471 }
472
473 /**
474 * Removes an account from the AccountManager. Does nothing if the account
475 * does not exist. Does not delete the account from the server.
476 * The authenticator may have its own policies preventing account
477 * deletion, in which case the account will not be deleted.
478 *
479 * <p>This method may be called from any thread, but the returned
480 * {@link AccountManagerFuture} must not be used on the main thread.
481 *
482 * <p>This method requires the caller to hold the permission
483 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
484 *
485 * @param account The {@link Account} to remove
486 * @param callback Callback to invoke when the request completes,
487 * null for no callback
488 * @param handler {@link Handler} identifying the callback thread,
489 * null for the main thread
490 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
491 * true if the account has been successfully removed,
492 * false if the authenticator forbids deleting this account.
493 */
494 public AccountManagerFuture<Boolean> removeAccount(final Account account,
495 AccountManagerCallback<Boolean> callback, Handler handler) {
496 return new Future2Task<Boolean>(handler, callback) {
497 public void doWork() throws RemoteException {
498 mService.removeAccount(mResponse, account);
499 }
500 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
501 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
502 throw new AuthenticatorException("no result in response");
503 }
504 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
505 }
506 }.start();
507 }
508
509 /**
510 * Removes an auth token from the AccountManager's cache. Does nothing if
511 * the auth token is not currently in the cache. Applications must call this
512 * method when the auth token is found to have expired or otherwise become
513 * invalid for authenticating requests. The AccountManager does not validate
514 * or expire cached auth tokens otherwise.
515 *
516 * <p>It is safe to call this method from the main thread.
517 *
518 * <p>This method requires the caller to hold the permission
Fred Quintanab38eb142010-02-24 13:40:54 -0800519 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
520 * {@link android.Manifest.permission#USE_CREDENTIALS}
Dan Egnor661f0132010-02-19 11:23:00 -0800521 *
522 * @param accountType The account type of the auth token to invalidate
523 * @param authToken The auth token to invalidate
524 */
525 public void invalidateAuthToken(final String accountType, final String authToken) {
526 try {
527 mService.invalidateAuthToken(accountType, authToken);
528 } catch (RemoteException e) {
529 // won't ever happen
530 throw new RuntimeException(e);
531 }
532 }
533
534 /**
535 * Gets an auth token from the AccountManager's cache. If no auth
536 * token is cached for this account, null will be returned -- a new
537 * auth token will not be generated, and the server will not be contacted.
538 * Intended for use by the authenticator, not directly by applications.
539 *
540 * <p>It is safe to call this method from the main thread.
541 *
542 * <p>This method requires the caller to hold the permission
543 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
544 * and to have the same UID as the account's authenticator.
545 *
546 * @param account The account to fetch an auth token for
547 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
548 * @return The cached auth token for this account and type, or null if
549 * no auth token is cached or the account does not exist.
550 */
551 public String peekAuthToken(final Account account, final String authTokenType) {
552 if (account == null) {
553 Log.e(TAG, "peekAuthToken: the account must not be null");
554 return null;
555 }
556 if (authTokenType == null) {
557 return null;
558 }
559 try {
560 return mService.peekAuthToken(account, authTokenType);
561 } catch (RemoteException e) {
562 // won't ever happen
563 throw new RuntimeException(e);
564 }
565 }
566
567 /**
568 * Sets or forgets a saved password. This modifies the local copy of the
569 * password used to automatically authenticate the user; it does
570 * not change the user's account password on the server. Intended for use
571 * by the authenticator, not directly by applications.
572 *
573 * <p>It is safe to call this method from the main thread.
574 *
575 * <p>This method requires the caller to hold the permission
576 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
577 * and have the same UID as the account's authenticator.
578 *
579 * @param account The account to set a password for
580 * @param password The password to set, null to clear the password
581 */
582 public void setPassword(final Account account, final String password) {
583 if (account == null) {
584 Log.e(TAG, "the account must not be null");
585 return;
586 }
587 try {
588 mService.setPassword(account, password);
589 } catch (RemoteException e) {
590 // won't ever happen
591 throw new RuntimeException(e);
592 }
593 }
594
595 /**
596 * Forgets a saved password. This erases the local copy of the password;
597 * it does not change the user's account password on the server.
598 * Has the same effect as setPassword(account, null) but requires fewer
599 * permissions, and may be used by applications or management interfaces
600 * to "sign out" from an account.
601 *
602 * <p>It is safe to call this method from the main thread.
603 *
604 * <p>This method requires the caller to hold the permission
605 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
606 *
607 * @param account The account whose password to clear
608 */
609 public void clearPassword(final Account account) {
610 if (account == null) {
611 Log.e(TAG, "the account must not be null");
612 return;
613 }
614 try {
615 mService.clearPassword(account);
616 } catch (RemoteException e) {
617 // won't ever happen
618 throw new RuntimeException(e);
619 }
620 }
621
622 /**
623 * Sets one userdata key for an account. Intended by use for the
624 * authenticator to stash state for itself, not directly by applications.
625 * The meaning of the keys and values is up to the authenticator.
626 *
627 * <p>It is safe to call this method from the main thread.
628 *
629 * <p>This method requires the caller to hold the permission
630 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
631 * and to have the same UID as the account's authenticator.
632 *
633 * @param account The account to set the userdata for
634 * @param key The userdata key to set. Must not be null
635 * @param value The value to set, null to clear this userdata key
636 */
637 public void setUserData(final Account account, final String key, final String value) {
638 if (account == null) {
639 Log.e(TAG, "the account must not be null");
640 return;
641 }
642 if (key == null) {
643 Log.e(TAG, "the key must not be null");
644 return;
645 }
646 try {
647 mService.setUserData(account, key, value);
648 } catch (RemoteException e) {
649 // won't ever happen
650 throw new RuntimeException(e);
651 }
652 }
653
654 /**
655 * Adds an auth token to the AccountManager cache for an account.
656 * If the account does not exist then this call has no effect.
657 * Replaces any previous auth token for this account and auth token type.
658 * Intended for use by the authenticator, not directly by applications.
659 *
660 * <p>It is safe to call this method from the main thread.
661 *
662 * <p>This method requires the caller to hold the permission
663 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
664 * and to have the same UID as the account's authenticator.
665 *
666 * @param account The account to set an auth token for
667 * @param authTokenType The type of the auth token, see {#getAuthToken}
668 * @param authToken The auth token to add to the cache
669 */
670 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
671 try {
672 mService.setAuthToken(account, authTokenType, authToken);
673 } catch (RemoteException e) {
674 // won't ever happen
675 throw new RuntimeException(e);
676 }
677 }
678
679 /**
680 * This convenience helper synchronously gets an auth token with
681 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
682 *
683 * <p>This method may block while a network request completes, and must
684 * never be made from the main thread.
685 *
686 * <p>This method requires the caller to hold the permission
687 * {@link android.Manifest.permission#USE_CREDENTIALS}.
688 *
689 * @param account The account to fetch an auth token for
690 * @param authTokenType The auth token type, see {#link getAuthToken}
691 * @param notifyAuthFailure If true, display a notification and return null
692 * if authentication fails; if false, prompt and wait for the user to
693 * re-enter correct credentials before returning
694 * @return An auth token of the specified type for this account, or null
695 * if authentication fails or none can be fetched.
696 * @throws AuthenticatorException if the authenticator failed to respond
697 * @throws OperationCanceledException if the request was canceled for any
698 * reason, including the user canceling a credential request
699 * @throws java.io.IOException if the authenticator experienced an I/O problem
700 * creating a new auth token, usually because of network trouble
701 */
702 public String blockingGetAuthToken(Account account, String authTokenType,
703 boolean notifyAuthFailure)
704 throws OperationCanceledException, IOException, AuthenticatorException {
705 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
706 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -0800707 if (bundle == null) {
708 // This should never happen, but it does, occasionally. If it does return null to
709 // signify that we were not able to get the authtoken.
710 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
711 // returned
712 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
713 + account + ", authTokenType " + authTokenType);
714 return null;
715 }
Dan Egnor661f0132010-02-19 11:23:00 -0800716 return bundle.getString(KEY_AUTHTOKEN);
717 }
718
719 /**
720 * Gets an auth token of the specified type for a particular account,
721 * prompting the user for credentials if necessary. This method is
722 * intended for applications running in the foreground where it makes
723 * sense to ask the user directly for a password.
724 *
725 * <p>If a previously generated auth token is cached for this account and
726 * type, then it will be returned. Otherwise, if we have a saved password
727 * the server accepts, it will be used to generate a new auth token.
728 * Otherwise, the user will be asked for a password, which will be sent to
729 * the server to generate a new auth token.
730 *
731 * <p>The value of the auth token type depends on the authenticator.
732 * Some services use different tokens to access different functionality --
733 * for example, Google uses different auth tokens to access Gmail and
734 * Google Calendar for the same account.
735 *
736 * <p>This method may be called from any thread, but the returned
737 * {@link AccountManagerFuture} must not be used on the main thread.
738 *
739 * <p>This method requires the caller to hold the permission
740 * {@link android.Manifest.permission#USE_CREDENTIALS}.
741 *
742 * @param account The account to fetch an auth token for
743 * @param authTokenType The auth token type, an authenticator-dependent
744 * string token, must not be null
745 * @param options Authenticator-specific options for the request,
746 * may be null or empty
747 * @param activity The {@link Activity} context to use for launching a new
748 * authenticator-defined sub-Activity to prompt the user for a password
749 * if necessary; used only to call startActivity(); must not be null.
750 * @param callback Callback to invoke when the request completes,
751 * null for no callback
752 * @param handler {@link Handler} identifying the callback thread,
753 * null for the main thread
754 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
755 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -0700756 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800757 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
758 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
759 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -0700760 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800761 *
762 * (Other authenticator-specific values may be returned.) If an auth token
763 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
764 * <ul>
765 * <li> {@link AuthenticatorException} if the authenticator failed to respond
766 * <li> {@link OperationCanceledException} if the operation is canceled for
767 * any reason, incluidng the user canceling a credential request
768 * <li> {@link IOException} if the authenticator experienced an I/O problem
769 * creating a new auth token, usually because of network trouble
770 * </ul>
771 */
772 public AccountManagerFuture<Bundle> getAuthToken(
773 final Account account, final String authTokenType, final Bundle options,
774 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
775 if (activity == null) throw new IllegalArgumentException("activity is null");
776 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
777 return new AmsTask(activity, handler, callback) {
778 public void doWork() throws RemoteException {
779 mService.getAuthToken(mResponse, account, authTokenType,
780 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
781 options);
782 }
783 }.start();
784 }
785
786 /**
787 * Gets an auth token of the specified type for a particular account,
788 * optionally raising a notification if the user must enter credentials.
789 * This method is intended for background tasks and services where the
790 * user should not be immediately interrupted with a password prompt.
791 *
792 * <p>If a previously generated auth token is cached for this account and
793 * type, then it will be returned. Otherwise, if we have saved credentials
794 * the server accepts, it will be used to generate a new auth token.
795 * Otherwise, an Intent will be returned which, when started, will prompt
796 * the user for a password. If the notifyAuthFailure parameter is set,
797 * the same Intent will be associated with a status bar notification,
798 * alerting the user that they need to enter a password at some point.
799 *
800 * <p>If the intent is left in a notification, you will need to wait until
801 * the user gets around to entering a password before trying again,
802 * which could be hours or days or never. When it does happen, the
803 * account manager will broadcast the {@link #LOGIN_ACCOUNTS_CHANGED_ACTION}
804 * {@link Intent}, which applications can use to trigger another attempt
805 * to fetch an auth token.
806 *
807 * <p>If notifications are not enabled, it is the application's
808 * responsibility to launch the returned intent at some point to let
809 * the user enter credentials. In either case, the result from this
810 * call will not wait for user action.
811 *
812 * <p>The value of the auth token type depends on the authenticator.
813 * Some services use different tokens to access different functionality --
814 * for example, Google uses different auth tokens to access Gmail and
815 * Google Calendar for the same account.
816 *
817 * <p>This method may be called from any thread, but the returned
818 * {@link AccountManagerFuture} must not be used on the main thread.
819 *
820 * <p>This method requires the caller to hold the permission
821 * {@link android.Manifest.permission#USE_CREDENTIALS}.
822 *
823 * @param account The account to fetch an auth token for
824 * @param authTokenType The auth token type, an authenticator-dependent
825 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -0800826 * @param notifyAuthFailure True to add a notification to prompt the
827 * user for a password if necessary, false to leave that to the caller
828 * @param callback Callback to invoke when the request completes,
829 * null for no callback
830 * @param handler {@link Handler} identifying the callback thread,
831 * null for the main thread
832 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
833 * at least the following fields on success:
834 * <ul>
835 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
836 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
837 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
838 * </ul>
839 *
840 * (Other authenticator-specific values may be returned.) If the user
841 * must enter credentials, the returned Bundle contains only
842 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
843 *
844 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
845 * <ul>
846 * <li> {@link AuthenticatorException} if the authenticator failed to respond
847 * <li> {@link OperationCanceledException} if the operation is canceled for
848 * any reason, incluidng the user canceling a credential request
849 * <li> {@link IOException} if the authenticator experienced an I/O problem
850 * creating a new auth token, usually because of network trouble
851 * </ul>
852 */
853 public AccountManagerFuture<Bundle> getAuthToken(
854 final Account account, final String authTokenType, final boolean notifyAuthFailure,
855 AccountManagerCallback<Bundle> callback, Handler handler) {
856 if (account == null) throw new IllegalArgumentException("account is null");
857 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
858 return new AmsTask(null, handler, callback) {
859 public void doWork() throws RemoteException {
860 mService.getAuthToken(mResponse, account, authTokenType,
861 notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
862 }
863 }.start();
864 }
865
866 /**
867 * Asks the user to add an account of a specified type. The authenticator
868 * for this account type processes this request with the appropriate user
869 * interface. If the user does elect to create a new account, the account
870 * name is returned.
871 *
872 * <p>This method may be called from any thread, but the returned
873 * {@link AccountManagerFuture} must not be used on the main thread.
874 *
875 * <p>This method requires the caller to hold the permission
876 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
877 *
878 * @param accountType The type of account to add; must not be null
879 * @param authTokenType The type of auth token (see {@link #getAuthToken})
880 * this account will need to be able to generate, null for none
881 * @param requiredFeatures The features (see {@link #hasFeatures}) this
882 * account must have, null for none
883 * @param addAccountOptions Authenticator-specific options for the request,
884 * may be null or empty
885 * @param activity The {@link Activity} context to use for launching a new
886 * authenticator-defined sub-Activity to prompt the user to create an
887 * account; used only to call startActivity(); if null, the prompt
888 * will not be launched directly, but the necessary {@link Intent}
889 * will be returned to the caller instead
890 * @param callback Callback to invoke when the request completes,
891 * null for no callback
892 * @param handler {@link Handler} identifying the callback thread,
893 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -0800894 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -0800895 * these fields if activity was specified and an account was created:
896 * <ul>
897 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
898 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
899 * </ul>
900 *
901 * If no activity was specified, the returned Bundle contains only
902 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
903 * actual account creation process.
904 *
905 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
906 * <ul>
907 * <li> {@link AuthenticatorException} if no authenticator was registered for
908 * this account type or the authenticator failed to respond
909 * <li> {@link OperationCanceledException} if the operation was canceled for
910 * any reason, including the user canceling the creation process
911 * <li> {@link IOException} if the authenticator experienced an I/O problem
912 * creating a new account, usually because of network trouble
913 * </ul>
914 */
915 public AccountManagerFuture<Bundle> addAccount(final String accountType,
916 final String authTokenType, final String[] requiredFeatures,
917 final Bundle addAccountOptions,
918 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
919 return new AmsTask(activity, handler, callback) {
920 public void doWork() throws RemoteException {
921 if (accountType == null) {
922 Log.e(TAG, "the account must not be null");
923 // to unblock caller waiting on Future.get()
924 set(new Bundle());
925 return;
926 }
927 mService.addAcount(mResponse, accountType, authTokenType,
928 requiredFeatures, activity != null, addAccountOptions);
929 }
930 }.start();
931 }
932
933 /**
934 * Confirms that the user knows the password for an account to make extra
935 * sure they are the owner of the account. The user-entered password can
936 * be supplied directly, otherwise the authenticator for this account type
937 * prompts the user with the appropriate interface. This method is
938 * intended for applications which want extra assurance; for example, the
939 * phone lock screen uses this to let the user unlock the phone with an
940 * account password if they forget the lock pattern.
941 *
942 * <p>If the user-entered password matches a saved password for this
943 * account, the request is considered valid; otherwise the authenticator
944 * verifies the password (usually by contacting the server).
945 *
946 * <p>This method may be called from any thread, but the returned
947 * {@link AccountManagerFuture} must not be used on the main thread.
948 *
949 * <p>This method requires the caller to hold the permission
950 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
951 *
952 * @param account The account to confirm password knowledge for
953 * @param options Authenticator-specific options for the request;
954 * if the {@link #KEY_PASSWORD} string field is present, the
955 * authenticator may use it directly rather than prompting the user;
956 * may be null or empty
957 * @param activity The {@link Activity} context to use for launching a new
958 * authenticator-defined sub-Activity to prompt the user to enter a
959 * password; used only to call startActivity(); if null, the prompt
960 * will not be launched directly, but the necessary {@link Intent}
961 * will be returned to the caller instead
962 * @param callback Callback to invoke when the request completes,
963 * null for no callback
964 * @param handler {@link Handler} identifying the callback thread,
965 * null for the main thread
966 * @return An {@link AccountManagerFuture} which resolves to a Bundle
967 * with these fields if activity or password was supplied and
968 * the account was successfully verified:
969 * <ul>
970 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
971 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
972 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
973 * </ul>
974 *
975 * If no activity or password was specified, the returned Bundle contains
976 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
977 * password prompt.
978 *
979 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
980 * <ul>
981 * <li> {@link AuthenticatorException} if the authenticator failed to respond
982 * <li> {@link OperationCanceledException} if the operation was canceled for
983 * any reason, including the user canceling the password prompt
984 * <li> {@link IOException} if the authenticator experienced an I/O problem
985 * verifying the password, usually because of network trouble
986 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -0700987 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700988 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
989 final Bundle options,
990 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700991 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -0700992 final Handler handler) {
993 return new AmsTask(activity, handler, callback) {
994 public void doWork() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700995 mService.confirmCredentials(mResponse, account, options, activity != null);
Fred Quintanaa698f422009-04-08 19:14:54 -0700996 }
Fred Quintana33269202009-04-20 16:05:10 -0700997 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -0700998 }
999
Fred Quintana756b7352009-10-21 13:43:10 -07001000 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001001 * Asks the user to enter a new password for an account, updating the
1002 * saved credentials for the account. Normally this happens automatically
1003 * when the server rejects credentials during an auth token fetch, but this
1004 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001005 *
Dan Egnor661f0132010-02-19 11:23:00 -08001006 * <p>This method may be called from any thread, but the returned
1007 * {@link AccountManagerFuture} must not be used on the main thread.
1008 *
1009 * <p>This method requires the caller to hold the permission
1010 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1011 *
1012 * @param account The account to update credentials for
1013 * @param authTokenType The credentials entered must allow an auth token
1014 * of this type to be created (but no actual auth token is returned);
1015 * may be null
1016 * @param options Authenticator-specific options for the request;
1017 * may be null or empty
1018 * @param activity The {@link Activity} context to use for launching a new
1019 * authenticator-defined sub-Activity to prompt the user to enter a
1020 * password; used only to call startActivity(); if null, the prompt
1021 * will not be launched directly, but the necessary {@link Intent}
1022 * will be returned to the caller instead
1023 * @param callback Callback to invoke when the request completes,
1024 * null for no callback
1025 * @param handler {@link Handler} identifying the callback thread,
1026 * null for the main thread
1027 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1028 * with these fields if an activity was supplied and the account
1029 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001030 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001031 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1032 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001033 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001034 *
1035 * If no activity was specified, the returned Bundle contains only
1036 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1037 * password prompt.
1038 *
1039 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1040 * <ul>
1041 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1042 * <li> {@link OperationCanceledException} if the operation was canceled for
1043 * any reason, including the user canceling the password prompt
1044 * <li> {@link IOException} if the authenticator experienced an I/O problem
1045 * verifying the password, usually because of network trouble
1046 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001047 */
1048 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1049 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001050 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001051 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001052 final Handler handler) {
1053 return new AmsTask(activity, handler, callback) {
1054 public void doWork() throws RemoteException {
1055 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001056 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001057 }
Fred Quintana33269202009-04-20 16:05:10 -07001058 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001059 }
1060
Fred Quintana756b7352009-10-21 13:43:10 -07001061 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001062 * Offers the user an opportunity to change an authenticator's settings.
1063 * These properties are for the authenticator in general, not a particular
1064 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001065 *
Dan Egnor661f0132010-02-19 11:23:00 -08001066 * <p>This method may be called from any thread, but the returned
1067 * {@link AccountManagerFuture} must not be used on the main thread.
1068 *
1069 * <p>This method requires the caller to hold the permission
1070 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1071 *
1072 * @param accountType The account type associated with the authenticator
1073 * to adjust
1074 * @param activity The {@link Activity} context to use for launching a new
1075 * authenticator-defined sub-Activity to adjust authenticator settings;
1076 * used only to call startActivity(); if null, the settings dialog will
1077 * not be launched directly, but the necessary {@link Intent} will be
1078 * returned to the caller instead
1079 * @param callback Callback to invoke when the request completes,
1080 * null for no callback
1081 * @param handler {@link Handler} identifying the callback thread,
1082 * null for the main thread
1083 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1084 * which is empty if properties were edited successfully, or
1085 * if no activity was specified, contains only {@link #KEY_INTENT}
1086 * needed to launch the authenticator's settings dialog.
1087 *
1088 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001089 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001090 * <li> {@link AuthenticatorException} if no authenticator was registered for
1091 * this account type or the authenticator failed to respond
1092 * <li> {@link OperationCanceledException} if the operation was canceled for
1093 * any reason, including the user canceling the settings dialog
1094 * <li> {@link IOException} if the authenticator experienced an I/O problem
1095 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001096 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001097 */
1098 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1099 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001100 final Handler handler) {
1101 return new AmsTask(activity, handler, callback) {
1102 public void doWork() throws RemoteException {
1103 mService.editProperties(mResponse, accountType, activity != null);
1104 }
Fred Quintana33269202009-04-20 16:05:10 -07001105 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001106 }
1107
1108 private void ensureNotOnMainThread() {
1109 final Looper looper = Looper.myLooper();
1110 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001111 final IllegalStateException exception = new IllegalStateException(
1112 "calling this from your main thread can lead to deadlock");
1113 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1114 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001115 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1116 throw exception;
1117 }
Fred Quintana60307342009-03-24 22:48:12 -07001118 }
1119 }
1120
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001121 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1122 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001123 handler = handler == null ? mMainHandler : handler;
1124 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001125 public void run() {
1126 callback.run(future);
1127 }
1128 });
1129 }
Fred Quintana60307342009-03-24 22:48:12 -07001130
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001131 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001132 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001133 final Account[] accountsCopy = new Account[accounts.length];
1134 // send a copy to make sure that one doesn't
1135 // change what another sees
1136 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1137 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001138 handler.post(new Runnable() {
1139 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001140 try {
1141 listener.onAccountsUpdated(accountsCopy);
1142 } catch (SQLException e) {
1143 // Better luck next time. If the problem was disk-full,
1144 // the STORAGE_OK intent will re-trigger the update.
1145 Log.e(TAG, "Can't update accounts", e);
1146 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001147 }
1148 });
1149 }
1150
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001151 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001152 final IAccountManagerResponse mResponse;
1153 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001154 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001155 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001156 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001157 super(new Callable<Bundle>() {
1158 public Bundle call() throws Exception {
1159 throw new IllegalStateException("this should never be called");
1160 }
1161 });
1162
1163 mHandler = handler;
1164 mCallback = callback;
1165 mActivity = activity;
1166 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001167 }
1168
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001169 public final AccountManagerFuture<Bundle> start() {
1170 try {
1171 doWork();
1172 } catch (RemoteException e) {
1173 setException(e);
1174 }
Fred Quintana33269202009-04-20 16:05:10 -07001175 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001176 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001177
Fred Quintana96580e02010-03-04 13:42:42 -08001178 protected void set(Bundle bundle) {
1179 // TODO: somehow a null is being set as the result of the Future. Log this
1180 // case to help debug where this is occurring. When this bug is fixed this
1181 // condition statement should be removed.
1182 if (bundle == null) {
1183 Log.e(TAG, "the bundle must not be null", new Exception());
1184 }
1185 super.set(bundle);
1186 }
1187
Fred Quintanaa698f422009-04-08 19:14:54 -07001188 public abstract void doWork() throws RemoteException;
1189
1190 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1191 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001192 if (!isDone()) {
1193 ensureNotOnMainThread();
1194 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001195 try {
1196 if (timeout == null) {
1197 return get();
1198 } else {
1199 return get(timeout, unit);
1200 }
1201 } catch (CancellationException e) {
1202 throw new OperationCanceledException();
1203 } catch (TimeoutException e) {
1204 // fall through and cancel
1205 } catch (InterruptedException e) {
1206 // fall through and cancel
1207 } catch (ExecutionException e) {
1208 final Throwable cause = e.getCause();
1209 if (cause instanceof IOException) {
1210 throw (IOException) cause;
1211 } else if (cause instanceof UnsupportedOperationException) {
1212 throw new AuthenticatorException(cause);
1213 } else if (cause instanceof AuthenticatorException) {
1214 throw (AuthenticatorException) cause;
1215 } else if (cause instanceof RuntimeException) {
1216 throw (RuntimeException) cause;
1217 } else if (cause instanceof Error) {
1218 throw (Error) cause;
1219 } else {
1220 throw new IllegalStateException(cause);
1221 }
1222 } finally {
1223 cancel(true /* interrupt if running */);
1224 }
1225 throw new OperationCanceledException();
1226 }
1227
1228 public Bundle getResult()
1229 throws OperationCanceledException, IOException, AuthenticatorException {
1230 return internalGetResult(null, null);
1231 }
1232
1233 public Bundle getResult(long timeout, TimeUnit unit)
1234 throws OperationCanceledException, IOException, AuthenticatorException {
1235 return internalGetResult(timeout, unit);
1236 }
1237
1238 protected void done() {
1239 if (mCallback != null) {
1240 postToHandler(mHandler, mCallback, this);
1241 }
1242 }
1243
1244 /** Handles the responses from the AccountManager */
1245 private class Response extends IAccountManagerResponse.Stub {
1246 public void onResult(Bundle bundle) {
1247 Intent intent = bundle.getParcelable("intent");
1248 if (intent != null && mActivity != null) {
1249 // since the user provided an Activity we will silently start intents
1250 // that we see
1251 mActivity.startActivity(intent);
1252 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001253 } else if (bundle.getBoolean("retry")) {
1254 try {
1255 doWork();
1256 } catch (RemoteException e) {
1257 // this will only happen if the system process is dead, which means
1258 // we will be dying ourselves
1259 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001260 } else {
1261 set(bundle);
1262 }
1263 }
1264
1265 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001266 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001267 // the authenticator indicated that this request was canceled, do so now
1268 cancel(true /* mayInterruptIfRunning */);
1269 return;
1270 }
1271 setException(convertErrorToException(code, message));
1272 }
1273 }
1274
Fred Quintana60307342009-03-24 22:48:12 -07001275 }
1276
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001277 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1278 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001279 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001280
1281 public BaseFutureTask(Handler handler) {
1282 super(new Callable<T>() {
1283 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001284 throw new IllegalStateException("this should never be called");
1285 }
1286 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001287 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001288 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001289 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001290
1291 public abstract void doWork() throws RemoteException;
1292
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001293 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001294
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001295 protected void postRunnableToHandler(Runnable runnable) {
1296 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1297 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001298 }
1299
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001300 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001301 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001302 doWork();
1303 } catch (RemoteException e) {
1304 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001305 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001306 }
1307
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001308 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001309 public void onResult(Bundle bundle) {
1310 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001311 T result = bundleToResult(bundle);
1312 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001313 return;
1314 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001315 set(result);
1316 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001317 } catch (ClassCastException e) {
1318 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001319 } catch (AuthenticatorException e) {
1320 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001321 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001322 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001323 }
1324
1325 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001326 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001327 cancel(true /* mayInterruptIfRunning */);
1328 return;
1329 }
1330 setException(convertErrorToException(code, message));
1331 }
1332 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001333 }
1334
1335 private abstract class Future2Task<T>
1336 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1337 final AccountManagerCallback<T> mCallback;
1338 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1339 super(handler);
1340 mCallback = callback;
1341 }
1342
1343 protected void done() {
1344 if (mCallback != null) {
1345 postRunnableToHandler(new Runnable() {
1346 public void run() {
1347 mCallback.run(Future2Task.this);
1348 }
1349 });
1350 }
1351 }
1352
1353 public Future2Task<T> start() {
1354 startTask();
1355 return this;
1356 }
1357
1358 private T internalGetResult(Long timeout, TimeUnit unit)
1359 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001360 if (!isDone()) {
1361 ensureNotOnMainThread();
1362 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001363 try {
1364 if (timeout == null) {
1365 return get();
1366 } else {
1367 return get(timeout, unit);
1368 }
1369 } catch (InterruptedException e) {
1370 // fall through and cancel
1371 } catch (TimeoutException e) {
1372 // fall through and cancel
1373 } catch (CancellationException e) {
1374 // fall through and cancel
1375 } catch (ExecutionException e) {
1376 final Throwable cause = e.getCause();
1377 if (cause instanceof IOException) {
1378 throw (IOException) cause;
1379 } else if (cause instanceof UnsupportedOperationException) {
1380 throw new AuthenticatorException(cause);
1381 } else if (cause instanceof AuthenticatorException) {
1382 throw (AuthenticatorException) cause;
1383 } else if (cause instanceof RuntimeException) {
1384 throw (RuntimeException) cause;
1385 } else if (cause instanceof Error) {
1386 throw (Error) cause;
1387 } else {
1388 throw new IllegalStateException(cause);
1389 }
1390 } finally {
1391 cancel(true /* interrupt if running */);
1392 }
1393 throw new OperationCanceledException();
1394 }
1395
1396 public T getResult()
1397 throws OperationCanceledException, IOException, AuthenticatorException {
1398 return internalGetResult(null, null);
1399 }
1400
1401 public T getResult(long timeout, TimeUnit unit)
1402 throws OperationCanceledException, IOException, AuthenticatorException {
1403 return internalGetResult(timeout, unit);
1404 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001405
Fred Quintana60307342009-03-24 22:48:12 -07001406 }
1407
Fred Quintanaa698f422009-04-08 19:14:54 -07001408 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001409 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001410 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001411 }
Fred Quintana60307342009-03-24 22:48:12 -07001412
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001413 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07001414 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001415 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001416
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001417 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07001418 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07001419 }
1420
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001421 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07001422 return new IllegalArgumentException(message);
1423 }
1424
1425 return new AuthenticatorException(message);
1426 }
1427
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001428 private class GetAuthTokenByTypeAndFeaturesTask
1429 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07001430 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1431 final String[] features, Activity activityForPrompting,
1432 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001433 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001434 super(activityForPrompting, handler, callback);
1435 if (accountType == null) throw new IllegalArgumentException("account type is null");
1436 mAccountType = accountType;
1437 mAuthTokenType = authTokenType;
1438 mFeatures = features;
1439 mAddAccountOptions = addAccountOptions;
1440 mLoginOptions = loginOptions;
1441 mMyCallback = this;
1442 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001443 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07001444 final String mAccountType;
1445 final String mAuthTokenType;
1446 final String[] mFeatures;
1447 final Bundle mAddAccountOptions;
1448 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001449 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintana33269202009-04-20 16:05:10 -07001450
1451 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001452 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1453 new AccountManagerCallback<Account[]>() {
1454 public void run(AccountManagerFuture<Account[]> future) {
1455 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07001456 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001457 accounts = future.getResult();
1458 } catch (OperationCanceledException e) {
1459 setException(e);
1460 return;
1461 } catch (IOException e) {
1462 setException(e);
1463 return;
1464 } catch (AuthenticatorException e) {
1465 setException(e);
1466 return;
Fred Quintana33269202009-04-20 16:05:10 -07001467 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001468
1469 if (accounts.length == 0) {
1470 if (mActivity != null) {
1471 // no accounts, add one now. pretend that the user directly
1472 // made this request
1473 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1474 mAddAccountOptions, mActivity, mMyCallback, mHandler);
1475 } else {
1476 // send result since we can't prompt to add an account
1477 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001478 result.putString(KEY_ACCOUNT_NAME, null);
1479 result.putString(KEY_ACCOUNT_TYPE, null);
1480 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001481 try {
1482 mResponse.onResult(result);
1483 } catch (RemoteException e) {
1484 // this will never happen
1485 }
1486 // we are done
1487 }
1488 } else if (accounts.length == 1) {
1489 // have a single account, return an authtoken for it
1490 if (mActivity == null) {
1491 mFuture = getAuthToken(accounts[0], mAuthTokenType,
1492 false /* notifyAuthFailure */, mMyCallback, mHandler);
1493 } else {
1494 mFuture = getAuthToken(accounts[0],
1495 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07001496 mActivity, mMyCallback, mHandler);
1497 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001498 } else {
1499 if (mActivity != null) {
1500 IAccountManagerResponse chooseResponse =
1501 new IAccountManagerResponse.Stub() {
1502 public void onResult(Bundle value) throws RemoteException {
1503 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001504 value.getString(KEY_ACCOUNT_NAME),
1505 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001506 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1507 mActivity, mMyCallback, mHandler);
1508 }
Fred Quintana33269202009-04-20 16:05:10 -07001509
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001510 public void onError(int errorCode, String errorMessage)
1511 throws RemoteException {
1512 mResponse.onError(errorCode, errorMessage);
1513 }
1514 };
1515 // have many accounts, launch the chooser
1516 Intent intent = new Intent();
1517 intent.setClassName("android",
1518 "android.accounts.ChooseAccountActivity");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001519 intent.putExtra(KEY_ACCOUNTS, accounts);
1520 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001521 new AccountManagerResponse(chooseResponse));
1522 mActivity.startActivity(intent);
1523 // the result will arrive via the IAccountManagerResponse
1524 } else {
1525 // send result since we can't prompt to select an account
1526 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001527 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001528 try {
1529 mResponse.onResult(result);
1530 } catch (RemoteException e) {
1531 // this will never happen
1532 }
1533 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07001534 }
Fred Quintana33269202009-04-20 16:05:10 -07001535 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001536 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07001537 }
1538
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001539 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07001540 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001541 set(future.getResult());
1542 } catch (OperationCanceledException e) {
1543 cancel(true /* mayInterruptIfRUnning */);
1544 } catch (IOException e) {
1545 setException(e);
1546 } catch (AuthenticatorException e) {
1547 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07001548 }
1549 }
1550 }
1551
Fred Quintana756b7352009-10-21 13:43:10 -07001552 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001553 * This convenience helper combines the functionality of
1554 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1555 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07001556 *
Dan Egnor661f0132010-02-19 11:23:00 -08001557 * <p>This method gets a list of the accounts matching the
1558 * specified type and feature set; if there is exactly one, it is
1559 * used; if there are more than one, the user is prompted to pick one;
1560 * if there are none, the user is prompted to add one. Finally,
1561 * an auth token is acquired for the chosen account.
1562 *
1563 * <p>This method may be called from any thread, but the returned
1564 * {@link AccountManagerFuture} must not be used on the main thread.
1565 *
1566 * <p>This method requires the caller to hold the permission
1567 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1568 *
1569 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08001570 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001571 * @param authTokenType The desired auth token type
1572 * (see {@link #getAuthToken}), must not be null
1573 * @param features Required features for the account
1574 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1575 * @param activity The {@link Activity} context to use for launching new
1576 * sub-Activities to prompt to add an account, select an account,
1577 * and/or enter a password, as necessary; used only to call
1578 * startActivity(); should not be null
1579 * @param addAccountOptions Authenticator-specific options to use for
1580 * adding new accounts; may be null or empty
1581 * @param getAuthTokenOptions Authenticator-specific options to use for
1582 * getting auth tokens; may be null or empty
1583 * @param callback Callback to invoke when the request completes,
1584 * null for no callback
1585 * @param handler {@link Handler} identifying the callback thread,
1586 * null for the main thread
1587 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1588 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001589 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001590 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1591 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1592 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001593 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001594 *
1595 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1596 * <ul>
1597 * <li> {@link AuthenticatorException} if no authenticator was registered for
1598 * this account type or the authenticator failed to respond
1599 * <li> {@link OperationCanceledException} if the operation was canceled for
1600 * any reason, including the user canceling any operation
1601 * <li> {@link IOException} if the authenticator experienced an I/O problem
1602 * updating settings, usually because of network trouble
1603 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001604 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001605 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07001606 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08001607 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07001608 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001609 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001610 if (accountType == null) throw new IllegalArgumentException("account type is null");
1611 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001612 final GetAuthTokenByTypeAndFeaturesTask task =
1613 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08001614 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001615 task.start();
1616 return task;
Fred Quintana60307342009-03-24 22:48:12 -07001617 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001618
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001619 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07001620 Maps.newHashMap();
1621
Fred Quintanad9d2f112009-04-23 13:36:27 -07001622 /**
1623 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1624 * so that it can read the updated list of accounts and send them to the listener
1625 * in mAccountsUpdatedListeners.
1626 */
1627 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1628 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001629 final Account[] accounts = getAccounts();
1630 // send the result to the listeners
1631 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001632 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001633 mAccountsUpdatedListeners.entrySet()) {
1634 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001635 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001636 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001637 }
1638 };
1639
1640 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001641 * Adds an {@link OnAccountsUpdateListener} to this instance of the
1642 * {@link AccountManager}. This listener will be notified whenever the
1643 * list of accounts on the device changes.
1644 *
1645 * <p>As long as this listener is present, the AccountManager instance
1646 * will not be garbage-collected, and neither will the {@link Context}
1647 * used to retrieve it, which may be a large Activity instance. To avoid
1648 * memory leaks, you must remove this listener before then. Normally
1649 * listeners are added in an Activity or Service's {@link Activity#onCreate}
1650 * and removed in {@link Activity#onDestroy}.
1651 *
1652 * <p>It is safe to call this method from the main thread.
1653 *
1654 * <p>No permission is required to call this method.
1655 *
1656 * @param listener The listener to send notifications to
1657 * @param handler {@link Handler} identifying the thread to use
1658 * for notifications, null for the main thread
1659 * @param updateImmediately If true, the listener will be invoked
1660 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07001661 * @throws IllegalArgumentException if listener is null
1662 * @throws IllegalStateException if listener was already added
1663 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001664 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001665 Handler handler, boolean updateImmediately) {
1666 if (listener == null) {
1667 throw new IllegalArgumentException("the listener is null");
1668 }
1669 synchronized (mAccountsUpdatedListeners) {
1670 if (mAccountsUpdatedListeners.containsKey(listener)) {
1671 throw new IllegalStateException("this listener is already added");
1672 }
1673 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
1674
1675 mAccountsUpdatedListeners.put(listener, handler);
1676
1677 if (wasEmpty) {
1678 // Register a broadcast receiver to monitor account changes
1679 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001680 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07001681 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001682 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001683 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
1684 }
1685 }
1686
1687 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001688 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07001689 }
1690 }
1691
1692 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001693 * Removes an {@link OnAccountsUpdateListener} previously registered with
1694 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
1695 * receive notifications of account changes.
1696 *
1697 * <p>It is safe to call this method from the main thread.
1698 *
1699 * <p>No permission is required to call this method.
1700 *
1701 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07001702 * @throws IllegalArgumentException if listener is null
1703 * @throws IllegalStateException if listener was not already added
1704 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001705 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001706 if (listener == null) {
Costin Manolache88a211b2009-10-29 11:30:11 -07001707 Log.e(TAG, "Missing listener");
1708 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001709 }
1710 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01001711 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07001712 Log.e(TAG, "Listener was not previously added");
1713 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001714 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01001715 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001716 if (mAccountsUpdatedListeners.isEmpty()) {
1717 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
1718 }
1719 }
1720 }
Fred Quintana60307342009-03-24 22:48:12 -07001721}