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