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