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