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