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