AccountManager.java revision 3df7d697ca86ee2081bcfba31bcbd3ae4f4bcdf8
1/* 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 19import android.app.Activity; 20import android.content.Intent; 21import android.content.ComponentName; 22import android.content.Context; 23import android.content.IntentFilter; 24import android.content.BroadcastReceiver; 25import android.content.res.Resources; 26import android.database.SQLException; 27import android.os.Bundle; 28import android.os.Handler; 29import android.os.Looper; 30import android.os.RemoteException; 31import android.os.Parcelable; 32import android.os.Build; 33import android.os.Process; 34import android.os.UserHandle; 35import android.util.Log; 36import android.text.TextUtils; 37 38import java.io.IOException; 39import java.util.ArrayList; 40import java.util.concurrent.Callable; 41import java.util.concurrent.CancellationException; 42import java.util.concurrent.ExecutionException; 43import java.util.concurrent.FutureTask; 44import java.util.concurrent.TimeoutException; 45import java.util.concurrent.TimeUnit; 46import java.util.HashMap; 47import java.util.Map; 48 49import com.android.internal.R; 50import com.google.android.collect.Maps; 51 52/** 53 * This class provides access to a centralized registry of the user's 54 * online accounts. The user enters credentials (username and password) once 55 * per account, granting applications access to online resources with 56 * "one-click" approval. 57 * 58 * <p>Different online services have different ways of handling accounts and 59 * authentication, so the account manager uses pluggable <em>authenticator</em> 60 * modules for different <em>account types</em>. Authenticators (which may be 61 * written by third parties) handle the actual details of validating account 62 * credentials and storing account information. For example, Google, Facebook, 63 * and Microsoft Exchange each have their own authenticator. 64 * 65 * <p>Many servers support some notion of an <em>authentication token</em>, 66 * which can be used to authenticate a request to the server without sending 67 * the user's actual password. (Auth tokens are normally created with a 68 * separate request which does include the user's credentials.) AccountManager 69 * can generate auth tokens for applications, so the application doesn't need to 70 * handle passwords directly. Auth tokens are normally reusable and cached by 71 * AccountManager, but must be refreshed periodically. It's the responsibility 72 * of applications to <em>invalidate</em> auth tokens when they stop working so 73 * the AccountManager knows it needs to regenerate them. 74 * 75 * <p>Applications accessing a server normally go through these steps: 76 * 77 * <ul> 78 * <li>Get an instance of AccountManager using {@link #get(Context)}. 79 * 80 * <li>List the available accounts using {@link #getAccountsByType} or 81 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only 82 * be interested in accounts with one particular <em>type</em>, which 83 * identifies the authenticator. Account <em>features</em> are used to 84 * identify particular account subtypes and capabilities. Both the account 85 * type and features are authenticator-specific strings, and must be known by 86 * the application in coordination with its preferred authenticators. 87 * 88 * <li>Select one or more of the available accounts, possibly by asking the 89 * user for their preference. If no suitable accounts are available, 90 * {@link #addAccount} may be called to prompt the user to create an 91 * account of the appropriate type. 92 * 93 * <li><b>Important:</b> If the application is using a previously remembered 94 * account selection, it must make sure the account is still in the list 95 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token 96 * for an account no longer on the device results in an undefined failure. 97 * 98 * <li>Request an auth token for the selected account(s) using one of the 99 * {@link #getAuthToken} methods or related helpers. Refer to the description 100 * of each method for exact usage and error handling details. 101 * 102 * <li>Make the request using the auth token. The form of the auth token, 103 * the format of the request, and the protocol used are all specific to the 104 * service you are accessing. The application may use whatever network and 105 * protocol libraries are useful. 106 * 107 * <li><b>Important:</b> If the request fails with an authentication error, 108 * it could be that a cached auth token is stale and no longer honored by 109 * the server. The application must call {@link #invalidateAuthToken} to remove 110 * the token from the cache, otherwise requests will continue failing! After 111 * invalidating the auth token, immediately go back to the "Request an auth 112 * token" step above. If the process fails the second time, then it can be 113 * treated as a "genuine" authentication failure and the user notified or other 114 * appropriate actions taken. 115 * </ul> 116 * 117 * <p>Some AccountManager methods may need to interact with the user to 118 * prompt for credentials, present options, or ask the user to add an account. 119 * The caller may choose whether to allow AccountManager to directly launch the 120 * necessary user interface and wait for the user, or to return an Intent which 121 * the caller may use to launch the interface, or (in some cases) to install a 122 * notification which the user can select at any time to launch the interface. 123 * To have AccountManager launch the interface directly, the caller must supply 124 * the current foreground {@link Activity} context. 125 * 126 * <p>Many AccountManager methods take {@link AccountManagerCallback} and 127 * {@link Handler} as parameters. These methods return immediately and 128 * run asynchronously. If a callback is provided then 129 * {@link AccountManagerCallback#run} will be invoked on the Handler's 130 * thread when the request completes, successfully or not. 131 * The result is retrieved by calling {@link AccountManagerFuture#getResult()} 132 * on the {@link AccountManagerFuture} returned by the method (and also passed 133 * to the callback). This method waits for the operation to complete (if 134 * necessary) and either returns the result or throws an exception if an error 135 * occurred during the operation. To make the request synchronously, call 136 * {@link AccountManagerFuture#getResult()} immediately on receiving the 137 * future from the method; no callback need be supplied. 138 * 139 * <p>Requests which may block, including 140 * {@link AccountManagerFuture#getResult()}, must never be called on 141 * the application's main event thread. These operations throw 142 * {@link IllegalStateException} if they are used on the main thread. 143 */ 144public class AccountManager { 145 private static final String TAG = "AccountManager"; 146 147 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1; 148 public static final int ERROR_CODE_NETWORK_ERROR = 3; 149 public static final int ERROR_CODE_CANCELED = 4; 150 public static final int ERROR_CODE_INVALID_RESPONSE = 5; 151 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6; 152 public static final int ERROR_CODE_BAD_ARGUMENTS = 7; 153 public static final int ERROR_CODE_BAD_REQUEST = 8; 154 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9; 155 156 /** @hide */ 157 public static final int ERROR_CODE_USER_RESTRICTED = 100; 158 159 /** 160 * Bundle key used for the {@link String} account name in results 161 * from methods which return information about a particular account. 162 */ 163 public static final String KEY_ACCOUNT_NAME = "authAccount"; 164 165 /** 166 * Bundle key used for the {@link String} account type in results 167 * from methods which return information about a particular account. 168 */ 169 public static final String KEY_ACCOUNT_TYPE = "accountType"; 170 171 /** 172 * Bundle key used for the auth token value in results 173 * from {@link #getAuthToken} and friends. 174 */ 175 public static final String KEY_AUTHTOKEN = "authtoken"; 176 177 /** 178 * Bundle key used for an {@link Intent} in results from methods that 179 * may require the caller to interact with the user. The Intent can 180 * be used to start the corresponding user interface activity. 181 */ 182 public static final String KEY_INTENT = "intent"; 183 184 /** 185 * Bundle key used to supply the password directly in options to 186 * {@link #confirmCredentials}, rather than prompting the user with 187 * the standard password prompt. 188 */ 189 public static final String KEY_PASSWORD = "password"; 190 191 public static final String KEY_ACCOUNTS = "accounts"; 192 193 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse"; 194 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse"; 195 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types"; 196 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage"; 197 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey"; 198 public static final String KEY_BOOLEAN_RESULT = "booleanResult"; 199 public static final String KEY_ERROR_CODE = "errorCode"; 200 public static final String KEY_ERROR_MESSAGE = "errorMessage"; 201 public static final String KEY_USERDATA = "userdata"; 202 203 /** 204 * Authenticators using 'customTokens' option will also get the UID of the 205 * caller 206 */ 207 public static final String KEY_CALLER_UID = "callerUid"; 208 public static final String KEY_CALLER_PID = "callerPid"; 209 210 /** 211 * The Android package of the caller will be set in the options bundle by the 212 * {@link AccountManager} and will be passed to the AccountManagerService and 213 * to the AccountAuthenticators. The uid of the caller will be known by the 214 * AccountManagerService as well as the AccountAuthenticators so they will be able to 215 * verify that the package is consistent with the uid (a uid might be shared by many 216 * packages). 217 */ 218 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName"; 219 220 /** 221 * Boolean, if set and 'customTokens' the authenticator is responsible for 222 * notifications. 223 * @hide 224 */ 225 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure"; 226 227 public static final String ACTION_AUTHENTICATOR_INTENT = 228 "android.accounts.AccountAuthenticator"; 229 public static final String AUTHENTICATOR_META_DATA_NAME = 230 "android.accounts.AccountAuthenticator"; 231 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator"; 232 233 private final Context mContext; 234 private final IAccountManager mService; 235 private final Handler mMainHandler; 236 237 /** 238 * Action sent as a broadcast Intent by the AccountsService 239 * when accounts are added, accounts are removed, or an 240 * account's credentials (saved password, etc) are changed. 241 * 242 * @see #addOnAccountsUpdatedListener 243 */ 244 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION = 245 "android.accounts.LOGIN_ACCOUNTS_CHANGED"; 246 247 /** 248 * @hide 249 */ 250 public AccountManager(Context context, IAccountManager service) { 251 mContext = context; 252 mService = service; 253 mMainHandler = new Handler(mContext.getMainLooper()); 254 } 255 256 /** 257 * @hide used for testing only 258 */ 259 public AccountManager(Context context, IAccountManager service, Handler handler) { 260 mContext = context; 261 mService = service; 262 mMainHandler = handler; 263 } 264 265 /** 266 * @hide for internal use only 267 */ 268 public static Bundle sanitizeResult(Bundle result) { 269 if (result != null) { 270 if (result.containsKey(KEY_AUTHTOKEN) 271 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) { 272 final Bundle newResult = new Bundle(result); 273 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>"); 274 return newResult; 275 } 276 } 277 return result; 278 } 279 280 /** 281 * Gets an AccountManager instance associated with a Context. 282 * The {@link Context} will be used as long as the AccountManager is 283 * active, so make sure to use a {@link Context} whose lifetime is 284 * commensurate with any listeners registered to 285 * {@link #addOnAccountsUpdatedListener} or similar methods. 286 * 287 * <p>It is safe to call this method from the main thread. 288 * 289 * <p>No permission is required to call this method. 290 * 291 * @param context The {@link Context} to use when necessary 292 * @return An {@link AccountManager} instance 293 */ 294 public static AccountManager get(Context context) { 295 if (context == null) throw new IllegalArgumentException("context is null"); 296 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); 297 } 298 299 /** 300 * Gets the saved password associated with the account. 301 * This is intended for authenticators and related code; applications 302 * should get an auth token instead. 303 * 304 * <p>It is safe to call this method from the main thread. 305 * 306 * <p>This method requires the caller to hold the permission 307 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 308 * and to have the same UID as the account's authenticator. 309 * 310 * @param account The account to query for a password 311 * @return The account's password, null if none or if the account doesn't exist 312 */ 313 public String getPassword(final Account account) { 314 if (account == null) throw new IllegalArgumentException("account is null"); 315 try { 316 return mService.getPassword(account); 317 } catch (RemoteException e) { 318 // will never happen 319 throw new RuntimeException(e); 320 } 321 } 322 323 /** 324 * Gets the user data named by "key" associated with the account. 325 * This is intended for authenticators and related code to store 326 * arbitrary metadata along with accounts. The meaning of the keys 327 * and values is up to the authenticator for the account. 328 * 329 * <p>It is safe to call this method from the main thread. 330 * 331 * <p>This method requires the caller to hold the permission 332 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 333 * and to have the same UID as the account's authenticator. 334 * 335 * @param account The account to query for user data 336 * @return The user data, null if the account or key doesn't exist 337 */ 338 public String getUserData(final Account account, final String key) { 339 if (account == null) throw new IllegalArgumentException("account is null"); 340 if (key == null) throw new IllegalArgumentException("key is null"); 341 try { 342 return mService.getUserData(account, key); 343 } catch (RemoteException e) { 344 // will never happen 345 throw new RuntimeException(e); 346 } 347 } 348 349 /** 350 * Lists the currently registered authenticators. 351 * 352 * <p>It is safe to call this method from the main thread. 353 * 354 * <p>No permission is required to call this method. 355 * 356 * @return An array of {@link AuthenticatorDescription} for every 357 * authenticator known to the AccountManager service. Empty (never 358 * null) if no authenticators are known. 359 */ 360 public AuthenticatorDescription[] getAuthenticatorTypes() { 361 try { 362 return mService.getAuthenticatorTypes(); 363 } catch (RemoteException e) { 364 // will never happen 365 throw new RuntimeException(e); 366 } 367 } 368 369 /** 370 * Lists all accounts of any type registered on the device. 371 * Equivalent to getAccountsByType(null). 372 * 373 * <p>It is safe to call this method from the main thread. 374 * 375 * <p>This method requires the caller to hold the permission 376 * {@link android.Manifest.permission#GET_ACCOUNTS}. 377 * 378 * @return An array of {@link Account}, one for each account. Empty 379 * (never null) if no accounts have been added. 380 */ 381 public Account[] getAccounts() { 382 try { 383 return mService.getAccounts(null); 384 } catch (RemoteException e) { 385 // won't ever happen 386 throw new RuntimeException(e); 387 } 388 } 389 390 /** 391 * Lists all accounts of a particular type. The account type is a 392 * string token corresponding to the authenticator and useful domain 393 * of the account. For example, there are types corresponding to Google 394 * and Facebook. The exact string token to use will be published somewhere 395 * associated with the authenticator in question. 396 * 397 * <p>It is safe to call this method from the main thread. 398 * 399 * <p>This method requires the caller to hold the permission 400 * {@link android.Manifest.permission#GET_ACCOUNTS}. 401 * 402 * @param type The type of accounts to return, null to retrieve all accounts 403 * @return An array of {@link Account}, one per matching account. Empty 404 * (never null) if no accounts of the specified type have been added. 405 */ 406 public Account[] getAccountsByType(String type) { 407 return getAccountsByTypeAsUser(type, Process.myUserHandle()); 408 } 409 410 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */ 411 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) { 412 try { 413 return mService.getAccountsAsUser(type, userHandle.getIdentifier()); 414 } catch (RemoteException e) { 415 // won't ever happen 416 throw new RuntimeException(e); 417 } 418 } 419 420 /** 421 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken 422 * for an account. 423 * <p> 424 * This is only meant to be used by system activities and is not in the SDK. 425 * @param account The account whose permissions are being modified 426 * @param authTokenType The type of token whose permissions are being modified 427 * @param uid The uid that identifies the app which is being granted or revoked permission. 428 * @param value true is permission is being granted, false for revoked 429 * @hide 430 */ 431 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) { 432 try { 433 mService.updateAppPermission(account, authTokenType, uid, value); 434 } catch (RemoteException e) { 435 // won't ever happen 436 throw new RuntimeException(e); 437 } 438 } 439 440 /** 441 * Get the user-friendly label associated with an authenticator's auth token. 442 * @param accountType the type of the authenticator. must not be null. 443 * @param authTokenType the token type. must not be null. 444 * @param callback callback to invoke when the result is available. may be null. 445 * @param handler the handler on which to invoke the callback, or null for the main thread 446 * @return a future containing the label string 447 * @hide 448 */ 449 public AccountManagerFuture<String> getAuthTokenLabel( 450 final String accountType, final String authTokenType, 451 AccountManagerCallback<String> callback, Handler handler) { 452 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 453 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 454 return new Future2Task<String>(handler, callback) { 455 public void doWork() throws RemoteException { 456 mService.getAuthTokenLabel(mResponse, accountType, authTokenType); 457 } 458 459 @Override 460 public String bundleToResult(Bundle bundle) throws AuthenticatorException { 461 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) { 462 throw new AuthenticatorException("no result in response"); 463 } 464 return bundle.getString(KEY_AUTH_TOKEN_LABEL); 465 } 466 }.start(); 467 } 468 469 /** 470 * Finds out whether a particular account has all the specified features. 471 * Account features are authenticator-specific string tokens identifying 472 * boolean account properties. For example, features are used to tell 473 * whether Google accounts have a particular service (such as Google 474 * Calendar or Google Talk) enabled. The feature names and their meanings 475 * are published somewhere associated with the authenticator in question. 476 * 477 * <p>This method may be called from any thread, but the returned 478 * {@link AccountManagerFuture} must not be used on the main thread. 479 * 480 * <p>This method requires the caller to hold the permission 481 * {@link android.Manifest.permission#GET_ACCOUNTS}. 482 * 483 * @param account The {@link Account} to test 484 * @param features An array of the account features to check 485 * @param callback Callback to invoke when the request completes, 486 * null for no callback 487 * @param handler {@link Handler} identifying the callback thread, 488 * null for the main thread 489 * @return An {@link AccountManagerFuture} which resolves to a Boolean, 490 * true if the account exists and has all of the specified features. 491 */ 492 public AccountManagerFuture<Boolean> hasFeatures(final Account account, 493 final String[] features, 494 AccountManagerCallback<Boolean> callback, Handler handler) { 495 if (account == null) throw new IllegalArgumentException("account is null"); 496 if (features == null) throw new IllegalArgumentException("features is null"); 497 return new Future2Task<Boolean>(handler, callback) { 498 public void doWork() throws RemoteException { 499 mService.hasFeatures(mResponse, account, features); 500 } 501 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 502 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 503 throw new AuthenticatorException("no result in response"); 504 } 505 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 506 } 507 }.start(); 508 } 509 510 /** 511 * Lists all accounts of a type which have certain features. The account 512 * type identifies the authenticator (see {@link #getAccountsByType}). 513 * Account features are authenticator-specific string tokens identifying 514 * boolean account properties (see {@link #hasFeatures}). 515 * 516 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator, 517 * which may contact the server or do other work to check account features, 518 * so the method returns an {@link AccountManagerFuture}. 519 * 520 * <p>This method may be called from any thread, but the returned 521 * {@link AccountManagerFuture} must not be used on the main thread. 522 * 523 * <p>This method requires the caller to hold the permission 524 * {@link android.Manifest.permission#GET_ACCOUNTS}. 525 * 526 * @param type The type of accounts to return, must not be null 527 * @param features An array of the account features to require, 528 * may be null or empty 529 * @param callback Callback to invoke when the request completes, 530 * null for no callback 531 * @param handler {@link Handler} identifying the callback thread, 532 * null for the main thread 533 * @return An {@link AccountManagerFuture} which resolves to an array of 534 * {@link Account}, one per account of the specified type which 535 * matches the requested features. 536 */ 537 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures( 538 final String type, final String[] features, 539 AccountManagerCallback<Account[]> callback, Handler handler) { 540 if (type == null) throw new IllegalArgumentException("type is null"); 541 return new Future2Task<Account[]>(handler, callback) { 542 public void doWork() throws RemoteException { 543 mService.getAccountsByFeatures(mResponse, type, features); 544 } 545 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException { 546 if (!bundle.containsKey(KEY_ACCOUNTS)) { 547 throw new AuthenticatorException("no result in response"); 548 } 549 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS); 550 Account[] descs = new Account[parcelables.length]; 551 for (int i = 0; i < parcelables.length; i++) { 552 descs[i] = (Account) parcelables[i]; 553 } 554 return descs; 555 } 556 }.start(); 557 } 558 559 /** 560 * Adds an account directly to the AccountManager. Normally used by sign-up 561 * wizards associated with authenticators, not directly by applications. 562 * 563 * <p>It is safe to call this method from the main thread. 564 * 565 * <p>This method requires the caller to hold the permission 566 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 567 * and to have the same UID as the added account's authenticator. 568 * 569 * @param account The {@link Account} to add 570 * @param password The password to associate with the account, null for none 571 * @param userdata String values to use for the account's userdata, null for none 572 * @return True if the account was successfully added, false if the account 573 * already exists, the account is null, or another error occurs. 574 */ 575 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) { 576 if (account == null) throw new IllegalArgumentException("account is null"); 577 try { 578 return mService.addAccount(account, password, userdata); 579 } catch (RemoteException e) { 580 // won't ever happen 581 throw new RuntimeException(e); 582 } 583 } 584 585 /** 586 * Removes an account from the AccountManager. Does nothing if the account 587 * does not exist. Does not delete the account from the server. 588 * The authenticator may have its own policies preventing account 589 * deletion, in which case the account will not be deleted. 590 * 591 * <p>This method may be called from any thread, but the returned 592 * {@link AccountManagerFuture} must not be used on the main thread. 593 * 594 * <p>This method requires the caller to hold the permission 595 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 596 * 597 * @param account The {@link Account} to remove 598 * @param callback Callback to invoke when the request completes, 599 * null for no callback 600 * @param handler {@link Handler} identifying the callback thread, 601 * null for the main thread 602 * @return An {@link AccountManagerFuture} which resolves to a Boolean, 603 * true if the account has been successfully removed, 604 * false if the authenticator forbids deleting this account. 605 */ 606 public AccountManagerFuture<Boolean> removeAccount(final Account account, 607 AccountManagerCallback<Boolean> callback, Handler handler) { 608 if (account == null) throw new IllegalArgumentException("account is null"); 609 return new Future2Task<Boolean>(handler, callback) { 610 public void doWork() throws RemoteException { 611 mService.removeAccount(mResponse, account); 612 } 613 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 614 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 615 throw new AuthenticatorException("no result in response"); 616 } 617 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 618 } 619 }.start(); 620 } 621 622 /** 623 * Removes an auth token from the AccountManager's cache. Does nothing if 624 * the auth token is not currently in the cache. Applications must call this 625 * method when the auth token is found to have expired or otherwise become 626 * invalid for authenticating requests. The AccountManager does not validate 627 * or expire cached auth tokens otherwise. 628 * 629 * <p>It is safe to call this method from the main thread. 630 * 631 * <p>This method requires the caller to hold the permission 632 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or 633 * {@link android.Manifest.permission#USE_CREDENTIALS} 634 * 635 * @param accountType The account type of the auth token to invalidate, must not be null 636 * @param authToken The auth token to invalidate, may be null 637 */ 638 public void invalidateAuthToken(final String accountType, final String authToken) { 639 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 640 try { 641 if (authToken != null) { 642 mService.invalidateAuthToken(accountType, authToken); 643 } 644 } catch (RemoteException e) { 645 // won't ever happen 646 throw new RuntimeException(e); 647 } 648 } 649 650 /** 651 * Gets an auth token from the AccountManager's cache. If no auth 652 * token is cached for this account, null will be returned -- a new 653 * auth token will not be generated, and the server will not be contacted. 654 * Intended for use by the authenticator, not directly by applications. 655 * 656 * <p>It is safe to call this method from the main thread. 657 * 658 * <p>This method requires the caller to hold the permission 659 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 660 * and to have the same UID as the account's authenticator. 661 * 662 * @param account The account to fetch an auth token for 663 * @param authTokenType The type of auth token to fetch, see {#getAuthToken} 664 * @return The cached auth token for this account and type, or null if 665 * no auth token is cached or the account does not exist. 666 */ 667 public String peekAuthToken(final Account account, final String authTokenType) { 668 if (account == null) throw new IllegalArgumentException("account is null"); 669 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 670 try { 671 return mService.peekAuthToken(account, authTokenType); 672 } catch (RemoteException e) { 673 // won't ever happen 674 throw new RuntimeException(e); 675 } 676 } 677 678 /** 679 * Sets or forgets a saved password. This modifies the local copy of the 680 * password used to automatically authenticate the user; it does 681 * not change the user's account password on the server. Intended for use 682 * by the authenticator, not directly by applications. 683 * 684 * <p>It is safe to call this method from the main thread. 685 * 686 * <p>This method requires the caller to hold the permission 687 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 688 * and have the same UID as the account's authenticator. 689 * 690 * @param account The account to set a password for 691 * @param password The password to set, null to clear the password 692 */ 693 public void setPassword(final Account account, final String password) { 694 if (account == null) throw new IllegalArgumentException("account is null"); 695 try { 696 mService.setPassword(account, password); 697 } catch (RemoteException e) { 698 // won't ever happen 699 throw new RuntimeException(e); 700 } 701 } 702 703 /** 704 * Forgets a saved password. This erases the local copy of the password; 705 * it does not change the user's account password on the server. 706 * Has the same effect as setPassword(account, null) but requires fewer 707 * permissions, and may be used by applications or management interfaces 708 * to "sign out" from an account. 709 * 710 * <p>It is safe to call this method from the main thread. 711 * 712 * <p>This method requires the caller to hold the permission 713 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} 714 * 715 * @param account The account whose password to clear 716 */ 717 public void clearPassword(final Account account) { 718 if (account == null) throw new IllegalArgumentException("account is null"); 719 try { 720 mService.clearPassword(account); 721 } catch (RemoteException e) { 722 // won't ever happen 723 throw new RuntimeException(e); 724 } 725 } 726 727 /** 728 * Sets one userdata key for an account. Intended by use for the 729 * authenticator to stash state for itself, not directly by applications. 730 * The meaning of the keys and values is up to the authenticator. 731 * 732 * <p>It is safe to call this method from the main thread. 733 * 734 * <p>This method requires the caller to hold the permission 735 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 736 * and to have the same UID as the account's authenticator. 737 * 738 * @param account The account to set the userdata for 739 * @param key The userdata key to set. Must not be null 740 * @param value The value to set, null to clear this userdata key 741 */ 742 public void setUserData(final Account account, final String key, final String value) { 743 if (account == null) throw new IllegalArgumentException("account is null"); 744 if (key == null) throw new IllegalArgumentException("key is null"); 745 try { 746 mService.setUserData(account, key, value); 747 } catch (RemoteException e) { 748 // won't ever happen 749 throw new RuntimeException(e); 750 } 751 } 752 753 /** 754 * Adds an auth token to the AccountManager cache for an account. 755 * If the account does not exist then this call has no effect. 756 * Replaces any previous auth token for this account and auth token type. 757 * Intended for use by the authenticator, not directly by applications. 758 * 759 * <p>It is safe to call this method from the main thread. 760 * 761 * <p>This method requires the caller to hold the permission 762 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} 763 * and to have the same UID as the account's authenticator. 764 * 765 * @param account The account to set an auth token for 766 * @param authTokenType The type of the auth token, see {#getAuthToken} 767 * @param authToken The auth token to add to the cache 768 */ 769 public void setAuthToken(Account account, final String authTokenType, final String authToken) { 770 if (account == null) throw new IllegalArgumentException("account is null"); 771 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 772 try { 773 mService.setAuthToken(account, authTokenType, authToken); 774 } catch (RemoteException e) { 775 // won't ever happen 776 throw new RuntimeException(e); 777 } 778 } 779 780 /** 781 * This convenience helper synchronously gets an auth token with 782 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}. 783 * 784 * <p>This method may block while a network request completes, and must 785 * never be made from the main thread. 786 * 787 * <p>This method requires the caller to hold the permission 788 * {@link android.Manifest.permission#USE_CREDENTIALS}. 789 * 790 * @param account The account to fetch an auth token for 791 * @param authTokenType The auth token type, see {#link getAuthToken} 792 * @param notifyAuthFailure If true, display a notification and return null 793 * if authentication fails; if false, prompt and wait for the user to 794 * re-enter correct credentials before returning 795 * @return An auth token of the specified type for this account, or null 796 * if authentication fails or none can be fetched. 797 * @throws AuthenticatorException if the authenticator failed to respond 798 * @throws OperationCanceledException if the request was canceled for any 799 * reason, including the user canceling a credential request 800 * @throws java.io.IOException if the authenticator experienced an I/O problem 801 * creating a new auth token, usually because of network trouble 802 */ 803 public String blockingGetAuthToken(Account account, String authTokenType, 804 boolean notifyAuthFailure) 805 throws OperationCanceledException, IOException, AuthenticatorException { 806 if (account == null) throw new IllegalArgumentException("account is null"); 807 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 808 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */, 809 null /* handler */).getResult(); 810 if (bundle == null) { 811 // This should never happen, but it does, occasionally. If it does return null to 812 // signify that we were not able to get the authtoken. 813 // TODO: remove this when the bug is found that sometimes causes a null bundle to be 814 // returned 815 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for " 816 + account + ", authTokenType " + authTokenType); 817 return null; 818 } 819 return bundle.getString(KEY_AUTHTOKEN); 820 } 821 822 /** 823 * Gets an auth token of the specified type for a particular account, 824 * prompting the user for credentials if necessary. This method is 825 * intended for applications running in the foreground where it makes 826 * sense to ask the user directly for a password. 827 * 828 * <p>If a previously generated auth token is cached for this account and 829 * type, then it is returned. Otherwise, if a saved password is 830 * available, it is sent to the server to generate a new auth token. 831 * Otherwise, the user is prompted to enter a password. 832 * 833 * <p>Some authenticators have auth token <em>types</em>, whose value 834 * is authenticator-dependent. Some services use different token types to 835 * access different functionality -- for example, Google uses different auth 836 * tokens to access Gmail and Google Calendar for the same account. 837 * 838 * <p>This method may be called from any thread, but the returned 839 * {@link AccountManagerFuture} must not be used on the main thread. 840 * 841 * <p>This method requires the caller to hold the permission 842 * {@link android.Manifest.permission#USE_CREDENTIALS}. 843 * 844 * @param account The account to fetch an auth token for 845 * @param authTokenType The auth token type, an authenticator-dependent 846 * string token, must not be null 847 * @param options Authenticator-specific options for the request, 848 * may be null or empty 849 * @param activity The {@link Activity} context to use for launching a new 850 * authenticator-defined sub-Activity to prompt the user for a password 851 * if necessary; used only to call startActivity(); must not be null. 852 * @param callback Callback to invoke when the request completes, 853 * null for no callback 854 * @param handler {@link Handler} identifying the callback thread, 855 * null for the main thread 856 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 857 * at least the following fields: 858 * <ul> 859 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 860 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 861 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 862 * </ul> 863 * 864 * (Other authenticator-specific values may be returned.) If an auth token 865 * could not be fetched, {@link AccountManagerFuture#getResult()} throws: 866 * <ul> 867 * <li> {@link AuthenticatorException} if the authenticator failed to respond 868 * <li> {@link OperationCanceledException} if the operation is canceled for 869 * any reason, incluidng the user canceling a credential request 870 * <li> {@link IOException} if the authenticator experienced an I/O problem 871 * creating a new auth token, usually because of network trouble 872 * </ul> 873 * If the account is no longer present on the device, the return value is 874 * authenticator-dependent. The caller should verify the validity of the 875 * account before requesting an auth token. 876 */ 877 public AccountManagerFuture<Bundle> getAuthToken( 878 final Account account, final String authTokenType, final Bundle options, 879 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { 880 if (account == null) throw new IllegalArgumentException("account is null"); 881 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 882 final Bundle optionsIn = new Bundle(); 883 if (options != null) { 884 optionsIn.putAll(options); 885 } 886 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 887 return new AmsTask(activity, handler, callback) { 888 public void doWork() throws RemoteException { 889 mService.getAuthToken(mResponse, account, authTokenType, 890 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */, 891 optionsIn); 892 } 893 }.start(); 894 } 895 896 /** 897 * Gets an auth token of the specified type for a particular account, 898 * optionally raising a notification if the user must enter credentials. 899 * This method is intended for background tasks and services where the 900 * user should not be immediately interrupted with a password prompt. 901 * 902 * <p>If a previously generated auth token is cached for this account and 903 * type, then it is returned. Otherwise, if a saved password is 904 * available, it is sent to the server to generate a new auth token. 905 * Otherwise, an {@link Intent} is returned which, when started, will 906 * prompt the user for a password. If the notifyAuthFailure parameter is 907 * set, a status bar notification is also created with the same Intent, 908 * alerting the user that they need to enter a password at some point. 909 * 910 * <p>In that case, you may need to wait until the user responds, which 911 * could take hours or days or forever. When the user does respond and 912 * supply a new password, the account manager will broadcast the 913 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can 914 * use to try again. 915 * 916 * <p>If notifyAuthFailure is not set, it is the application's 917 * responsibility to launch the returned Intent at some point. 918 * Either way, the result from this call will not wait for user action. 919 * 920 * <p>Some authenticators have auth token <em>types</em>, whose value 921 * is authenticator-dependent. Some services use different token types to 922 * access different functionality -- for example, Google uses different auth 923 * tokens to access Gmail and Google Calendar for the same account. 924 * 925 * <p>This method may be called from any thread, but the returned 926 * {@link AccountManagerFuture} must not be used on the main thread. 927 * 928 * <p>This method requires the caller to hold the permission 929 * {@link android.Manifest.permission#USE_CREDENTIALS}. 930 * 931 * @param account The account to fetch an auth token for 932 * @param authTokenType The auth token type, an authenticator-dependent 933 * string token, must not be null 934 * @param notifyAuthFailure True to add a notification to prompt the 935 * user for a password if necessary, false to leave that to the caller 936 * @param callback Callback to invoke when the request completes, 937 * null for no callback 938 * @param handler {@link Handler} identifying the callback thread, 939 * null for the main thread 940 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 941 * at least the following fields on success: 942 * <ul> 943 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 944 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 945 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 946 * </ul> 947 * 948 * (Other authenticator-specific values may be returned.) If the user 949 * must enter credentials, the returned Bundle contains only 950 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt. 951 * 952 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 953 * <ul> 954 * <li> {@link AuthenticatorException} if the authenticator failed to respond 955 * <li> {@link OperationCanceledException} if the operation is canceled for 956 * any reason, incluidng the user canceling a credential request 957 * <li> {@link IOException} if the authenticator experienced an I/O problem 958 * creating a new auth token, usually because of network trouble 959 * </ul> 960 * If the account is no longer present on the device, the return value is 961 * authenticator-dependent. The caller should verify the validity of the 962 * account before requesting an auth token. 963 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle, 964 * boolean, AccountManagerCallback, android.os.Handler)} instead 965 */ 966 @Deprecated 967 public AccountManagerFuture<Bundle> getAuthToken( 968 final Account account, final String authTokenType, 969 final boolean notifyAuthFailure, 970 AccountManagerCallback<Bundle> callback, Handler handler) { 971 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback, 972 handler); 973 } 974 975 /** 976 * Gets an auth token of the specified type for a particular account, 977 * optionally raising a notification if the user must enter credentials. 978 * This method is intended for background tasks and services where the 979 * user should not be immediately interrupted with a password prompt. 980 * 981 * <p>If a previously generated auth token is cached for this account and 982 * type, then it is returned. Otherwise, if a saved password is 983 * available, it is sent to the server to generate a new auth token. 984 * Otherwise, an {@link Intent} is returned which, when started, will 985 * prompt the user for a password. If the notifyAuthFailure parameter is 986 * set, a status bar notification is also created with the same Intent, 987 * alerting the user that they need to enter a password at some point. 988 * 989 * <p>In that case, you may need to wait until the user responds, which 990 * could take hours or days or forever. When the user does respond and 991 * supply a new password, the account manager will broadcast the 992 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can 993 * use to try again. 994 * 995 * <p>If notifyAuthFailure is not set, it is the application's 996 * responsibility to launch the returned Intent at some point. 997 * Either way, the result from this call will not wait for user action. 998 * 999 * <p>Some authenticators have auth token <em>types</em>, whose value 1000 * is authenticator-dependent. Some services use different token types to 1001 * access different functionality -- for example, Google uses different auth 1002 * tokens to access Gmail and Google Calendar for the same account. 1003 * 1004 * <p>This method may be called from any thread, but the returned 1005 * {@link AccountManagerFuture} must not be used on the main thread. 1006 * 1007 * <p>This method requires the caller to hold the permission 1008 * {@link android.Manifest.permission#USE_CREDENTIALS}. 1009 * 1010 * @param account The account to fetch an auth token for 1011 * @param authTokenType The auth token type, an authenticator-dependent 1012 * string token, must not be null 1013 * @param options Authenticator-specific options for the request, 1014 * may be null or empty 1015 * @param notifyAuthFailure True to add a notification to prompt the 1016 * user for a password if necessary, false to leave that to the caller 1017 * @param callback Callback to invoke when the request completes, 1018 * null for no callback 1019 * @param handler {@link Handler} identifying the callback thread, 1020 * null for the main thread 1021 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1022 * at least the following fields on success: 1023 * <ul> 1024 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 1025 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1026 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 1027 * </ul> 1028 * 1029 * (Other authenticator-specific values may be returned.) If the user 1030 * must enter credentials, the returned Bundle contains only 1031 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt. 1032 * 1033 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 1034 * <ul> 1035 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1036 * <li> {@link OperationCanceledException} if the operation is canceled for 1037 * any reason, incluidng the user canceling a credential request 1038 * <li> {@link IOException} if the authenticator experienced an I/O problem 1039 * creating a new auth token, usually because of network trouble 1040 * </ul> 1041 * If the account is no longer present on the device, the return value is 1042 * authenticator-dependent. The caller should verify the validity of the 1043 * account before requesting an auth token. 1044 */ 1045 public AccountManagerFuture<Bundle> getAuthToken( 1046 final Account account, final String authTokenType, final Bundle options, 1047 final boolean notifyAuthFailure, 1048 AccountManagerCallback<Bundle> callback, Handler handler) { 1049 1050 if (account == null) throw new IllegalArgumentException("account is null"); 1051 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1052 final Bundle optionsIn = new Bundle(); 1053 if (options != null) { 1054 optionsIn.putAll(options); 1055 } 1056 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1057 return new AmsTask(null, handler, callback) { 1058 public void doWork() throws RemoteException { 1059 mService.getAuthToken(mResponse, account, authTokenType, 1060 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn); 1061 } 1062 }.start(); 1063 } 1064 1065 /** 1066 * Asks the user to add an account of a specified type. The authenticator 1067 * for this account type processes this request with the appropriate user 1068 * interface. If the user does elect to create a new account, the account 1069 * name is returned. 1070 * 1071 * <p>This method may be called from any thread, but the returned 1072 * {@link AccountManagerFuture} must not be used on the main thread. 1073 * 1074 * <p>This method requires the caller to hold the permission 1075 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1076 * 1077 * @param accountType The type of account to add; must not be null 1078 * @param authTokenType The type of auth token (see {@link #getAuthToken}) 1079 * this account will need to be able to generate, null for none 1080 * @param requiredFeatures The features (see {@link #hasFeatures}) this 1081 * account must have, null for none 1082 * @param addAccountOptions Authenticator-specific options for the request, 1083 * may be null or empty 1084 * @param activity The {@link Activity} context to use for launching a new 1085 * authenticator-defined sub-Activity to prompt the user to create an 1086 * account; used only to call startActivity(); if null, the prompt 1087 * will not be launched directly, but the necessary {@link Intent} 1088 * will be returned to the caller instead 1089 * @param callback Callback to invoke when the request completes, 1090 * null for no callback 1091 * @param handler {@link Handler} identifying the callback thread, 1092 * null for the main thread 1093 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1094 * these fields if activity was specified and an account was created: 1095 * <ul> 1096 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1097 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1098 * </ul> 1099 * 1100 * If no activity was specified, the returned Bundle contains only 1101 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1102 * actual account creation process. If an error occurred, 1103 * {@link AccountManagerFuture#getResult()} throws: 1104 * <ul> 1105 * <li> {@link AuthenticatorException} if no authenticator was registered for 1106 * this account type or the authenticator failed to respond 1107 * <li> {@link OperationCanceledException} if the operation was canceled for 1108 * any reason, including the user canceling the creation process 1109 * <li> {@link IOException} if the authenticator experienced an I/O problem 1110 * creating a new account, usually because of network trouble 1111 * </ul> 1112 */ 1113 public AccountManagerFuture<Bundle> addAccount(final String accountType, 1114 final String authTokenType, final String[] requiredFeatures, 1115 final Bundle addAccountOptions, 1116 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { 1117 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1118 final Bundle optionsIn = new Bundle(); 1119 if (addAccountOptions != null) { 1120 optionsIn.putAll(addAccountOptions); 1121 } 1122 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1123 1124 return new AmsTask(activity, handler, callback) { 1125 public void doWork() throws RemoteException { 1126 mService.addAcount(mResponse, accountType, authTokenType, 1127 requiredFeatures, activity != null, optionsIn); 1128 } 1129 }.start(); 1130 } 1131 1132 /** 1133 * Adds a shared account from the primary user to a secondary user. Adding the shared account 1134 * doesn't take effect immediately. When the target user starts up, any pending shared accounts 1135 * are attempted to be copied to the target user from the primary via calls to the 1136 * authenticator. 1137 * @param account the account to share 1138 * @param user the target user 1139 * @return 1140 * @hide 1141 */ 1142 public boolean addSharedAccount(final Account account, UserHandle user) { 1143 try { 1144 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier()); 1145 return val; 1146 } catch (RemoteException re) { 1147 // won't ever happen 1148 throw new RuntimeException(re); 1149 } 1150 } 1151 1152 /** 1153 * @hide 1154 * Removes the shared account. 1155 * @param account the account to remove 1156 * @param user the user to remove the account from 1157 * @return 1158 */ 1159 public boolean removeSharedAccount(final Account account, UserHandle user) { 1160 try { 1161 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier()); 1162 return val; 1163 } catch (RemoteException re) { 1164 // won't ever happen 1165 throw new RuntimeException(re); 1166 } 1167 } 1168 1169 /** 1170 * @hide 1171 * @param user 1172 * @return 1173 */ 1174 public Account[] getSharedAccounts(UserHandle user) { 1175 try { 1176 return mService.getSharedAccountsAsUser(user.getIdentifier()); 1177 } catch (RemoteException re) { 1178 // won't ever happen 1179 throw new RuntimeException(re); 1180 } 1181 } 1182 1183 /** 1184 * Confirms that the user knows the password for an account to make extra 1185 * sure they are the owner of the account. The user-entered password can 1186 * be supplied directly, otherwise the authenticator for this account type 1187 * prompts the user with the appropriate interface. This method is 1188 * intended for applications which want extra assurance; for example, the 1189 * phone lock screen uses this to let the user unlock the phone with an 1190 * account password if they forget the lock pattern. 1191 * 1192 * <p>If the user-entered password matches a saved password for this 1193 * account, the request is considered valid; otherwise the authenticator 1194 * verifies the password (usually by contacting the server). 1195 * 1196 * <p>This method may be called from any thread, but the returned 1197 * {@link AccountManagerFuture} must not be used on the main thread. 1198 * 1199 * <p>This method requires the caller to hold the permission 1200 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1201 * 1202 * @param account The account to confirm password knowledge for 1203 * @param options Authenticator-specific options for the request; 1204 * if the {@link #KEY_PASSWORD} string field is present, the 1205 * authenticator may use it directly rather than prompting the user; 1206 * may be null or empty 1207 * @param activity The {@link Activity} context to use for launching a new 1208 * authenticator-defined sub-Activity to prompt the user to enter a 1209 * password; used only to call startActivity(); if null, the prompt 1210 * will not be launched directly, but the necessary {@link Intent} 1211 * will be returned to the caller instead 1212 * @param callback Callback to invoke when the request completes, 1213 * null for no callback 1214 * @param handler {@link Handler} identifying the callback thread, 1215 * null for the main thread 1216 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1217 * with these fields if activity or password was supplied and 1218 * the account was successfully verified: 1219 * <ul> 1220 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1221 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1222 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success 1223 * </ul> 1224 * 1225 * If no activity or password was specified, the returned Bundle contains 1226 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1227 * password prompt. If an error occurred, 1228 * {@link AccountManagerFuture#getResult()} throws: 1229 * <ul> 1230 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1231 * <li> {@link OperationCanceledException} if the operation was canceled for 1232 * any reason, including the user canceling the password prompt 1233 * <li> {@link IOException} if the authenticator experienced an I/O problem 1234 * verifying the password, usually because of network trouble 1235 * </ul> 1236 */ 1237 public AccountManagerFuture<Bundle> confirmCredentials(final Account account, 1238 final Bundle options, 1239 final Activity activity, 1240 final AccountManagerCallback<Bundle> callback, 1241 final Handler handler) { 1242 return confirmCredentialsAsUser(account, options, activity, callback, handler, 1243 Process.myUserHandle()); 1244 } 1245 1246 /** 1247 * @hide 1248 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)} 1249 * but for the specified user. 1250 */ 1251 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account, 1252 final Bundle options, 1253 final Activity activity, 1254 final AccountManagerCallback<Bundle> callback, 1255 final Handler handler, UserHandle userHandle) { 1256 if (account == null) throw new IllegalArgumentException("account is null"); 1257 final int userId = userHandle.getIdentifier(); 1258 return new AmsTask(activity, handler, callback) { 1259 public void doWork() throws RemoteException { 1260 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null, 1261 userId); 1262 } 1263 }.start(); 1264 } 1265 1266 /** 1267 * Asks the user to enter a new password for an account, updating the 1268 * saved credentials for the account. Normally this happens automatically 1269 * when the server rejects credentials during an auth token fetch, but this 1270 * can be invoked directly to ensure we have the correct credentials stored. 1271 * 1272 * <p>This method may be called from any thread, but the returned 1273 * {@link AccountManagerFuture} must not be used on the main thread. 1274 * 1275 * <p>This method requires the caller to hold the permission 1276 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1277 * 1278 * @param account The account to update credentials for 1279 * @param authTokenType The credentials entered must allow an auth token 1280 * of this type to be created (but no actual auth token is returned); 1281 * may be null 1282 * @param options Authenticator-specific options for the request; 1283 * may be null or empty 1284 * @param activity The {@link Activity} context to use for launching a new 1285 * authenticator-defined sub-Activity to prompt the user to enter a 1286 * password; used only to call startActivity(); if null, the prompt 1287 * will not be launched directly, but the necessary {@link Intent} 1288 * will be returned to the caller instead 1289 * @param callback Callback to invoke when the request completes, 1290 * null for no callback 1291 * @param handler {@link Handler} identifying the callback thread, 1292 * null for the main thread 1293 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1294 * with these fields if an activity was supplied and the account 1295 * credentials were successfully updated: 1296 * <ul> 1297 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1298 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1299 * </ul> 1300 * 1301 * If no activity was specified, the returned Bundle contains only 1302 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1303 * password prompt. If an error occurred, 1304 * {@link AccountManagerFuture#getResult()} throws: 1305 * <ul> 1306 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1307 * <li> {@link OperationCanceledException} if the operation was canceled for 1308 * any reason, including the user canceling the password prompt 1309 * <li> {@link IOException} if the authenticator experienced an I/O problem 1310 * verifying the password, usually because of network trouble 1311 * </ul> 1312 */ 1313 public AccountManagerFuture<Bundle> updateCredentials(final Account account, 1314 final String authTokenType, 1315 final Bundle options, final Activity activity, 1316 final AccountManagerCallback<Bundle> callback, 1317 final Handler handler) { 1318 if (account == null) throw new IllegalArgumentException("account is null"); 1319 return new AmsTask(activity, handler, callback) { 1320 public void doWork() throws RemoteException { 1321 mService.updateCredentials(mResponse, account, authTokenType, activity != null, 1322 options); 1323 } 1324 }.start(); 1325 } 1326 1327 /** 1328 * Offers the user an opportunity to change an authenticator's settings. 1329 * These properties are for the authenticator in general, not a particular 1330 * account. Not all authenticators support this method. 1331 * 1332 * <p>This method may be called from any thread, but the returned 1333 * {@link AccountManagerFuture} must not be used on the main thread. 1334 * 1335 * <p>This method requires the caller to hold the permission 1336 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1337 * 1338 * @param accountType The account type associated with the authenticator 1339 * to adjust 1340 * @param activity The {@link Activity} context to use for launching a new 1341 * authenticator-defined sub-Activity to adjust authenticator settings; 1342 * used only to call startActivity(); if null, the settings dialog will 1343 * not be launched directly, but the necessary {@link Intent} will be 1344 * returned to the caller instead 1345 * @param callback Callback to invoke when the request completes, 1346 * null for no callback 1347 * @param handler {@link Handler} identifying the callback thread, 1348 * null for the main thread 1349 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1350 * which is empty if properties were edited successfully, or 1351 * if no activity was specified, contains only {@link #KEY_INTENT} 1352 * needed to launch the authenticator's settings dialog. 1353 * If an error occurred, {@link AccountManagerFuture#getResult()} 1354 * throws: 1355 * <ul> 1356 * <li> {@link AuthenticatorException} if no authenticator was registered for 1357 * this account type or the authenticator failed to respond 1358 * <li> {@link OperationCanceledException} if the operation was canceled for 1359 * any reason, including the user canceling the settings dialog 1360 * <li> {@link IOException} if the authenticator experienced an I/O problem 1361 * updating settings, usually because of network trouble 1362 * </ul> 1363 */ 1364 public AccountManagerFuture<Bundle> editProperties(final String accountType, 1365 final Activity activity, final AccountManagerCallback<Bundle> callback, 1366 final Handler handler) { 1367 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1368 return new AmsTask(activity, handler, callback) { 1369 public void doWork() throws RemoteException { 1370 mService.editProperties(mResponse, accountType, activity != null); 1371 } 1372 }.start(); 1373 } 1374 1375 private void ensureNotOnMainThread() { 1376 final Looper looper = Looper.myLooper(); 1377 if (looper != null && looper == mContext.getMainLooper()) { 1378 final IllegalStateException exception = new IllegalStateException( 1379 "calling this from your main thread can lead to deadlock"); 1380 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs", 1381 exception); 1382 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) { 1383 throw exception; 1384 } 1385 } 1386 } 1387 1388 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback, 1389 final AccountManagerFuture<Bundle> future) { 1390 handler = handler == null ? mMainHandler : handler; 1391 handler.post(new Runnable() { 1392 public void run() { 1393 callback.run(future); 1394 } 1395 }); 1396 } 1397 1398 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener, 1399 final Account[] accounts) { 1400 final Account[] accountsCopy = new Account[accounts.length]; 1401 // send a copy to make sure that one doesn't 1402 // change what another sees 1403 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length); 1404 handler = (handler == null) ? mMainHandler : handler; 1405 handler.post(new Runnable() { 1406 public void run() { 1407 try { 1408 listener.onAccountsUpdated(accountsCopy); 1409 } catch (SQLException e) { 1410 // Better luck next time. If the problem was disk-full, 1411 // the STORAGE_OK intent will re-trigger the update. 1412 Log.e(TAG, "Can't update accounts", e); 1413 } 1414 } 1415 }); 1416 } 1417 1418 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> { 1419 final IAccountManagerResponse mResponse; 1420 final Handler mHandler; 1421 final AccountManagerCallback<Bundle> mCallback; 1422 final Activity mActivity; 1423 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) { 1424 super(new Callable<Bundle>() { 1425 public Bundle call() throws Exception { 1426 throw new IllegalStateException("this should never be called"); 1427 } 1428 }); 1429 1430 mHandler = handler; 1431 mCallback = callback; 1432 mActivity = activity; 1433 mResponse = new Response(); 1434 } 1435 1436 public final AccountManagerFuture<Bundle> start() { 1437 try { 1438 doWork(); 1439 } catch (RemoteException e) { 1440 setException(e); 1441 } 1442 return this; 1443 } 1444 1445 protected void set(Bundle bundle) { 1446 // TODO: somehow a null is being set as the result of the Future. Log this 1447 // case to help debug where this is occurring. When this bug is fixed this 1448 // condition statement should be removed. 1449 if (bundle == null) { 1450 Log.e(TAG, "the bundle must not be null", new Exception()); 1451 } 1452 super.set(bundle); 1453 } 1454 1455 public abstract void doWork() throws RemoteException; 1456 1457 private Bundle internalGetResult(Long timeout, TimeUnit unit) 1458 throws OperationCanceledException, IOException, AuthenticatorException { 1459 if (!isDone()) { 1460 ensureNotOnMainThread(); 1461 } 1462 try { 1463 if (timeout == null) { 1464 return get(); 1465 } else { 1466 return get(timeout, unit); 1467 } 1468 } catch (CancellationException e) { 1469 throw new OperationCanceledException(); 1470 } catch (TimeoutException e) { 1471 // fall through and cancel 1472 } catch (InterruptedException e) { 1473 // fall through and cancel 1474 } catch (ExecutionException e) { 1475 final Throwable cause = e.getCause(); 1476 if (cause instanceof IOException) { 1477 throw (IOException) cause; 1478 } else if (cause instanceof UnsupportedOperationException) { 1479 throw new AuthenticatorException(cause); 1480 } else if (cause instanceof AuthenticatorException) { 1481 throw (AuthenticatorException) cause; 1482 } else if (cause instanceof RuntimeException) { 1483 throw (RuntimeException) cause; 1484 } else if (cause instanceof Error) { 1485 throw (Error) cause; 1486 } else { 1487 throw new IllegalStateException(cause); 1488 } 1489 } finally { 1490 cancel(true /* interrupt if running */); 1491 } 1492 throw new OperationCanceledException(); 1493 } 1494 1495 public Bundle getResult() 1496 throws OperationCanceledException, IOException, AuthenticatorException { 1497 return internalGetResult(null, null); 1498 } 1499 1500 public Bundle getResult(long timeout, TimeUnit unit) 1501 throws OperationCanceledException, IOException, AuthenticatorException { 1502 return internalGetResult(timeout, unit); 1503 } 1504 1505 protected void done() { 1506 if (mCallback != null) { 1507 postToHandler(mHandler, mCallback, this); 1508 } 1509 } 1510 1511 /** Handles the responses from the AccountManager */ 1512 private class Response extends IAccountManagerResponse.Stub { 1513 public void onResult(Bundle bundle) { 1514 Intent intent = bundle.getParcelable(KEY_INTENT); 1515 if (intent != null && mActivity != null) { 1516 // since the user provided an Activity we will silently start intents 1517 // that we see 1518 mActivity.startActivity(intent); 1519 // leave the Future running to wait for the real response to this request 1520 } else if (bundle.getBoolean("retry")) { 1521 try { 1522 doWork(); 1523 } catch (RemoteException e) { 1524 // this will only happen if the system process is dead, which means 1525 // we will be dying ourselves 1526 } 1527 } else { 1528 set(bundle); 1529 } 1530 } 1531 1532 public void onError(int code, String message) { 1533 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED) { 1534 // the authenticator indicated that this request was canceled, do so now 1535 cancel(true /* mayInterruptIfRunning */); 1536 return; 1537 } 1538 setException(convertErrorToException(code, message)); 1539 } 1540 } 1541 1542 } 1543 1544 private abstract class BaseFutureTask<T> extends FutureTask<T> { 1545 final public IAccountManagerResponse mResponse; 1546 final Handler mHandler; 1547 1548 public BaseFutureTask(Handler handler) { 1549 super(new Callable<T>() { 1550 public T call() throws Exception { 1551 throw new IllegalStateException("this should never be called"); 1552 } 1553 }); 1554 mHandler = handler; 1555 mResponse = new Response(); 1556 } 1557 1558 public abstract void doWork() throws RemoteException; 1559 1560 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException; 1561 1562 protected void postRunnableToHandler(Runnable runnable) { 1563 Handler handler = (mHandler == null) ? mMainHandler : mHandler; 1564 handler.post(runnable); 1565 } 1566 1567 protected void startTask() { 1568 try { 1569 doWork(); 1570 } catch (RemoteException e) { 1571 setException(e); 1572 } 1573 } 1574 1575 protected class Response extends IAccountManagerResponse.Stub { 1576 public void onResult(Bundle bundle) { 1577 try { 1578 T result = bundleToResult(bundle); 1579 if (result == null) { 1580 return; 1581 } 1582 set(result); 1583 return; 1584 } catch (ClassCastException e) { 1585 // we will set the exception below 1586 } catch (AuthenticatorException e) { 1587 // we will set the exception below 1588 } 1589 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response"); 1590 } 1591 1592 public void onError(int code, String message) { 1593 if (code == ERROR_CODE_CANCELED) { 1594 cancel(true /* mayInterruptIfRunning */); 1595 return; 1596 } 1597 setException(convertErrorToException(code, message)); 1598 } 1599 } 1600 } 1601 1602 private abstract class Future2Task<T> 1603 extends BaseFutureTask<T> implements AccountManagerFuture<T> { 1604 final AccountManagerCallback<T> mCallback; 1605 public Future2Task(Handler handler, AccountManagerCallback<T> callback) { 1606 super(handler); 1607 mCallback = callback; 1608 } 1609 1610 protected void done() { 1611 if (mCallback != null) { 1612 postRunnableToHandler(new Runnable() { 1613 public void run() { 1614 mCallback.run(Future2Task.this); 1615 } 1616 }); 1617 } 1618 } 1619 1620 public Future2Task<T> start() { 1621 startTask(); 1622 return this; 1623 } 1624 1625 private T internalGetResult(Long timeout, TimeUnit unit) 1626 throws OperationCanceledException, IOException, AuthenticatorException { 1627 if (!isDone()) { 1628 ensureNotOnMainThread(); 1629 } 1630 try { 1631 if (timeout == null) { 1632 return get(); 1633 } else { 1634 return get(timeout, unit); 1635 } 1636 } catch (InterruptedException e) { 1637 // fall through and cancel 1638 } catch (TimeoutException e) { 1639 // fall through and cancel 1640 } catch (CancellationException e) { 1641 // fall through and cancel 1642 } catch (ExecutionException e) { 1643 final Throwable cause = e.getCause(); 1644 if (cause instanceof IOException) { 1645 throw (IOException) cause; 1646 } else if (cause instanceof UnsupportedOperationException) { 1647 throw new AuthenticatorException(cause); 1648 } else if (cause instanceof AuthenticatorException) { 1649 throw (AuthenticatorException) cause; 1650 } else if (cause instanceof RuntimeException) { 1651 throw (RuntimeException) cause; 1652 } else if (cause instanceof Error) { 1653 throw (Error) cause; 1654 } else { 1655 throw new IllegalStateException(cause); 1656 } 1657 } finally { 1658 cancel(true /* interrupt if running */); 1659 } 1660 throw new OperationCanceledException(); 1661 } 1662 1663 public T getResult() 1664 throws OperationCanceledException, IOException, AuthenticatorException { 1665 return internalGetResult(null, null); 1666 } 1667 1668 public T getResult(long timeout, TimeUnit unit) 1669 throws OperationCanceledException, IOException, AuthenticatorException { 1670 return internalGetResult(timeout, unit); 1671 } 1672 1673 } 1674 1675 private Exception convertErrorToException(int code, String message) { 1676 if (code == ERROR_CODE_NETWORK_ERROR) { 1677 return new IOException(message); 1678 } 1679 1680 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) { 1681 return new UnsupportedOperationException(message); 1682 } 1683 1684 if (code == ERROR_CODE_INVALID_RESPONSE) { 1685 return new AuthenticatorException(message); 1686 } 1687 1688 if (code == ERROR_CODE_BAD_ARGUMENTS) { 1689 return new IllegalArgumentException(message); 1690 } 1691 1692 return new AuthenticatorException(message); 1693 } 1694 1695 private class GetAuthTokenByTypeAndFeaturesTask 1696 extends AmsTask implements AccountManagerCallback<Bundle> { 1697 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType, 1698 final String[] features, Activity activityForPrompting, 1699 final Bundle addAccountOptions, final Bundle loginOptions, 1700 AccountManagerCallback<Bundle> callback, Handler handler) { 1701 super(activityForPrompting, handler, callback); 1702 if (accountType == null) throw new IllegalArgumentException("account type is null"); 1703 mAccountType = accountType; 1704 mAuthTokenType = authTokenType; 1705 mFeatures = features; 1706 mAddAccountOptions = addAccountOptions; 1707 mLoginOptions = loginOptions; 1708 mMyCallback = this; 1709 } 1710 volatile AccountManagerFuture<Bundle> mFuture = null; 1711 final String mAccountType; 1712 final String mAuthTokenType; 1713 final String[] mFeatures; 1714 final Bundle mAddAccountOptions; 1715 final Bundle mLoginOptions; 1716 final AccountManagerCallback<Bundle> mMyCallback; 1717 private volatile int mNumAccounts = 0; 1718 1719 public void doWork() throws RemoteException { 1720 getAccountsByTypeAndFeatures(mAccountType, mFeatures, 1721 new AccountManagerCallback<Account[]>() { 1722 public void run(AccountManagerFuture<Account[]> future) { 1723 Account[] accounts; 1724 try { 1725 accounts = future.getResult(); 1726 } catch (OperationCanceledException e) { 1727 setException(e); 1728 return; 1729 } catch (IOException e) { 1730 setException(e); 1731 return; 1732 } catch (AuthenticatorException e) { 1733 setException(e); 1734 return; 1735 } 1736 1737 mNumAccounts = accounts.length; 1738 1739 if (accounts.length == 0) { 1740 if (mActivity != null) { 1741 // no accounts, add one now. pretend that the user directly 1742 // made this request 1743 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures, 1744 mAddAccountOptions, mActivity, mMyCallback, mHandler); 1745 } else { 1746 // send result since we can't prompt to add an account 1747 Bundle result = new Bundle(); 1748 result.putString(KEY_ACCOUNT_NAME, null); 1749 result.putString(KEY_ACCOUNT_TYPE, null); 1750 result.putString(KEY_AUTHTOKEN, null); 1751 try { 1752 mResponse.onResult(result); 1753 } catch (RemoteException e) { 1754 // this will never happen 1755 } 1756 // we are done 1757 } 1758 } else if (accounts.length == 1) { 1759 // have a single account, return an authtoken for it 1760 if (mActivity == null) { 1761 mFuture = getAuthToken(accounts[0], mAuthTokenType, 1762 false /* notifyAuthFailure */, mMyCallback, mHandler); 1763 } else { 1764 mFuture = getAuthToken(accounts[0], 1765 mAuthTokenType, mLoginOptions, 1766 mActivity, mMyCallback, mHandler); 1767 } 1768 } else { 1769 if (mActivity != null) { 1770 IAccountManagerResponse chooseResponse = 1771 new IAccountManagerResponse.Stub() { 1772 public void onResult(Bundle value) throws RemoteException { 1773 Account account = new Account( 1774 value.getString(KEY_ACCOUNT_NAME), 1775 value.getString(KEY_ACCOUNT_TYPE)); 1776 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions, 1777 mActivity, mMyCallback, mHandler); 1778 } 1779 1780 public void onError(int errorCode, String errorMessage) 1781 throws RemoteException { 1782 mResponse.onError(errorCode, errorMessage); 1783 } 1784 }; 1785 // have many accounts, launch the chooser 1786 Intent intent = new Intent(); 1787 ComponentName componentName = ComponentName.unflattenFromString( 1788 Resources.getSystem().getString( 1789 R.string.config_chooseAccountActivity)); 1790 intent.setClassName(componentName.getPackageName(), 1791 componentName.getClassName()); 1792 intent.putExtra(KEY_ACCOUNTS, accounts); 1793 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE, 1794 new AccountManagerResponse(chooseResponse)); 1795 mActivity.startActivity(intent); 1796 // the result will arrive via the IAccountManagerResponse 1797 } else { 1798 // send result since we can't prompt to select an account 1799 Bundle result = new Bundle(); 1800 result.putString(KEY_ACCOUNTS, null); 1801 try { 1802 mResponse.onResult(result); 1803 } catch (RemoteException e) { 1804 // this will never happen 1805 } 1806 // we are done 1807 } 1808 } 1809 }}, mHandler); 1810 } 1811 1812 public void run(AccountManagerFuture<Bundle> future) { 1813 try { 1814 final Bundle result = future.getResult(); 1815 if (mNumAccounts == 0) { 1816 final String accountName = result.getString(KEY_ACCOUNT_NAME); 1817 final String accountType = result.getString(KEY_ACCOUNT_TYPE); 1818 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) { 1819 setException(new AuthenticatorException("account not in result")); 1820 return; 1821 } 1822 final Account account = new Account(accountName, accountType); 1823 mNumAccounts = 1; 1824 getAuthToken(account, mAuthTokenType, null /* options */, mActivity, 1825 mMyCallback, mHandler); 1826 return; 1827 } 1828 set(result); 1829 } catch (OperationCanceledException e) { 1830 cancel(true /* mayInterruptIfRUnning */); 1831 } catch (IOException e) { 1832 setException(e); 1833 } catch (AuthenticatorException e) { 1834 setException(e); 1835 } 1836 } 1837 } 1838 1839 /** 1840 * This convenience helper combines the functionality of 1841 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and 1842 * {@link #addAccount}. 1843 * 1844 * <p>This method gets a list of the accounts matching the 1845 * specified type and feature set; if there is exactly one, it is 1846 * used; if there are more than one, the user is prompted to pick one; 1847 * if there are none, the user is prompted to add one. Finally, 1848 * an auth token is acquired for the chosen account. 1849 * 1850 * <p>This method may be called from any thread, but the returned 1851 * {@link AccountManagerFuture} must not be used on the main thread. 1852 * 1853 * <p>This method requires the caller to hold the permission 1854 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1855 * 1856 * @param accountType The account type required 1857 * (see {@link #getAccountsByType}), must not be null 1858 * @param authTokenType The desired auth token type 1859 * (see {@link #getAuthToken}), must not be null 1860 * @param features Required features for the account 1861 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty 1862 * @param activity The {@link Activity} context to use for launching new 1863 * sub-Activities to prompt to add an account, select an account, 1864 * and/or enter a password, as necessary; used only to call 1865 * startActivity(); should not be null 1866 * @param addAccountOptions Authenticator-specific options to use for 1867 * adding new accounts; may be null or empty 1868 * @param getAuthTokenOptions Authenticator-specific options to use for 1869 * getting auth tokens; may be null or empty 1870 * @param callback Callback to invoke when the request completes, 1871 * null for no callback 1872 * @param handler {@link Handler} identifying the callback thread, 1873 * null for the main thread 1874 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1875 * at least the following fields: 1876 * <ul> 1877 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account 1878 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1879 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 1880 * </ul> 1881 * 1882 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 1883 * <ul> 1884 * <li> {@link AuthenticatorException} if no authenticator was registered for 1885 * this account type or the authenticator failed to respond 1886 * <li> {@link OperationCanceledException} if the operation was canceled for 1887 * any reason, including the user canceling any operation 1888 * <li> {@link IOException} if the authenticator experienced an I/O problem 1889 * updating settings, usually because of network trouble 1890 * </ul> 1891 */ 1892 public AccountManagerFuture<Bundle> getAuthTokenByFeatures( 1893 final String accountType, final String authTokenType, final String[] features, 1894 final Activity activity, final Bundle addAccountOptions, 1895 final Bundle getAuthTokenOptions, 1896 final AccountManagerCallback<Bundle> callback, final Handler handler) { 1897 if (accountType == null) throw new IllegalArgumentException("account type is null"); 1898 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1899 final GetAuthTokenByTypeAndFeaturesTask task = 1900 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features, 1901 activity, addAccountOptions, getAuthTokenOptions, callback, handler); 1902 task.start(); 1903 return task; 1904 } 1905 1906 /** 1907 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of 1908 * accounts. 1909 * The caller will then typically start the activity by calling 1910 * <code>startActivityForResult(intent, ...);</code>. 1911 * <p> 1912 * On success the activity returns a Bundle with the account name and type specified using 1913 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}. 1914 * <p> 1915 * The most common case is to call this with one account type, e.g.: 1916 * <p> 1917 * <pre> newChooseAccountsIntent(null, null, new String[]{"com.google"}, false, null, 1918 * null, null, null);</pre> 1919 * @param selectedAccount if specified, indicates that the {@link Account} is the currently 1920 * selected one, according to the caller's definition of selected. 1921 * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be 1922 * shown. If not specified then this field will not limit the displayed accounts. 1923 * @param allowableAccountTypes an optional string array of account types. These are used 1924 * both to filter the shown accounts and to filter the list of account types that are shown 1925 * when adding an account. 1926 * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise 1927 * it is only shown when there is more than one account from which to choose 1928 * @param descriptionOverrideText if non-null this string is used as the description in the 1929 * accounts chooser screen rather than the default 1930 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount} 1931 * authTokenType parameter 1932 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount} 1933 * requiredFeatures parameter 1934 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options 1935 * parameter 1936 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow. 1937 */ 1938 static public Intent newChooseAccountIntent(Account selectedAccount, 1939 ArrayList<Account> allowableAccounts, 1940 String[] allowableAccountTypes, 1941 boolean alwaysPromptForAccount, 1942 String descriptionOverrideText, 1943 String addAccountAuthTokenType, 1944 String[] addAccountRequiredFeatures, 1945 Bundle addAccountOptions) { 1946 Intent intent = new Intent(); 1947 ComponentName componentName = ComponentName.unflattenFromString( 1948 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity)); 1949 intent.setClassName(componentName.getPackageName(), 1950 componentName.getClassName()); 1951 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST, 1952 allowableAccounts); 1953 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY, 1954 allowableAccountTypes); 1955 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE, 1956 addAccountOptions); 1957 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount); 1958 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT, 1959 alwaysPromptForAccount); 1960 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE, 1961 descriptionOverrideText); 1962 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING, 1963 addAccountAuthTokenType); 1964 intent.putExtra( 1965 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY, 1966 addAccountRequiredFeatures); 1967 return intent; 1968 } 1969 1970 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners = 1971 Maps.newHashMap(); 1972 1973 /** 1974 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent 1975 * so that it can read the updated list of accounts and send them to the listener 1976 * in mAccountsUpdatedListeners. 1977 */ 1978 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() { 1979 public void onReceive(final Context context, final Intent intent) { 1980 final Account[] accounts = getAccounts(); 1981 // send the result to the listeners 1982 synchronized (mAccountsUpdatedListeners) { 1983 for (Map.Entry<OnAccountsUpdateListener, Handler> entry : 1984 mAccountsUpdatedListeners.entrySet()) { 1985 postToHandler(entry.getValue(), entry.getKey(), accounts); 1986 } 1987 } 1988 } 1989 }; 1990 1991 /** 1992 * Adds an {@link OnAccountsUpdateListener} to this instance of the 1993 * {@link AccountManager}. This listener will be notified whenever the 1994 * list of accounts on the device changes. 1995 * 1996 * <p>As long as this listener is present, the AccountManager instance 1997 * will not be garbage-collected, and neither will the {@link Context} 1998 * used to retrieve it, which may be a large Activity instance. To avoid 1999 * memory leaks, you must remove this listener before then. Normally 2000 * listeners are added in an Activity or Service's {@link Activity#onCreate} 2001 * and removed in {@link Activity#onDestroy}. 2002 * 2003 * <p>It is safe to call this method from the main thread. 2004 * 2005 * <p>This method requires the caller to hold the permission 2006 * {@link android.Manifest.permission#GET_ACCOUNTS}. 2007 * 2008 * @param listener The listener to send notifications to 2009 * @param handler {@link Handler} identifying the thread to use 2010 * for notifications, null for the main thread 2011 * @param updateImmediately If true, the listener will be invoked 2012 * (on the handler thread) right away with the current account list 2013 * @throws IllegalArgumentException if listener is null 2014 * @throws IllegalStateException if listener was already added 2015 */ 2016 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener, 2017 Handler handler, boolean updateImmediately) { 2018 if (listener == null) { 2019 throw new IllegalArgumentException("the listener is null"); 2020 } 2021 synchronized (mAccountsUpdatedListeners) { 2022 if (mAccountsUpdatedListeners.containsKey(listener)) { 2023 throw new IllegalStateException("this listener is already added"); 2024 } 2025 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty(); 2026 2027 mAccountsUpdatedListeners.put(listener, handler); 2028 2029 if (wasEmpty) { 2030 // Register a broadcast receiver to monitor account changes 2031 IntentFilter intentFilter = new IntentFilter(); 2032 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION); 2033 // To recover from disk-full. 2034 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); 2035 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter); 2036 } 2037 } 2038 2039 if (updateImmediately) { 2040 postToHandler(handler, listener, getAccounts()); 2041 } 2042 } 2043 2044 /** 2045 * Removes an {@link OnAccountsUpdateListener} previously registered with 2046 * {@link #addOnAccountsUpdatedListener}. The listener will no longer 2047 * receive notifications of account changes. 2048 * 2049 * <p>It is safe to call this method from the main thread. 2050 * 2051 * <p>No permission is required to call this method. 2052 * 2053 * @param listener The previously added listener to remove 2054 * @throws IllegalArgumentException if listener is null 2055 * @throws IllegalStateException if listener was not already added 2056 */ 2057 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) { 2058 if (listener == null) throw new IllegalArgumentException("listener is null"); 2059 synchronized (mAccountsUpdatedListeners) { 2060 if (!mAccountsUpdatedListeners.containsKey(listener)) { 2061 Log.e(TAG, "Listener was not previously added"); 2062 return; 2063 } 2064 mAccountsUpdatedListeners.remove(listener); 2065 if (mAccountsUpdatedListeners.isEmpty()) { 2066 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver); 2067 } 2068 } 2069 } 2070} 2071