AccountManager.java revision b61e8fbabea2cc40ad65bf4f372a32d526cfc7ac
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 = options == null ? new Bundle() : options; 819 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 820 return new AmsTask(activity, handler, callback) { 821 public void doWork() throws RemoteException { 822 mService.getAuthToken(mResponse, account, authTokenType, 823 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */, 824 optionsIn); 825 } 826 }.start(); 827 } 828 829 /** 830 * Gets an auth token of the specified type for a particular account, 831 * optionally raising a notification if the user must enter credentials. 832 * This method is intended for background tasks and services where the 833 * user should not be immediately interrupted with a password prompt. 834 * 835 * <p>If a previously generated auth token is cached for this account and 836 * type, then it is returned. Otherwise, if a saved password is 837 * available, it is sent to the server to generate a new auth token. 838 * Otherwise, an {@link Intent} is returned which, when started, will 839 * prompt the user for a password. If the notifyAuthFailure parameter is 840 * set, a status bar notification is also created with the same Intent, 841 * alerting the user that they need to enter a password at some point. 842 * 843 * <p>In that case, you may need to wait until the user responds, which 844 * could take hours or days or forever. When the user does respond and 845 * supply a new password, the account manager will broadcast the 846 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can 847 * use to try again. 848 * 849 * <p>If notifyAuthFailure is not set, it is the application's 850 * responsibility to launch the returned Intent at some point. 851 * Either way, the result from this call will not wait for user action. 852 * 853 * <p>Some authenticators have auth token <em>types</em>, whose value 854 * is authenticator-dependent. Some services use different token types to 855 * access different functionality -- for example, Google uses different auth 856 * tokens to access Gmail and Google Calendar for the same account. 857 * 858 * <p>This method may be called from any thread, but the returned 859 * {@link AccountManagerFuture} must not be used on the main thread. 860 * 861 * <p>This method requires the caller to hold the permission 862 * {@link android.Manifest.permission#USE_CREDENTIALS}. 863 * 864 * @param account The account to fetch an auth token for 865 * @param authTokenType The auth token type, an authenticator-dependent 866 * string token, must not be null 867 * @param notifyAuthFailure True to add a notification to prompt the 868 * user for a password if necessary, false to leave that to the caller 869 * @param callback Callback to invoke when the request completes, 870 * null for no callback 871 * @param handler {@link Handler} identifying the callback thread, 872 * null for the main thread 873 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 874 * at least the following fields on success: 875 * <ul> 876 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 877 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 878 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 879 * </ul> 880 * 881 * (Other authenticator-specific values may be returned.) If the user 882 * must enter credentials, the returned Bundle contains only 883 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt. 884 * 885 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 886 * <ul> 887 * <li> {@link AuthenticatorException} if the authenticator failed to respond 888 * <li> {@link OperationCanceledException} if the operation is canceled for 889 * any reason, incluidng the user canceling a credential request 890 * <li> {@link IOException} if the authenticator experienced an I/O problem 891 * creating a new auth token, usually because of network trouble 892 * </ul> 893 * If the account is no longer present on the device, the return value is 894 * authenticator-dependent. The caller should verify the validity of the 895 * account before requesting an auth token. 896 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle, 897 * boolean, AccountManagerCallback, android.os.Handler)} instead 898 */ 899 @Deprecated 900 public AccountManagerFuture<Bundle> getAuthToken( 901 final Account account, final String authTokenType, 902 final boolean notifyAuthFailure, 903 AccountManagerCallback<Bundle> callback, Handler handler) { 904 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback, 905 handler); 906 } 907 908 /** 909 * Gets an auth token of the specified type for a particular account, 910 * optionally raising a notification if the user must enter credentials. 911 * This method is intended for background tasks and services where the 912 * user should not be immediately interrupted with a password prompt. 913 * 914 * <p>If a previously generated auth token is cached for this account and 915 * type, then it is returned. Otherwise, if a saved password is 916 * available, it is sent to the server to generate a new auth token. 917 * Otherwise, an {@link Intent} is returned which, when started, will 918 * prompt the user for a password. If the notifyAuthFailure parameter is 919 * set, a status bar notification is also created with the same Intent, 920 * alerting the user that they need to enter a password at some point. 921 * 922 * <p>In that case, you may need to wait until the user responds, which 923 * could take hours or days or forever. When the user does respond and 924 * supply a new password, the account manager will broadcast the 925 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can 926 * use to try again. 927 * 928 * <p>If notifyAuthFailure is not set, it is the application's 929 * responsibility to launch the returned Intent at some point. 930 * Either way, the result from this call will not wait for user action. 931 * 932 * <p>Some authenticators have auth token <em>types</em>, whose value 933 * is authenticator-dependent. Some services use different token types to 934 * access different functionality -- for example, Google uses different auth 935 * tokens to access Gmail and Google Calendar for the same account. 936 * 937 * <p>This method may be called from any thread, but the returned 938 * {@link AccountManagerFuture} must not be used on the main thread. 939 * 940 * <p>This method requires the caller to hold the permission 941 * {@link android.Manifest.permission#USE_CREDENTIALS}. 942 * 943 * @param account The account to fetch an auth token for 944 * @param authTokenType The auth token type, an authenticator-dependent 945 * string token, must not be null 946 * @param options Authenticator-specific options for the request, 947 * may be null or empty 948 * @param notifyAuthFailure True to add a notification to prompt the 949 * user for a password if necessary, false to leave that to the caller 950 * @param callback Callback to invoke when the request completes, 951 * null for no callback 952 * @param handler {@link Handler} identifying the callback thread, 953 * null for the main thread 954 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 955 * at least the following fields on success: 956 * <ul> 957 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 958 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 959 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 960 * </ul> 961 * 962 * (Other authenticator-specific values may be returned.) If the user 963 * must enter credentials, the returned Bundle contains only 964 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt. 965 * 966 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 967 * <ul> 968 * <li> {@link AuthenticatorException} if the authenticator failed to respond 969 * <li> {@link OperationCanceledException} if the operation is canceled for 970 * any reason, incluidng the user canceling a credential request 971 * <li> {@link IOException} if the authenticator experienced an I/O problem 972 * creating a new auth token, usually because of network trouble 973 * </ul> 974 * If the account is no longer present on the device, the return value is 975 * authenticator-dependent. The caller should verify the validity of the 976 * account before requesting an auth token. 977 */ 978 public AccountManagerFuture<Bundle> getAuthToken( 979 final Account account, final String authTokenType, final Bundle options, 980 final boolean notifyAuthFailure, 981 AccountManagerCallback<Bundle> callback, Handler handler) { 982 983 if (account == null) throw new IllegalArgumentException("account is null"); 984 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 985 final Bundle optionsIn = options == null ? new Bundle() : options; 986 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 987 return new AmsTask(null, handler, callback) { 988 public void doWork() throws RemoteException { 989 mService.getAuthToken(mResponse, account, authTokenType, 990 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn); 991 } 992 }.start(); 993 } 994 995 /** 996 * Asks the user to add an account of a specified type. The authenticator 997 * for this account type processes this request with the appropriate user 998 * interface. If the user does elect to create a new account, the account 999 * name is returned. 1000 * 1001 * <p>This method may be called from any thread, but the returned 1002 * {@link AccountManagerFuture} must not be used on the main thread. 1003 * 1004 * <p>This method requires the caller to hold the permission 1005 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1006 * 1007 * @param accountType The type of account to add; must not be null 1008 * @param authTokenType The type of auth token (see {@link #getAuthToken}) 1009 * this account will need to be able to generate, null for none 1010 * @param requiredFeatures The features (see {@link #hasFeatures}) this 1011 * account must have, null for none 1012 * @param addAccountOptions Authenticator-specific options for the request, 1013 * may be null or empty 1014 * @param activity The {@link Activity} context to use for launching a new 1015 * authenticator-defined sub-Activity to prompt the user to create an 1016 * account; used only to call startActivity(); if null, the prompt 1017 * will not be launched directly, but the necessary {@link Intent} 1018 * will be returned to the caller instead 1019 * @param callback Callback to invoke when the request completes, 1020 * null for no callback 1021 * @param handler {@link Handler} identifying the callback thread, 1022 * null for the main thread 1023 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1024 * these fields if activity was specified and an account was created: 1025 * <ul> 1026 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1027 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1028 * </ul> 1029 * 1030 * If no activity was specified, the returned Bundle contains only 1031 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1032 * actual account creation process. If an error occurred, 1033 * {@link AccountManagerFuture#getResult()} throws: 1034 * <ul> 1035 * <li> {@link AuthenticatorException} if no authenticator was registered for 1036 * this account type or the authenticator failed to respond 1037 * <li> {@link OperationCanceledException} if the operation was canceled for 1038 * any reason, including the user canceling the creation process 1039 * <li> {@link IOException} if the authenticator experienced an I/O problem 1040 * creating a new account, usually because of network trouble 1041 * </ul> 1042 */ 1043 public AccountManagerFuture<Bundle> addAccount(final String accountType, 1044 final String authTokenType, final String[] requiredFeatures, 1045 final Bundle addAccountOptions, 1046 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { 1047 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1048 final Bundle options = (addAccountOptions == null) ? new Bundle() : 1049 addAccountOptions; 1050 options.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1051 1052 return new AmsTask(activity, handler, callback) { 1053 public void doWork() throws RemoteException { 1054 mService.addAcount(mResponse, accountType, authTokenType, 1055 requiredFeatures, activity != null, options); 1056 } 1057 }.start(); 1058 } 1059 1060 /** 1061 * Confirms that the user knows the password for an account to make extra 1062 * sure they are the owner of the account. The user-entered password can 1063 * be supplied directly, otherwise the authenticator for this account type 1064 * prompts the user with the appropriate interface. This method is 1065 * intended for applications which want extra assurance; for example, the 1066 * phone lock screen uses this to let the user unlock the phone with an 1067 * account password if they forget the lock pattern. 1068 * 1069 * <p>If the user-entered password matches a saved password for this 1070 * account, the request is considered valid; otherwise the authenticator 1071 * verifies the password (usually by contacting the server). 1072 * 1073 * <p>This method may be called from any thread, but the returned 1074 * {@link AccountManagerFuture} must not be used on the main thread. 1075 * 1076 * <p>This method requires the caller to hold the permission 1077 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1078 * 1079 * @param account The account to confirm password knowledge for 1080 * @param options Authenticator-specific options for the request; 1081 * if the {@link #KEY_PASSWORD} string field is present, the 1082 * authenticator may use it directly rather than prompting the user; 1083 * may be null or empty 1084 * @param activity The {@link Activity} context to use for launching a new 1085 * authenticator-defined sub-Activity to prompt the user to enter a 1086 * password; used only to call startActivity(); if null, the prompt 1087 * will not be launched directly, but the necessary {@link Intent} 1088 * will be returned to the caller instead 1089 * @param callback Callback to invoke when the request completes, 1090 * null for no callback 1091 * @param handler {@link Handler} identifying the callback thread, 1092 * null for the main thread 1093 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1094 * with these fields if activity or password was supplied and 1095 * the account was successfully verified: 1096 * <ul> 1097 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1098 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1099 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success 1100 * </ul> 1101 * 1102 * If no activity or password was specified, the returned Bundle contains 1103 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1104 * password prompt. If an error occurred, 1105 * {@link AccountManagerFuture#getResult()} throws: 1106 * <ul> 1107 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1108 * <li> {@link OperationCanceledException} if the operation was canceled for 1109 * any reason, including the user canceling the password prompt 1110 * <li> {@link IOException} if the authenticator experienced an I/O problem 1111 * verifying the password, usually because of network trouble 1112 * </ul> 1113 */ 1114 public AccountManagerFuture<Bundle> confirmCredentials(final Account account, 1115 final Bundle options, 1116 final Activity activity, 1117 final AccountManagerCallback<Bundle> callback, 1118 final Handler handler) { 1119 if (account == null) throw new IllegalArgumentException("account is null"); 1120 return new AmsTask(activity, handler, callback) { 1121 public void doWork() throws RemoteException { 1122 mService.confirmCredentials(mResponse, account, options, activity != null); 1123 } 1124 }.start(); 1125 } 1126 1127 /** 1128 * Asks the user to enter a new password for an account, updating the 1129 * saved credentials for the account. Normally this happens automatically 1130 * when the server rejects credentials during an auth token fetch, but this 1131 * can be invoked directly to ensure we have the correct credentials stored. 1132 * 1133 * <p>This method may be called from any thread, but the returned 1134 * {@link AccountManagerFuture} must not be used on the main thread. 1135 * 1136 * <p>This method requires the caller to hold the permission 1137 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1138 * 1139 * @param account The account to update credentials for 1140 * @param authTokenType The credentials entered must allow an auth token 1141 * of this type to be created (but no actual auth token is returned); 1142 * may be null 1143 * @param options Authenticator-specific options for the request; 1144 * may be null or empty 1145 * @param activity The {@link Activity} context to use for launching a new 1146 * authenticator-defined sub-Activity to prompt the user to enter a 1147 * password; used only to call startActivity(); if null, the prompt 1148 * will not be launched directly, but the necessary {@link Intent} 1149 * will be returned to the caller instead 1150 * @param callback Callback to invoke when the request completes, 1151 * null for no callback 1152 * @param handler {@link Handler} identifying the callback thread, 1153 * null for the main thread 1154 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1155 * with these fields if an activity was supplied and the account 1156 * credentials were successfully updated: 1157 * <ul> 1158 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1159 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1160 * </ul> 1161 * 1162 * If no activity was specified, the returned Bundle contains only 1163 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1164 * password prompt. If an error occurred, 1165 * {@link AccountManagerFuture#getResult()} throws: 1166 * <ul> 1167 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1168 * <li> {@link OperationCanceledException} if the operation was canceled for 1169 * any reason, including the user canceling the password prompt 1170 * <li> {@link IOException} if the authenticator experienced an I/O problem 1171 * verifying the password, usually because of network trouble 1172 * </ul> 1173 */ 1174 public AccountManagerFuture<Bundle> updateCredentials(final Account account, 1175 final String authTokenType, 1176 final Bundle options, final Activity activity, 1177 final AccountManagerCallback<Bundle> callback, 1178 final Handler handler) { 1179 if (account == null) throw new IllegalArgumentException("account is null"); 1180 return new AmsTask(activity, handler, callback) { 1181 public void doWork() throws RemoteException { 1182 mService.updateCredentials(mResponse, account, authTokenType, activity != null, 1183 options); 1184 } 1185 }.start(); 1186 } 1187 1188 /** 1189 * Offers the user an opportunity to change an authenticator's settings. 1190 * These properties are for the authenticator in general, not a particular 1191 * account. Not all authenticators support this method. 1192 * 1193 * <p>This method may be called from any thread, but the returned 1194 * {@link AccountManagerFuture} must not be used on the main thread. 1195 * 1196 * <p>This method requires the caller to hold the permission 1197 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1198 * 1199 * @param accountType The account type associated with the authenticator 1200 * to adjust 1201 * @param activity The {@link Activity} context to use for launching a new 1202 * authenticator-defined sub-Activity to adjust authenticator settings; 1203 * used only to call startActivity(); if null, the settings dialog will 1204 * not be launched directly, but the necessary {@link Intent} will be 1205 * returned to the caller instead 1206 * @param callback Callback to invoke when the request completes, 1207 * null for no callback 1208 * @param handler {@link Handler} identifying the callback thread, 1209 * null for the main thread 1210 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1211 * which is empty if properties were edited successfully, or 1212 * if no activity was specified, contains only {@link #KEY_INTENT} 1213 * needed to launch the authenticator's settings dialog. 1214 * If an error occurred, {@link AccountManagerFuture#getResult()} 1215 * throws: 1216 * <ul> 1217 * <li> {@link AuthenticatorException} if no authenticator was registered for 1218 * this account type or the authenticator failed to respond 1219 * <li> {@link OperationCanceledException} if the operation was canceled for 1220 * any reason, including the user canceling the settings dialog 1221 * <li> {@link IOException} if the authenticator experienced an I/O problem 1222 * updating settings, usually because of network trouble 1223 * </ul> 1224 */ 1225 public AccountManagerFuture<Bundle> editProperties(final String accountType, 1226 final Activity activity, final AccountManagerCallback<Bundle> callback, 1227 final Handler handler) { 1228 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1229 return new AmsTask(activity, handler, callback) { 1230 public void doWork() throws RemoteException { 1231 mService.editProperties(mResponse, accountType, activity != null); 1232 } 1233 }.start(); 1234 } 1235 1236 private void ensureNotOnMainThread() { 1237 final Looper looper = Looper.myLooper(); 1238 if (looper != null && looper == mContext.getMainLooper()) { 1239 final IllegalStateException exception = new IllegalStateException( 1240 "calling this from your main thread can lead to deadlock"); 1241 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs", 1242 exception); 1243 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) { 1244 throw exception; 1245 } 1246 } 1247 } 1248 1249 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback, 1250 final AccountManagerFuture<Bundle> future) { 1251 handler = handler == null ? mMainHandler : handler; 1252 handler.post(new Runnable() { 1253 public void run() { 1254 callback.run(future); 1255 } 1256 }); 1257 } 1258 1259 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener, 1260 final Account[] accounts) { 1261 final Account[] accountsCopy = new Account[accounts.length]; 1262 // send a copy to make sure that one doesn't 1263 // change what another sees 1264 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length); 1265 handler = (handler == null) ? mMainHandler : handler; 1266 handler.post(new Runnable() { 1267 public void run() { 1268 try { 1269 listener.onAccountsUpdated(accountsCopy); 1270 } catch (SQLException e) { 1271 // Better luck next time. If the problem was disk-full, 1272 // the STORAGE_OK intent will re-trigger the update. 1273 Log.e(TAG, "Can't update accounts", e); 1274 } 1275 } 1276 }); 1277 } 1278 1279 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> { 1280 final IAccountManagerResponse mResponse; 1281 final Handler mHandler; 1282 final AccountManagerCallback<Bundle> mCallback; 1283 final Activity mActivity; 1284 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) { 1285 super(new Callable<Bundle>() { 1286 public Bundle call() throws Exception { 1287 throw new IllegalStateException("this should never be called"); 1288 } 1289 }); 1290 1291 mHandler = handler; 1292 mCallback = callback; 1293 mActivity = activity; 1294 mResponse = new Response(); 1295 } 1296 1297 public final AccountManagerFuture<Bundle> start() { 1298 try { 1299 doWork(); 1300 } catch (RemoteException e) { 1301 setException(e); 1302 } 1303 return this; 1304 } 1305 1306 protected void set(Bundle bundle) { 1307 // TODO: somehow a null is being set as the result of the Future. Log this 1308 // case to help debug where this is occurring. When this bug is fixed this 1309 // condition statement should be removed. 1310 if (bundle == null) { 1311 Log.e(TAG, "the bundle must not be null", new Exception()); 1312 } 1313 super.set(bundle); 1314 } 1315 1316 public abstract void doWork() throws RemoteException; 1317 1318 private Bundle internalGetResult(Long timeout, TimeUnit unit) 1319 throws OperationCanceledException, IOException, AuthenticatorException { 1320 if (!isDone()) { 1321 ensureNotOnMainThread(); 1322 } 1323 try { 1324 if (timeout == null) { 1325 return get(); 1326 } else { 1327 return get(timeout, unit); 1328 } 1329 } catch (CancellationException e) { 1330 throw new OperationCanceledException(); 1331 } catch (TimeoutException e) { 1332 // fall through and cancel 1333 } catch (InterruptedException e) { 1334 // fall through and cancel 1335 } catch (ExecutionException e) { 1336 final Throwable cause = e.getCause(); 1337 if (cause instanceof IOException) { 1338 throw (IOException) cause; 1339 } else if (cause instanceof UnsupportedOperationException) { 1340 throw new AuthenticatorException(cause); 1341 } else if (cause instanceof AuthenticatorException) { 1342 throw (AuthenticatorException) cause; 1343 } else if (cause instanceof RuntimeException) { 1344 throw (RuntimeException) cause; 1345 } else if (cause instanceof Error) { 1346 throw (Error) cause; 1347 } else { 1348 throw new IllegalStateException(cause); 1349 } 1350 } finally { 1351 cancel(true /* interrupt if running */); 1352 } 1353 throw new OperationCanceledException(); 1354 } 1355 1356 public Bundle getResult() 1357 throws OperationCanceledException, IOException, AuthenticatorException { 1358 return internalGetResult(null, null); 1359 } 1360 1361 public Bundle getResult(long timeout, TimeUnit unit) 1362 throws OperationCanceledException, IOException, AuthenticatorException { 1363 return internalGetResult(timeout, unit); 1364 } 1365 1366 protected void done() { 1367 if (mCallback != null) { 1368 postToHandler(mHandler, mCallback, this); 1369 } 1370 } 1371 1372 /** Handles the responses from the AccountManager */ 1373 private class Response extends IAccountManagerResponse.Stub { 1374 public void onResult(Bundle bundle) { 1375 Intent intent = bundle.getParcelable(KEY_INTENT); 1376 if (intent != null && mActivity != null) { 1377 // since the user provided an Activity we will silently start intents 1378 // that we see 1379 mActivity.startActivity(intent); 1380 // leave the Future running to wait for the real response to this request 1381 } else if (bundle.getBoolean("retry")) { 1382 try { 1383 doWork(); 1384 } catch (RemoteException e) { 1385 // this will only happen if the system process is dead, which means 1386 // we will be dying ourselves 1387 } 1388 } else { 1389 set(bundle); 1390 } 1391 } 1392 1393 public void onError(int code, String message) { 1394 if (code == ERROR_CODE_CANCELED) { 1395 // the authenticator indicated that this request was canceled, do so now 1396 cancel(true /* mayInterruptIfRunning */); 1397 return; 1398 } 1399 setException(convertErrorToException(code, message)); 1400 } 1401 } 1402 1403 } 1404 1405 private abstract class BaseFutureTask<T> extends FutureTask<T> { 1406 final public IAccountManagerResponse mResponse; 1407 final Handler mHandler; 1408 1409 public BaseFutureTask(Handler handler) { 1410 super(new Callable<T>() { 1411 public T call() throws Exception { 1412 throw new IllegalStateException("this should never be called"); 1413 } 1414 }); 1415 mHandler = handler; 1416 mResponse = new Response(); 1417 } 1418 1419 public abstract void doWork() throws RemoteException; 1420 1421 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException; 1422 1423 protected void postRunnableToHandler(Runnable runnable) { 1424 Handler handler = (mHandler == null) ? mMainHandler : mHandler; 1425 handler.post(runnable); 1426 } 1427 1428 protected void startTask() { 1429 try { 1430 doWork(); 1431 } catch (RemoteException e) { 1432 setException(e); 1433 } 1434 } 1435 1436 protected class Response extends IAccountManagerResponse.Stub { 1437 public void onResult(Bundle bundle) { 1438 try { 1439 T result = bundleToResult(bundle); 1440 if (result == null) { 1441 return; 1442 } 1443 set(result); 1444 return; 1445 } catch (ClassCastException e) { 1446 // we will set the exception below 1447 } catch (AuthenticatorException e) { 1448 // we will set the exception below 1449 } 1450 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response"); 1451 } 1452 1453 public void onError(int code, String message) { 1454 if (code == ERROR_CODE_CANCELED) { 1455 cancel(true /* mayInterruptIfRunning */); 1456 return; 1457 } 1458 setException(convertErrorToException(code, message)); 1459 } 1460 } 1461 } 1462 1463 private abstract class Future2Task<T> 1464 extends BaseFutureTask<T> implements AccountManagerFuture<T> { 1465 final AccountManagerCallback<T> mCallback; 1466 public Future2Task(Handler handler, AccountManagerCallback<T> callback) { 1467 super(handler); 1468 mCallback = callback; 1469 } 1470 1471 protected void done() { 1472 if (mCallback != null) { 1473 postRunnableToHandler(new Runnable() { 1474 public void run() { 1475 mCallback.run(Future2Task.this); 1476 } 1477 }); 1478 } 1479 } 1480 1481 public Future2Task<T> start() { 1482 startTask(); 1483 return this; 1484 } 1485 1486 private T internalGetResult(Long timeout, TimeUnit unit) 1487 throws OperationCanceledException, IOException, AuthenticatorException { 1488 if (!isDone()) { 1489 ensureNotOnMainThread(); 1490 } 1491 try { 1492 if (timeout == null) { 1493 return get(); 1494 } else { 1495 return get(timeout, unit); 1496 } 1497 } catch (InterruptedException e) { 1498 // fall through and cancel 1499 } catch (TimeoutException e) { 1500 // fall through and cancel 1501 } catch (CancellationException e) { 1502 // fall through and cancel 1503 } catch (ExecutionException e) { 1504 final Throwable cause = e.getCause(); 1505 if (cause instanceof IOException) { 1506 throw (IOException) cause; 1507 } else if (cause instanceof UnsupportedOperationException) { 1508 throw new AuthenticatorException(cause); 1509 } else if (cause instanceof AuthenticatorException) { 1510 throw (AuthenticatorException) cause; 1511 } else if (cause instanceof RuntimeException) { 1512 throw (RuntimeException) cause; 1513 } else if (cause instanceof Error) { 1514 throw (Error) cause; 1515 } else { 1516 throw new IllegalStateException(cause); 1517 } 1518 } finally { 1519 cancel(true /* interrupt if running */); 1520 } 1521 throw new OperationCanceledException(); 1522 } 1523 1524 public T getResult() 1525 throws OperationCanceledException, IOException, AuthenticatorException { 1526 return internalGetResult(null, null); 1527 } 1528 1529 public T getResult(long timeout, TimeUnit unit) 1530 throws OperationCanceledException, IOException, AuthenticatorException { 1531 return internalGetResult(timeout, unit); 1532 } 1533 1534 } 1535 1536 private Exception convertErrorToException(int code, String message) { 1537 if (code == ERROR_CODE_NETWORK_ERROR) { 1538 return new IOException(message); 1539 } 1540 1541 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) { 1542 return new UnsupportedOperationException(message); 1543 } 1544 1545 if (code == ERROR_CODE_INVALID_RESPONSE) { 1546 return new AuthenticatorException(message); 1547 } 1548 1549 if (code == ERROR_CODE_BAD_ARGUMENTS) { 1550 return new IllegalArgumentException(message); 1551 } 1552 1553 return new AuthenticatorException(message); 1554 } 1555 1556 private class GetAuthTokenByTypeAndFeaturesTask 1557 extends AmsTask implements AccountManagerCallback<Bundle> { 1558 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType, 1559 final String[] features, Activity activityForPrompting, 1560 final Bundle addAccountOptions, final Bundle loginOptions, 1561 AccountManagerCallback<Bundle> callback, Handler handler) { 1562 super(activityForPrompting, handler, callback); 1563 if (accountType == null) throw new IllegalArgumentException("account type is null"); 1564 mAccountType = accountType; 1565 mAuthTokenType = authTokenType; 1566 mFeatures = features; 1567 mAddAccountOptions = addAccountOptions; 1568 mLoginOptions = loginOptions; 1569 mMyCallback = this; 1570 } 1571 volatile AccountManagerFuture<Bundle> mFuture = null; 1572 final String mAccountType; 1573 final String mAuthTokenType; 1574 final String[] mFeatures; 1575 final Bundle mAddAccountOptions; 1576 final Bundle mLoginOptions; 1577 final AccountManagerCallback<Bundle> mMyCallback; 1578 private volatile int mNumAccounts = 0; 1579 1580 public void doWork() throws RemoteException { 1581 getAccountsByTypeAndFeatures(mAccountType, mFeatures, 1582 new AccountManagerCallback<Account[]>() { 1583 public void run(AccountManagerFuture<Account[]> future) { 1584 Account[] accounts; 1585 try { 1586 accounts = future.getResult(); 1587 } catch (OperationCanceledException e) { 1588 setException(e); 1589 return; 1590 } catch (IOException e) { 1591 setException(e); 1592 return; 1593 } catch (AuthenticatorException e) { 1594 setException(e); 1595 return; 1596 } 1597 1598 mNumAccounts = accounts.length; 1599 1600 if (accounts.length == 0) { 1601 if (mActivity != null) { 1602 // no accounts, add one now. pretend that the user directly 1603 // made this request 1604 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures, 1605 mAddAccountOptions, mActivity, mMyCallback, mHandler); 1606 } else { 1607 // send result since we can't prompt to add an account 1608 Bundle result = new Bundle(); 1609 result.putString(KEY_ACCOUNT_NAME, null); 1610 result.putString(KEY_ACCOUNT_TYPE, null); 1611 result.putString(KEY_AUTHTOKEN, null); 1612 try { 1613 mResponse.onResult(result); 1614 } catch (RemoteException e) { 1615 // this will never happen 1616 } 1617 // we are done 1618 } 1619 } else if (accounts.length == 1) { 1620 // have a single account, return an authtoken for it 1621 if (mActivity == null) { 1622 mFuture = getAuthToken(accounts[0], mAuthTokenType, 1623 false /* notifyAuthFailure */, mMyCallback, mHandler); 1624 } else { 1625 mFuture = getAuthToken(accounts[0], 1626 mAuthTokenType, mLoginOptions, 1627 mActivity, mMyCallback, mHandler); 1628 } 1629 } else { 1630 if (mActivity != null) { 1631 IAccountManagerResponse chooseResponse = 1632 new IAccountManagerResponse.Stub() { 1633 public void onResult(Bundle value) throws RemoteException { 1634 Account account = new Account( 1635 value.getString(KEY_ACCOUNT_NAME), 1636 value.getString(KEY_ACCOUNT_TYPE)); 1637 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions, 1638 mActivity, mMyCallback, mHandler); 1639 } 1640 1641 public void onError(int errorCode, String errorMessage) 1642 throws RemoteException { 1643 mResponse.onError(errorCode, errorMessage); 1644 } 1645 }; 1646 // have many accounts, launch the chooser 1647 Intent intent = new Intent(); 1648 intent.setClassName("android", 1649 "android.accounts.ChooseAccountActivity"); 1650 intent.putExtra(KEY_ACCOUNTS, accounts); 1651 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE, 1652 new AccountManagerResponse(chooseResponse)); 1653 mActivity.startActivity(intent); 1654 // the result will arrive via the IAccountManagerResponse 1655 } else { 1656 // send result since we can't prompt to select an account 1657 Bundle result = new Bundle(); 1658 result.putString(KEY_ACCOUNTS, null); 1659 try { 1660 mResponse.onResult(result); 1661 } catch (RemoteException e) { 1662 // this will never happen 1663 } 1664 // we are done 1665 } 1666 } 1667 }}, mHandler); 1668 } 1669 1670 public void run(AccountManagerFuture<Bundle> future) { 1671 try { 1672 final Bundle result = future.getResult(); 1673 if (mNumAccounts == 0) { 1674 final String accountName = result.getString(KEY_ACCOUNT_NAME); 1675 final String accountType = result.getString(KEY_ACCOUNT_TYPE); 1676 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) { 1677 setException(new AuthenticatorException("account not in result")); 1678 return; 1679 } 1680 final Account account = new Account(accountName, accountType); 1681 mNumAccounts = 1; 1682 getAuthToken(account, mAuthTokenType, null /* options */, mActivity, 1683 mMyCallback, mHandler); 1684 return; 1685 } 1686 set(result); 1687 } catch (OperationCanceledException e) { 1688 cancel(true /* mayInterruptIfRUnning */); 1689 } catch (IOException e) { 1690 setException(e); 1691 } catch (AuthenticatorException e) { 1692 setException(e); 1693 } 1694 } 1695 } 1696 1697 /** 1698 * This convenience helper combines the functionality of 1699 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and 1700 * {@link #addAccount}. 1701 * 1702 * <p>This method gets a list of the accounts matching the 1703 * specified type and feature set; if there is exactly one, it is 1704 * used; if there are more than one, the user is prompted to pick one; 1705 * if there are none, the user is prompted to add one. Finally, 1706 * an auth token is acquired for the chosen account. 1707 * 1708 * <p>This method may be called from any thread, but the returned 1709 * {@link AccountManagerFuture} must not be used on the main thread. 1710 * 1711 * <p>This method requires the caller to hold the permission 1712 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}. 1713 * 1714 * @param accountType The account type required 1715 * (see {@link #getAccountsByType}), must not be null 1716 * @param authTokenType The desired auth token type 1717 * (see {@link #getAuthToken}), must not be null 1718 * @param features Required features for the account 1719 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty 1720 * @param activity The {@link Activity} context to use for launching new 1721 * sub-Activities to prompt to add an account, select an account, 1722 * and/or enter a password, as necessary; used only to call 1723 * startActivity(); should not be null 1724 * @param addAccountOptions Authenticator-specific options to use for 1725 * adding new accounts; may be null or empty 1726 * @param getAuthTokenOptions Authenticator-specific options to use for 1727 * getting auth tokens; may be null or empty 1728 * @param callback Callback to invoke when the request completes, 1729 * null for no callback 1730 * @param handler {@link Handler} identifying the callback thread, 1731 * null for the main thread 1732 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1733 * at least the following fields: 1734 * <ul> 1735 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account 1736 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1737 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 1738 * </ul> 1739 * 1740 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 1741 * <ul> 1742 * <li> {@link AuthenticatorException} if no authenticator was registered for 1743 * this account type or the authenticator failed to respond 1744 * <li> {@link OperationCanceledException} if the operation was canceled for 1745 * any reason, including the user canceling any operation 1746 * <li> {@link IOException} if the authenticator experienced an I/O problem 1747 * updating settings, usually because of network trouble 1748 * </ul> 1749 */ 1750 public AccountManagerFuture<Bundle> getAuthTokenByFeatures( 1751 final String accountType, final String authTokenType, final String[] features, 1752 final Activity activity, final Bundle addAccountOptions, 1753 final Bundle getAuthTokenOptions, 1754 final AccountManagerCallback<Bundle> callback, final Handler handler) { 1755 if (accountType == null) throw new IllegalArgumentException("account type is null"); 1756 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1757 final GetAuthTokenByTypeAndFeaturesTask task = 1758 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features, 1759 activity, addAccountOptions, getAuthTokenOptions, callback, handler); 1760 task.start(); 1761 return task; 1762 } 1763 1764 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners = 1765 Maps.newHashMap(); 1766 1767 /** 1768 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent 1769 * so that it can read the updated list of accounts and send them to the listener 1770 * in mAccountsUpdatedListeners. 1771 */ 1772 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() { 1773 public void onReceive(final Context context, final Intent intent) { 1774 final Account[] accounts = getAccounts(); 1775 // send the result to the listeners 1776 synchronized (mAccountsUpdatedListeners) { 1777 for (Map.Entry<OnAccountsUpdateListener, Handler> entry : 1778 mAccountsUpdatedListeners.entrySet()) { 1779 postToHandler(entry.getValue(), entry.getKey(), accounts); 1780 } 1781 } 1782 } 1783 }; 1784 1785 /** 1786 * Adds an {@link OnAccountsUpdateListener} to this instance of the 1787 * {@link AccountManager}. This listener will be notified whenever the 1788 * list of accounts on the device changes. 1789 * 1790 * <p>As long as this listener is present, the AccountManager instance 1791 * will not be garbage-collected, and neither will the {@link Context} 1792 * used to retrieve it, which may be a large Activity instance. To avoid 1793 * memory leaks, you must remove this listener before then. Normally 1794 * listeners are added in an Activity or Service's {@link Activity#onCreate} 1795 * and removed in {@link Activity#onDestroy}. 1796 * 1797 * <p>It is safe to call this method from the main thread. 1798 * 1799 * <p>No permission is required to call this method. 1800 * 1801 * @param listener The listener to send notifications to 1802 * @param handler {@link Handler} identifying the thread to use 1803 * for notifications, null for the main thread 1804 * @param updateImmediately If true, the listener will be invoked 1805 * (on the handler thread) right away with the current account list 1806 * @throws IllegalArgumentException if listener is null 1807 * @throws IllegalStateException if listener was already added 1808 */ 1809 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener, 1810 Handler handler, boolean updateImmediately) { 1811 if (listener == null) { 1812 throw new IllegalArgumentException("the listener is null"); 1813 } 1814 synchronized (mAccountsUpdatedListeners) { 1815 if (mAccountsUpdatedListeners.containsKey(listener)) { 1816 throw new IllegalStateException("this listener is already added"); 1817 } 1818 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty(); 1819 1820 mAccountsUpdatedListeners.put(listener, handler); 1821 1822 if (wasEmpty) { 1823 // Register a broadcast receiver to monitor account changes 1824 IntentFilter intentFilter = new IntentFilter(); 1825 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION); 1826 // To recover from disk-full. 1827 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); 1828 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter); 1829 } 1830 } 1831 1832 if (updateImmediately) { 1833 postToHandler(handler, listener, getAccounts()); 1834 } 1835 } 1836 1837 /** 1838 * Removes an {@link OnAccountsUpdateListener} previously registered with 1839 * {@link #addOnAccountsUpdatedListener}. The listener will no longer 1840 * receive notifications of account changes. 1841 * 1842 * <p>It is safe to call this method from the main thread. 1843 * 1844 * <p>No permission is required to call this method. 1845 * 1846 * @param listener The previously added listener to remove 1847 * @throws IllegalArgumentException if listener is null 1848 * @throws IllegalStateException if listener was not already added 1849 */ 1850 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) { 1851 if (listener == null) throw new IllegalArgumentException("listener is null"); 1852 synchronized (mAccountsUpdatedListeners) { 1853 if (!mAccountsUpdatedListeners.containsKey(listener)) { 1854 Log.e(TAG, "Listener was not previously added"); 1855 return; 1856 } 1857 mAccountsUpdatedListeners.remove(listener); 1858 if (mAccountsUpdatedListeners.isEmpty()) { 1859 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver); 1860 } 1861 } 1862 } 1863} 1864