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