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