blob: e2263fcb27b526745e28f8df56a2ea2edde60975 [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();
707 return bundle.getString(KEY_AUTHTOKEN);
708 }
709
710 /**
711 * Gets an auth token of the specified type for a particular account,
712 * prompting the user for credentials if necessary. This method is
713 * intended for applications running in the foreground where it makes
714 * sense to ask the user directly for a password.
715 *
716 * <p>If a previously generated auth token is cached for this account and
717 * type, then it will be returned. Otherwise, if we have a saved password
718 * the server accepts, it will be used to generate a new auth token.
719 * Otherwise, the user will be asked for a password, which will be sent to
720 * the server to generate a new auth token.
721 *
722 * <p>The value of the auth token type depends on the authenticator.
723 * Some services use different tokens to access different functionality --
724 * for example, Google uses different auth tokens to access Gmail and
725 * Google Calendar for the same account.
726 *
727 * <p>This method may be called from any thread, but the returned
728 * {@link AccountManagerFuture} must not be used on the main thread.
729 *
730 * <p>This method requires the caller to hold the permission
731 * {@link android.Manifest.permission#USE_CREDENTIALS}.
732 *
733 * @param account The account to fetch an auth token for
734 * @param authTokenType The auth token type, an authenticator-dependent
735 * string token, must not be null
736 * @param options Authenticator-specific options for the request,
737 * may be null or empty
738 * @param activity The {@link Activity} context to use for launching a new
739 * authenticator-defined sub-Activity to prompt the user for a password
740 * if necessary; used only to call startActivity(); must not be null.
741 * @param callback Callback to invoke when the request completes,
742 * null for no callback
743 * @param handler {@link Handler} identifying the callback thread,
744 * null for the main thread
745 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
746 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -0700747 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800748 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
749 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
750 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -0700751 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -0800752 *
753 * (Other authenticator-specific values may be returned.) If an auth token
754 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
755 * <ul>
756 * <li> {@link AuthenticatorException} if the authenticator failed to respond
757 * <li> {@link OperationCanceledException} if the operation is canceled for
758 * any reason, incluidng the user canceling a credential request
759 * <li> {@link IOException} if the authenticator experienced an I/O problem
760 * creating a new auth token, usually because of network trouble
761 * </ul>
762 */
763 public AccountManagerFuture<Bundle> getAuthToken(
764 final Account account, final String authTokenType, final Bundle options,
765 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
766 if (activity == null) throw new IllegalArgumentException("activity is null");
767 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
768 return new AmsTask(activity, handler, callback) {
769 public void doWork() throws RemoteException {
770 mService.getAuthToken(mResponse, account, authTokenType,
771 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
772 options);
773 }
774 }.start();
775 }
776
777 /**
778 * Gets an auth token of the specified type for a particular account,
779 * optionally raising a notification if the user must enter credentials.
780 * This method is intended for background tasks and services where the
781 * user should not be immediately interrupted with a password prompt.
782 *
783 * <p>If a previously generated auth token is cached for this account and
784 * type, then it will be returned. Otherwise, if we have saved credentials
785 * the server accepts, it will be used to generate a new auth token.
786 * Otherwise, an Intent will be returned which, when started, will prompt
787 * the user for a password. If the notifyAuthFailure parameter is set,
788 * the same Intent will be associated with a status bar notification,
789 * alerting the user that they need to enter a password at some point.
790 *
791 * <p>If the intent is left in a notification, you will need to wait until
792 * the user gets around to entering a password before trying again,
793 * which could be hours or days or never. When it does happen, the
794 * account manager will broadcast the {@link #LOGIN_ACCOUNTS_CHANGED_ACTION}
795 * {@link Intent}, which applications can use to trigger another attempt
796 * to fetch an auth token.
797 *
798 * <p>If notifications are not enabled, it is the application's
799 * responsibility to launch the returned intent at some point to let
800 * the user enter credentials. In either case, the result from this
801 * call will not wait for user action.
802 *
803 * <p>The value of the auth token type depends on the authenticator.
804 * Some services use different tokens to access different functionality --
805 * for example, Google uses different auth tokens to access Gmail and
806 * Google Calendar for the same account.
807 *
808 * <p>This method may be called from any thread, but the returned
809 * {@link AccountManagerFuture} must not be used on the main thread.
810 *
811 * <p>This method requires the caller to hold the permission
812 * {@link android.Manifest.permission#USE_CREDENTIALS}.
813 *
814 * @param account The account to fetch an auth token for
815 * @param authTokenType The auth token type, an authenticator-dependent
816 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -0800817 * @param notifyAuthFailure True to add a notification to prompt the
818 * user for a password if necessary, false to leave that to the caller
819 * @param callback Callback to invoke when the request completes,
820 * null for no callback
821 * @param handler {@link Handler} identifying the callback thread,
822 * null for the main thread
823 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
824 * at least the following fields on success:
825 * <ul>
826 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
827 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
828 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
829 * </ul>
830 *
831 * (Other authenticator-specific values may be returned.) If the user
832 * must enter credentials, the returned Bundle contains only
833 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
834 *
835 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
836 * <ul>
837 * <li> {@link AuthenticatorException} if the authenticator failed to respond
838 * <li> {@link OperationCanceledException} if the operation is canceled for
839 * any reason, incluidng the user canceling a credential request
840 * <li> {@link IOException} if the authenticator experienced an I/O problem
841 * creating a new auth token, usually because of network trouble
842 * </ul>
843 */
844 public AccountManagerFuture<Bundle> getAuthToken(
845 final Account account, final String authTokenType, final boolean notifyAuthFailure,
846 AccountManagerCallback<Bundle> callback, Handler handler) {
847 if (account == null) throw new IllegalArgumentException("account is null");
848 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
849 return new AmsTask(null, handler, callback) {
850 public void doWork() throws RemoteException {
851 mService.getAuthToken(mResponse, account, authTokenType,
852 notifyAuthFailure, false /* expectActivityLaunch */, null /* options */);
853 }
854 }.start();
855 }
856
857 /**
858 * Asks the user to add an account of a specified type. The authenticator
859 * for this account type processes this request with the appropriate user
860 * interface. If the user does elect to create a new account, the account
861 * name is returned.
862 *
863 * <p>This method may be called from any thread, but the returned
864 * {@link AccountManagerFuture} must not be used on the main thread.
865 *
866 * <p>This method requires the caller to hold the permission
867 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
868 *
869 * @param accountType The type of account to add; must not be null
870 * @param authTokenType The type of auth token (see {@link #getAuthToken})
871 * this account will need to be able to generate, null for none
872 * @param requiredFeatures The features (see {@link #hasFeatures}) this
873 * account must have, null for none
874 * @param addAccountOptions Authenticator-specific options for the request,
875 * may be null or empty
876 * @param activity The {@link Activity} context to use for launching a new
877 * authenticator-defined sub-Activity to prompt the user to create an
878 * account; used only to call startActivity(); if null, the prompt
879 * will not be launched directly, but the necessary {@link Intent}
880 * will be returned to the caller instead
881 * @param callback Callback to invoke when the request completes,
882 * null for no callback
883 * @param handler {@link Handler} identifying the callback thread,
884 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -0800885 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -0800886 * these fields if activity was specified and an account was created:
887 * <ul>
888 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
889 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
890 * </ul>
891 *
892 * If no activity was specified, the returned Bundle contains only
893 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
894 * actual account creation process.
895 *
896 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
897 * <ul>
898 * <li> {@link AuthenticatorException} if no authenticator was registered for
899 * this account type or the authenticator failed to respond
900 * <li> {@link OperationCanceledException} if the operation was canceled for
901 * any reason, including the user canceling the creation process
902 * <li> {@link IOException} if the authenticator experienced an I/O problem
903 * creating a new account, usually because of network trouble
904 * </ul>
905 */
906 public AccountManagerFuture<Bundle> addAccount(final String accountType,
907 final String authTokenType, final String[] requiredFeatures,
908 final Bundle addAccountOptions,
909 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
910 return new AmsTask(activity, handler, callback) {
911 public void doWork() throws RemoteException {
912 if (accountType == null) {
913 Log.e(TAG, "the account must not be null");
914 // to unblock caller waiting on Future.get()
915 set(new Bundle());
916 return;
917 }
918 mService.addAcount(mResponse, accountType, authTokenType,
919 requiredFeatures, activity != null, addAccountOptions);
920 }
921 }.start();
922 }
923
924 /**
925 * Confirms that the user knows the password for an account to make extra
926 * sure they are the owner of the account. The user-entered password can
927 * be supplied directly, otherwise the authenticator for this account type
928 * prompts the user with the appropriate interface. This method is
929 * intended for applications which want extra assurance; for example, the
930 * phone lock screen uses this to let the user unlock the phone with an
931 * account password if they forget the lock pattern.
932 *
933 * <p>If the user-entered password matches a saved password for this
934 * account, the request is considered valid; otherwise the authenticator
935 * verifies the password (usually by contacting the server).
936 *
937 * <p>This method may be called from any thread, but the returned
938 * {@link AccountManagerFuture} must not be used on the main thread.
939 *
940 * <p>This method requires the caller to hold the permission
941 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
942 *
943 * @param account The account to confirm password knowledge for
944 * @param options Authenticator-specific options for the request;
945 * if the {@link #KEY_PASSWORD} string field is present, the
946 * authenticator may use it directly rather than prompting the user;
947 * may be null or empty
948 * @param activity The {@link Activity} context to use for launching a new
949 * authenticator-defined sub-Activity to prompt the user to enter a
950 * password; used only to call startActivity(); if null, the prompt
951 * will not be launched directly, but the necessary {@link Intent}
952 * will be returned to the caller instead
953 * @param callback Callback to invoke when the request completes,
954 * null for no callback
955 * @param handler {@link Handler} identifying the callback thread,
956 * null for the main thread
957 * @return An {@link AccountManagerFuture} which resolves to a Bundle
958 * with these fields if activity or password was supplied and
959 * the account was successfully verified:
960 * <ul>
961 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
962 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
963 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
964 * </ul>
965 *
966 * If no activity or password was specified, the returned Bundle contains
967 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
968 * password prompt.
969 *
970 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
971 * <ul>
972 * <li> {@link AuthenticatorException} if the authenticator failed to respond
973 * <li> {@link OperationCanceledException} if the operation was canceled for
974 * any reason, including the user canceling the password prompt
975 * <li> {@link IOException} if the authenticator experienced an I/O problem
976 * verifying the password, usually because of network trouble
977 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -0700978 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700979 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
980 final Bundle options,
981 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700982 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -0700983 final Handler handler) {
984 return new AmsTask(activity, handler, callback) {
985 public void doWork() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700986 mService.confirmCredentials(mResponse, account, options, activity != null);
Fred Quintanaa698f422009-04-08 19:14:54 -0700987 }
Fred Quintana33269202009-04-20 16:05:10 -0700988 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -0700989 }
990
Fred Quintana756b7352009-10-21 13:43:10 -0700991 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800992 * Asks the user to enter a new password for an account, updating the
993 * saved credentials for the account. Normally this happens automatically
994 * when the server rejects credentials during an auth token fetch, but this
995 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -0700996 *
Dan Egnor661f0132010-02-19 11:23:00 -0800997 * <p>This method may be called from any thread, but the returned
998 * {@link AccountManagerFuture} must not be used on the main thread.
999 *
1000 * <p>This method requires the caller to hold the permission
1001 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1002 *
1003 * @param account The account to update credentials for
1004 * @param authTokenType The credentials entered must allow an auth token
1005 * of this type to be created (but no actual auth token is returned);
1006 * may be null
1007 * @param options Authenticator-specific options for the request;
1008 * may be null or empty
1009 * @param activity The {@link Activity} context to use for launching a new
1010 * authenticator-defined sub-Activity to prompt the user to enter a
1011 * password; used only to call startActivity(); if null, the prompt
1012 * will not be launched directly, but the necessary {@link Intent}
1013 * will be returned to the caller instead
1014 * @param callback Callback to invoke when the request completes,
1015 * null for no callback
1016 * @param handler {@link Handler} identifying the callback thread,
1017 * null for the main thread
1018 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1019 * with these fields if an activity was supplied and the account
1020 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001021 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001022 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1023 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001024 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001025 *
1026 * If no activity was specified, the returned Bundle contains only
1027 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1028 * password prompt.
1029 *
1030 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1031 * <ul>
1032 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1033 * <li> {@link OperationCanceledException} if the operation was canceled for
1034 * any reason, including the user canceling the password prompt
1035 * <li> {@link IOException} if the authenticator experienced an I/O problem
1036 * verifying the password, usually because of network trouble
1037 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001038 */
1039 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1040 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001041 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001042 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001043 final Handler handler) {
1044 return new AmsTask(activity, handler, callback) {
1045 public void doWork() throws RemoteException {
1046 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001047 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001048 }
Fred Quintana33269202009-04-20 16:05:10 -07001049 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001050 }
1051
Fred Quintana756b7352009-10-21 13:43:10 -07001052 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001053 * Offers the user an opportunity to change an authenticator's settings.
1054 * These properties are for the authenticator in general, not a particular
1055 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001056 *
Dan Egnor661f0132010-02-19 11:23:00 -08001057 * <p>This method may be called from any thread, but the returned
1058 * {@link AccountManagerFuture} must not be used on the main thread.
1059 *
1060 * <p>This method requires the caller to hold the permission
1061 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1062 *
1063 * @param accountType The account type associated with the authenticator
1064 * to adjust
1065 * @param activity The {@link Activity} context to use for launching a new
1066 * authenticator-defined sub-Activity to adjust authenticator settings;
1067 * used only to call startActivity(); if null, the settings dialog will
1068 * not be launched directly, but the necessary {@link Intent} will be
1069 * returned to the caller instead
1070 * @param callback Callback to invoke when the request completes,
1071 * null for no callback
1072 * @param handler {@link Handler} identifying the callback thread,
1073 * null for the main thread
1074 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1075 * which is empty if properties were edited successfully, or
1076 * if no activity was specified, contains only {@link #KEY_INTENT}
1077 * needed to launch the authenticator's settings dialog.
1078 *
1079 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001080 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001081 * <li> {@link AuthenticatorException} if no authenticator was registered for
1082 * this account type or the authenticator failed to respond
1083 * <li> {@link OperationCanceledException} if the operation was canceled for
1084 * any reason, including the user canceling the settings dialog
1085 * <li> {@link IOException} if the authenticator experienced an I/O problem
1086 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001087 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001088 */
1089 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1090 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001091 final Handler handler) {
1092 return new AmsTask(activity, handler, callback) {
1093 public void doWork() throws RemoteException {
1094 mService.editProperties(mResponse, accountType, activity != null);
1095 }
Fred Quintana33269202009-04-20 16:05:10 -07001096 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001097 }
1098
1099 private void ensureNotOnMainThread() {
1100 final Looper looper = Looper.myLooper();
1101 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001102 final IllegalStateException exception = new IllegalStateException(
1103 "calling this from your main thread can lead to deadlock");
1104 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1105 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001106 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1107 throw exception;
1108 }
Fred Quintana60307342009-03-24 22:48:12 -07001109 }
1110 }
1111
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001112 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1113 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001114 handler = handler == null ? mMainHandler : handler;
1115 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001116 public void run() {
1117 callback.run(future);
1118 }
1119 });
1120 }
Fred Quintana60307342009-03-24 22:48:12 -07001121
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001122 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001123 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001124 final Account[] accountsCopy = new Account[accounts.length];
1125 // send a copy to make sure that one doesn't
1126 // change what another sees
1127 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1128 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001129 handler.post(new Runnable() {
1130 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001131 try {
1132 listener.onAccountsUpdated(accountsCopy);
1133 } catch (SQLException e) {
1134 // Better luck next time. If the problem was disk-full,
1135 // the STORAGE_OK intent will re-trigger the update.
1136 Log.e(TAG, "Can't update accounts", e);
1137 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001138 }
1139 });
1140 }
1141
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001142 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001143 final IAccountManagerResponse mResponse;
1144 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001145 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001146 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001147 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001148 super(new Callable<Bundle>() {
1149 public Bundle call() throws Exception {
1150 throw new IllegalStateException("this should never be called");
1151 }
1152 });
1153
1154 mHandler = handler;
1155 mCallback = callback;
1156 mActivity = activity;
1157 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001158 }
1159
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001160 public final AccountManagerFuture<Bundle> start() {
1161 try {
1162 doWork();
1163 } catch (RemoteException e) {
1164 setException(e);
1165 }
Fred Quintana33269202009-04-20 16:05:10 -07001166 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001167 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001168
1169 public abstract void doWork() throws RemoteException;
1170
1171 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1172 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001173 if (!isDone()) {
1174 ensureNotOnMainThread();
1175 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001176 try {
1177 if (timeout == null) {
1178 return get();
1179 } else {
1180 return get(timeout, unit);
1181 }
1182 } catch (CancellationException e) {
1183 throw new OperationCanceledException();
1184 } catch (TimeoutException e) {
1185 // fall through and cancel
1186 } catch (InterruptedException e) {
1187 // fall through and cancel
1188 } catch (ExecutionException e) {
1189 final Throwable cause = e.getCause();
1190 if (cause instanceof IOException) {
1191 throw (IOException) cause;
1192 } else if (cause instanceof UnsupportedOperationException) {
1193 throw new AuthenticatorException(cause);
1194 } else if (cause instanceof AuthenticatorException) {
1195 throw (AuthenticatorException) cause;
1196 } else if (cause instanceof RuntimeException) {
1197 throw (RuntimeException) cause;
1198 } else if (cause instanceof Error) {
1199 throw (Error) cause;
1200 } else {
1201 throw new IllegalStateException(cause);
1202 }
1203 } finally {
1204 cancel(true /* interrupt if running */);
1205 }
1206 throw new OperationCanceledException();
1207 }
1208
1209 public Bundle getResult()
1210 throws OperationCanceledException, IOException, AuthenticatorException {
1211 return internalGetResult(null, null);
1212 }
1213
1214 public Bundle getResult(long timeout, TimeUnit unit)
1215 throws OperationCanceledException, IOException, AuthenticatorException {
1216 return internalGetResult(timeout, unit);
1217 }
1218
1219 protected void done() {
1220 if (mCallback != null) {
1221 postToHandler(mHandler, mCallback, this);
1222 }
1223 }
1224
1225 /** Handles the responses from the AccountManager */
1226 private class Response extends IAccountManagerResponse.Stub {
1227 public void onResult(Bundle bundle) {
1228 Intent intent = bundle.getParcelable("intent");
1229 if (intent != null && mActivity != null) {
1230 // since the user provided an Activity we will silently start intents
1231 // that we see
1232 mActivity.startActivity(intent);
1233 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001234 } else if (bundle.getBoolean("retry")) {
1235 try {
1236 doWork();
1237 } catch (RemoteException e) {
1238 // this will only happen if the system process is dead, which means
1239 // we will be dying ourselves
1240 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001241 } else {
1242 set(bundle);
1243 }
1244 }
1245
1246 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001247 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001248 // the authenticator indicated that this request was canceled, do so now
1249 cancel(true /* mayInterruptIfRunning */);
1250 return;
1251 }
1252 setException(convertErrorToException(code, message));
1253 }
1254 }
1255
Fred Quintana60307342009-03-24 22:48:12 -07001256 }
1257
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001258 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1259 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001260 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001261
1262 public BaseFutureTask(Handler handler) {
1263 super(new Callable<T>() {
1264 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001265 throw new IllegalStateException("this should never be called");
1266 }
1267 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001268 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001269 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001270 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001271
1272 public abstract void doWork() throws RemoteException;
1273
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001274 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001275
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001276 protected void postRunnableToHandler(Runnable runnable) {
1277 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1278 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001279 }
1280
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001281 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001282 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001283 doWork();
1284 } catch (RemoteException e) {
1285 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001286 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001287 }
1288
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001289 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001290 public void onResult(Bundle bundle) {
1291 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001292 T result = bundleToResult(bundle);
1293 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001294 return;
1295 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001296 set(result);
1297 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001298 } catch (ClassCastException e) {
1299 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001300 } catch (AuthenticatorException e) {
1301 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001302 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001303 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001304 }
1305
1306 public void onError(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001307 if (code == ERROR_CODE_CANCELED) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001308 cancel(true /* mayInterruptIfRunning */);
1309 return;
1310 }
1311 setException(convertErrorToException(code, message));
1312 }
1313 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001314 }
1315
1316 private abstract class Future2Task<T>
1317 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1318 final AccountManagerCallback<T> mCallback;
1319 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1320 super(handler);
1321 mCallback = callback;
1322 }
1323
1324 protected void done() {
1325 if (mCallback != null) {
1326 postRunnableToHandler(new Runnable() {
1327 public void run() {
1328 mCallback.run(Future2Task.this);
1329 }
1330 });
1331 }
1332 }
1333
1334 public Future2Task<T> start() {
1335 startTask();
1336 return this;
1337 }
1338
1339 private T internalGetResult(Long timeout, TimeUnit unit)
1340 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001341 if (!isDone()) {
1342 ensureNotOnMainThread();
1343 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001344 try {
1345 if (timeout == null) {
1346 return get();
1347 } else {
1348 return get(timeout, unit);
1349 }
1350 } catch (InterruptedException e) {
1351 // fall through and cancel
1352 } catch (TimeoutException e) {
1353 // fall through and cancel
1354 } catch (CancellationException e) {
1355 // fall through and cancel
1356 } catch (ExecutionException e) {
1357 final Throwable cause = e.getCause();
1358 if (cause instanceof IOException) {
1359 throw (IOException) cause;
1360 } else if (cause instanceof UnsupportedOperationException) {
1361 throw new AuthenticatorException(cause);
1362 } else if (cause instanceof AuthenticatorException) {
1363 throw (AuthenticatorException) cause;
1364 } else if (cause instanceof RuntimeException) {
1365 throw (RuntimeException) cause;
1366 } else if (cause instanceof Error) {
1367 throw (Error) cause;
1368 } else {
1369 throw new IllegalStateException(cause);
1370 }
1371 } finally {
1372 cancel(true /* interrupt if running */);
1373 }
1374 throw new OperationCanceledException();
1375 }
1376
1377 public T getResult()
1378 throws OperationCanceledException, IOException, AuthenticatorException {
1379 return internalGetResult(null, null);
1380 }
1381
1382 public T getResult(long timeout, TimeUnit unit)
1383 throws OperationCanceledException, IOException, AuthenticatorException {
1384 return internalGetResult(timeout, unit);
1385 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001386
Fred Quintana60307342009-03-24 22:48:12 -07001387 }
1388
Fred Quintanaa698f422009-04-08 19:14:54 -07001389 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001390 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001391 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001392 }
Fred Quintana60307342009-03-24 22:48:12 -07001393
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001394 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07001395 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001396 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001397
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001398 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07001399 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07001400 }
1401
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001402 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07001403 return new IllegalArgumentException(message);
1404 }
1405
1406 return new AuthenticatorException(message);
1407 }
1408
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001409 private class GetAuthTokenByTypeAndFeaturesTask
1410 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07001411 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1412 final String[] features, Activity activityForPrompting,
1413 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001414 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001415 super(activityForPrompting, handler, callback);
1416 if (accountType == null) throw new IllegalArgumentException("account type is null");
1417 mAccountType = accountType;
1418 mAuthTokenType = authTokenType;
1419 mFeatures = features;
1420 mAddAccountOptions = addAccountOptions;
1421 mLoginOptions = loginOptions;
1422 mMyCallback = this;
1423 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001424 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07001425 final String mAccountType;
1426 final String mAuthTokenType;
1427 final String[] mFeatures;
1428 final Bundle mAddAccountOptions;
1429 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001430 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintana33269202009-04-20 16:05:10 -07001431
1432 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001433 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
1434 new AccountManagerCallback<Account[]>() {
1435 public void run(AccountManagerFuture<Account[]> future) {
1436 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07001437 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001438 accounts = future.getResult();
1439 } catch (OperationCanceledException e) {
1440 setException(e);
1441 return;
1442 } catch (IOException e) {
1443 setException(e);
1444 return;
1445 } catch (AuthenticatorException e) {
1446 setException(e);
1447 return;
Fred Quintana33269202009-04-20 16:05:10 -07001448 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001449
1450 if (accounts.length == 0) {
1451 if (mActivity != null) {
1452 // no accounts, add one now. pretend that the user directly
1453 // made this request
1454 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
1455 mAddAccountOptions, mActivity, mMyCallback, mHandler);
1456 } else {
1457 // send result since we can't prompt to add an account
1458 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001459 result.putString(KEY_ACCOUNT_NAME, null);
1460 result.putString(KEY_ACCOUNT_TYPE, null);
1461 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001462 try {
1463 mResponse.onResult(result);
1464 } catch (RemoteException e) {
1465 // this will never happen
1466 }
1467 // we are done
1468 }
1469 } else if (accounts.length == 1) {
1470 // have a single account, return an authtoken for it
1471 if (mActivity == null) {
1472 mFuture = getAuthToken(accounts[0], mAuthTokenType,
1473 false /* notifyAuthFailure */, mMyCallback, mHandler);
1474 } else {
1475 mFuture = getAuthToken(accounts[0],
1476 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07001477 mActivity, mMyCallback, mHandler);
1478 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001479 } else {
1480 if (mActivity != null) {
1481 IAccountManagerResponse chooseResponse =
1482 new IAccountManagerResponse.Stub() {
1483 public void onResult(Bundle value) throws RemoteException {
1484 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001485 value.getString(KEY_ACCOUNT_NAME),
1486 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001487 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
1488 mActivity, mMyCallback, mHandler);
1489 }
Fred Quintana33269202009-04-20 16:05:10 -07001490
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001491 public void onError(int errorCode, String errorMessage)
1492 throws RemoteException {
1493 mResponse.onError(errorCode, errorMessage);
1494 }
1495 };
1496 // have many accounts, launch the chooser
1497 Intent intent = new Intent();
1498 intent.setClassName("android",
1499 "android.accounts.ChooseAccountActivity");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001500 intent.putExtra(KEY_ACCOUNTS, accounts);
1501 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001502 new AccountManagerResponse(chooseResponse));
1503 mActivity.startActivity(intent);
1504 // the result will arrive via the IAccountManagerResponse
1505 } else {
1506 // send result since we can't prompt to select an account
1507 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001508 result.putString(KEY_ACCOUNTS, 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
Fred Quintana33269202009-04-20 16:05:10 -07001515 }
Fred Quintana33269202009-04-20 16:05:10 -07001516 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001517 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07001518 }
1519
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001520 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07001521 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001522 set(future.getResult());
1523 } catch (OperationCanceledException e) {
1524 cancel(true /* mayInterruptIfRUnning */);
1525 } catch (IOException e) {
1526 setException(e);
1527 } catch (AuthenticatorException e) {
1528 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07001529 }
1530 }
1531 }
1532
Fred Quintana756b7352009-10-21 13:43:10 -07001533 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001534 * This convenience helper combines the functionality of
1535 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
1536 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07001537 *
Dan Egnor661f0132010-02-19 11:23:00 -08001538 * <p>This method gets a list of the accounts matching the
1539 * specified type and feature set; if there is exactly one, it is
1540 * used; if there are more than one, the user is prompted to pick one;
1541 * if there are none, the user is prompted to add one. Finally,
1542 * an auth token is acquired for the chosen account.
1543 *
1544 * <p>This method may be called from any thread, but the returned
1545 * {@link AccountManagerFuture} must not be used on the main thread.
1546 *
1547 * <p>This method requires the caller to hold the permission
1548 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1549 *
1550 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08001551 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001552 * @param authTokenType The desired auth token type
1553 * (see {@link #getAuthToken}), must not be null
1554 * @param features Required features for the account
1555 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
1556 * @param activity The {@link Activity} context to use for launching new
1557 * sub-Activities to prompt to add an account, select an account,
1558 * and/or enter a password, as necessary; used only to call
1559 * startActivity(); should not be null
1560 * @param addAccountOptions Authenticator-specific options to use for
1561 * adding new accounts; may be null or empty
1562 * @param getAuthTokenOptions Authenticator-specific options to use for
1563 * getting auth tokens; may be null or empty
1564 * @param callback Callback to invoke when the request completes,
1565 * null for no callback
1566 * @param handler {@link Handler} identifying the callback thread,
1567 * null for the main thread
1568 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1569 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001570 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001571 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
1572 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1573 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001574 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001575 *
1576 * <p>If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1577 * <ul>
1578 * <li> {@link AuthenticatorException} if no authenticator was registered for
1579 * this account type or the authenticator failed to respond
1580 * <li> {@link OperationCanceledException} if the operation was canceled for
1581 * any reason, including the user canceling any operation
1582 * <li> {@link IOException} if the authenticator experienced an I/O problem
1583 * updating settings, usually because of network trouble
1584 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001585 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001586 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07001587 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08001588 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07001589 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001590 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001591 if (accountType == null) throw new IllegalArgumentException("account type is null");
1592 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001593 final GetAuthTokenByTypeAndFeaturesTask task =
1594 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08001595 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001596 task.start();
1597 return task;
Fred Quintana60307342009-03-24 22:48:12 -07001598 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001599
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001600 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07001601 Maps.newHashMap();
1602
Fred Quintanad9d2f112009-04-23 13:36:27 -07001603 /**
1604 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
1605 * so that it can read the updated list of accounts and send them to the listener
1606 * in mAccountsUpdatedListeners.
1607 */
1608 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
1609 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001610 final Account[] accounts = getAccounts();
1611 // send the result to the listeners
1612 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001613 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001614 mAccountsUpdatedListeners.entrySet()) {
1615 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001616 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001617 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001618 }
1619 };
1620
1621 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001622 * Adds an {@link OnAccountsUpdateListener} to this instance of the
1623 * {@link AccountManager}. This listener will be notified whenever the
1624 * list of accounts on the device changes.
1625 *
1626 * <p>As long as this listener is present, the AccountManager instance
1627 * will not be garbage-collected, and neither will the {@link Context}
1628 * used to retrieve it, which may be a large Activity instance. To avoid
1629 * memory leaks, you must remove this listener before then. Normally
1630 * listeners are added in an Activity or Service's {@link Activity#onCreate}
1631 * and removed in {@link Activity#onDestroy}.
1632 *
1633 * <p>It is safe to call this method from the main thread.
1634 *
1635 * <p>No permission is required to call this method.
1636 *
1637 * @param listener The listener to send notifications to
1638 * @param handler {@link Handler} identifying the thread to use
1639 * for notifications, null for the main thread
1640 * @param updateImmediately If true, the listener will be invoked
1641 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07001642 * @throws IllegalArgumentException if listener is null
1643 * @throws IllegalStateException if listener was already added
1644 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001645 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001646 Handler handler, boolean updateImmediately) {
1647 if (listener == null) {
1648 throw new IllegalArgumentException("the listener is null");
1649 }
1650 synchronized (mAccountsUpdatedListeners) {
1651 if (mAccountsUpdatedListeners.containsKey(listener)) {
1652 throw new IllegalStateException("this listener is already added");
1653 }
1654 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
1655
1656 mAccountsUpdatedListeners.put(listener, handler);
1657
1658 if (wasEmpty) {
1659 // Register a broadcast receiver to monitor account changes
1660 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001661 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07001662 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001663 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001664 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
1665 }
1666 }
1667
1668 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001669 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07001670 }
1671 }
1672
1673 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001674 * Removes an {@link OnAccountsUpdateListener} previously registered with
1675 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
1676 * receive notifications of account changes.
1677 *
1678 * <p>It is safe to call this method from the main thread.
1679 *
1680 * <p>No permission is required to call this method.
1681 *
1682 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07001683 * @throws IllegalArgumentException if listener is null
1684 * @throws IllegalStateException if listener was not already added
1685 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001686 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001687 if (listener == null) {
Costin Manolache88a211b2009-10-29 11:30:11 -07001688 Log.e(TAG, "Missing listener");
1689 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001690 }
1691 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01001692 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07001693 Log.e(TAG, "Listener was not previously added");
1694 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001695 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01001696 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07001697 if (mAccountsUpdatedListeners.isEmpty()) {
1698 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
1699 }
1700 }
1701 }
Fred Quintana60307342009-03-24 22:48:12 -07001702}