AccountManager.java revision 390c9d2d91117c767b27e33e906f7830b4c0a4dc
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 public void doWork() throws RemoteException { 596 mService.getAuthTokenLabel(mResponse, accountType, authTokenType); 597 } 598 599 @Override 600 public String bundleToResult(Bundle bundle) throws AuthenticatorException { 601 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) { 602 throw new AuthenticatorException("no result in response"); 603 } 604 return bundle.getString(KEY_AUTH_TOKEN_LABEL); 605 } 606 }.start(); 607 } 608 609 /** 610 * Finds out whether a particular account has all the specified features. 611 * Account features are authenticator-specific string tokens identifying 612 * boolean account properties. For example, features are used to tell 613 * whether Google accounts have a particular service (such as Google 614 * Calendar or Google Talk) enabled. The feature names and their meanings 615 * are published somewhere associated with the authenticator in question. 616 * 617 * <p>This method may be called from any thread, but the returned 618 * {@link AccountManagerFuture} must not be used on the main thread. 619 * 620 * <p>This method requires the caller to hold the permission 621 * {@link android.Manifest.permission#GET_ACCOUNTS} or be a signature 622 * match with the AbstractAccountAuthenticator that manages the account. 623 * 624 * @param account The {@link Account} to test 625 * @param features An array of the account features to check 626 * @param callback Callback to invoke when the request completes, 627 * null for no callback 628 * @param handler {@link Handler} identifying the callback thread, 629 * null for the main thread 630 * @return An {@link AccountManagerFuture} which resolves to a Boolean, 631 * true if the account exists and has all of the specified features. 632 */ 633 @RequiresPermission(GET_ACCOUNTS) 634 public AccountManagerFuture<Boolean> hasFeatures(final Account account, 635 final String[] features, 636 AccountManagerCallback<Boolean> callback, Handler handler) { 637 if (account == null) throw new IllegalArgumentException("account is null"); 638 if (features == null) throw new IllegalArgumentException("features is null"); 639 return new Future2Task<Boolean>(handler, callback) { 640 public void doWork() throws RemoteException { 641 mService.hasFeatures(mResponse, account, features, mContext.getOpPackageName()); 642 } 643 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 644 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 645 throw new AuthenticatorException("no result in response"); 646 } 647 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 648 } 649 }.start(); 650 } 651 652 /** 653 * Lists all accounts of a type which have certain features. The account 654 * type identifies the authenticator (see {@link #getAccountsByType}). 655 * Account features are authenticator-specific string tokens identifying 656 * boolean account properties (see {@link #hasFeatures}). 657 * 658 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator, 659 * which may contact the server or do other work to check account features, 660 * so the method returns an {@link AccountManagerFuture}. 661 * 662 * <p>This method may be called from any thread, but the returned 663 * {@link AccountManagerFuture} must not be used on the main thread. 664 * 665 * <p>Clients of this method that have not been granted the 666 * {@link android.Manifest.permission#GET_ACCOUNTS} permission, 667 * will only see those accounts managed by AbstractAccountAuthenticators whose 668 * signature matches the client. 669 * 670 * @param type The type of accounts to return, must not be null 671 * @param features An array of the account features to require, 672 * may be null or empty 673 * 674 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 675 * GET_ACCOUNTS permission is needed for those platforms, irrespective of uid 676 * or signature match. See docs for this function in API level 22. 677 * 678 * @param callback Callback to invoke when the request completes, 679 * null for no callback 680 * @param handler {@link Handler} identifying the callback thread, 681 * null for the main thread 682 * @return An {@link AccountManagerFuture} which resolves to an array of 683 * {@link Account}, one per account of the specified type which 684 * matches the requested features. 685 */ 686 @RequiresPermission(GET_ACCOUNTS) 687 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures( 688 final String type, final String[] features, 689 AccountManagerCallback<Account[]> callback, Handler handler) { 690 if (type == null) throw new IllegalArgumentException("type is null"); 691 return new Future2Task<Account[]>(handler, callback) { 692 public void doWork() throws RemoteException { 693 mService.getAccountsByFeatures(mResponse, type, features, 694 mContext.getOpPackageName()); 695 } 696 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException { 697 if (!bundle.containsKey(KEY_ACCOUNTS)) { 698 throw new AuthenticatorException("no result in response"); 699 } 700 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS); 701 Account[] descs = new Account[parcelables.length]; 702 for (int i = 0; i < parcelables.length; i++) { 703 descs[i] = (Account) parcelables[i]; 704 } 705 return descs; 706 } 707 }.start(); 708 } 709 710 /** 711 * Adds an account directly to the AccountManager. Normally used by sign-up 712 * wizards associated with authenticators, not directly by applications. 713 * <p>Calling this method does not update the last authenticated timestamp, 714 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call 715 * {@link #notifyAccountAuthenticated(Account)} after getting success. 716 * However, if this method is called when it is triggered by addAccount() or 717 * addAccountAsUser() or similar functions, then there is no need to update 718 * timestamp manually as it is updated automatically by framework on 719 * successful completion of the mentioned functions. 720 * <p>It is safe to call this method from the main thread. 721 * <p>This method requires the caller to have a signature match with the 722 * authenticator that owns the specified account. 723 * 724 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 725 * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs 726 * for this function in API level 22. 727 * 728 * @param account The {@link Account} to add 729 * @param password The password to associate with the account, null for none 730 * @param userdata String values to use for the account's userdata, null for 731 * none 732 * @return True if the account was successfully added, false if the account 733 * already exists, the account is null, or another error occurs. 734 */ 735 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) { 736 if (account == null) throw new IllegalArgumentException("account is null"); 737 try { 738 return mService.addAccountExplicitly(account, password, userdata); 739 } catch (RemoteException e) { 740 // Can happen if there was a SecurityException was thrown. 741 throw new RuntimeException(e); 742 } 743 } 744 745 /** 746 * Notifies the system that the account has just been authenticated. This 747 * information may be used by other applications to verify the account. This 748 * should be called only when the user has entered correct credentials for 749 * the account. 750 * <p> 751 * It is not safe to call this method from the main thread. As such, call it 752 * from another thread. 753 * <p>This method requires the caller to have a signature match with the 754 * authenticator that owns the specified account. 755 * 756 * @param account The {@link Account} to be updated. 757 * @return boolean {@code true} if the authentication of the account has been successfully 758 * acknowledged. Otherwise {@code false}. 759 */ 760 public boolean notifyAccountAuthenticated(Account account) { 761 if (account == null) 762 throw new IllegalArgumentException("account is null"); 763 try { 764 return mService.accountAuthenticated(account); 765 } catch (RemoteException e) { 766 throw new RuntimeException(e); 767 } 768 } 769 770 /** 771 * Rename the specified {@link Account}. This is equivalent to removing 772 * the existing account and adding a new renamed account with the old 773 * account's user data. 774 * 775 * <p>It is safe to call this method from the main thread. 776 * 777 * <p>This method requires the caller to have a signature match with the 778 * authenticator that manages the specified account. 779 * 780 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 781 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator 782 * is needed for those platforms. See docs for this function in API level 22. 783 * 784 * @param account The {@link Account} to rename 785 * @param newName String name to be associated with the account. 786 * @param callback Callback to invoke when the request completes, null for 787 * no callback 788 * @param handler {@link Handler} identifying the callback thread, null for 789 * the main thread 790 * @return An {@link AccountManagerFuture} which resolves to the Account 791 * after the name change. If successful the account's name will be the 792 * specified new name. 793 */ 794 public AccountManagerFuture<Account> renameAccount( 795 final Account account, 796 @Size(min = 1) final String newName, 797 AccountManagerCallback<Account> callback, 798 Handler handler) { 799 if (account == null) throw new IllegalArgumentException("account is null."); 800 if (TextUtils.isEmpty(newName)) { 801 throw new IllegalArgumentException("newName is empty or null."); 802 } 803 return new Future2Task<Account>(handler, callback) { 804 @Override 805 public void doWork() throws RemoteException { 806 mService.renameAccount(mResponse, account, newName); 807 } 808 @Override 809 public Account bundleToResult(Bundle bundle) throws AuthenticatorException { 810 String name = bundle.getString(KEY_ACCOUNT_NAME); 811 String type = bundle.getString(KEY_ACCOUNT_TYPE); 812 return new Account(name, type); 813 } 814 }.start(); 815 } 816 817 /** 818 * Gets the previous name associated with the account or {@code null}, if 819 * none. This is intended so that clients of {@link 820 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an 821 * authenticator has renamed an account. 822 * 823 * <p>It is safe to call this method from the main thread. 824 * 825 * @param account The account to query for a previous name. 826 * @return The account's previous name, null if the account has never been 827 * renamed. 828 */ 829 public String getPreviousName(final Account account) { 830 if (account == null) throw new IllegalArgumentException("account is null"); 831 try { 832 return mService.getPreviousName(account); 833 } catch (RemoteException e) { 834 // will never happen 835 throw new RuntimeException(e); 836 } 837 } 838 839 /** 840 * Removes an account from the AccountManager. Does nothing if the account 841 * does not exist. Does not delete the account from the server. 842 * The authenticator may have its own policies preventing account 843 * deletion, in which case the account will not be deleted. 844 * 845 * <p>This method requires the caller to have a signature match with the 846 * authenticator that manages the specified account. 847 * 848 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 849 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 850 * this function in API level 22. 851 * 852 * @param account The {@link Account} to remove 853 * @param callback Callback to invoke when the request completes, 854 * null for no callback 855 * @param handler {@link Handler} identifying the callback thread, 856 * null for the main thread 857 * @return An {@link AccountManagerFuture} which resolves to a Boolean, 858 * true if the account has been successfully removed 859 * @deprecated use 860 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)} 861 * instead 862 */ 863 @Deprecated 864 public AccountManagerFuture<Boolean> removeAccount(final Account account, 865 AccountManagerCallback<Boolean> callback, Handler handler) { 866 if (account == null) throw new IllegalArgumentException("account is null"); 867 return new Future2Task<Boolean>(handler, callback) { 868 @Override 869 public void doWork() throws RemoteException { 870 mService.removeAccount(mResponse, account, false); 871 } 872 @Override 873 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 874 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 875 throw new AuthenticatorException("no result in response"); 876 } 877 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 878 } 879 }.start(); 880 } 881 882 /** 883 * Removes an account from the AccountManager. Does nothing if the account 884 * does not exist. Does not delete the account from the server. 885 * The authenticator may have its own policies preventing account 886 * deletion, in which case the account will not be deleted. 887 * 888 * <p>This method may be called from any thread, but the returned 889 * {@link AccountManagerFuture} must not be used on the main thread. 890 * 891 * <p>This method requires the caller to have a signature match with the 892 * authenticator that manages the specified account. 893 * 894 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 895 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 896 * this function in API level 22. 897 * 898 * @param account The {@link Account} to remove 899 * @param activity The {@link Activity} context to use for launching a new 900 * authenticator-defined sub-Activity to prompt the user to delete an 901 * account; used only to call startActivity(); if null, the prompt 902 * will not be launched directly, but the {@link Intent} may be 903 * returned to the caller instead 904 * @param callback Callback to invoke when the request completes, 905 * null for no callback 906 * @param handler {@link Handler} identifying the callback thread, 907 * null for the main thread 908 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 909 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account 910 * was removed or if active. If no activity was specified, the returned 911 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent} 912 * needed to launch the actual account removal process, if authenticator 913 * needs the activity launch. If an error occurred, 914 * {@link AccountManagerFuture#getResult()} throws: 915 * <ul> 916 * <li> {@link AuthenticatorException} if no authenticator was registered for 917 * this account type or the authenticator failed to respond 918 * <li> {@link OperationCanceledException} if the operation was canceled for 919 * any reason, including the user canceling the creation process or 920 * adding accounts (of this type) has been disabled by policy 921 * </ul> 922 */ 923 public AccountManagerFuture<Bundle> removeAccount(final Account account, 924 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { 925 if (account == null) throw new IllegalArgumentException("account is null"); 926 return new AmsTask(activity, handler, callback) { 927 @Override 928 public void doWork() throws RemoteException { 929 mService.removeAccount(mResponse, account, activity != null); 930 } 931 }.start(); 932 } 933 934 /** 935 * @see #removeAccount(Account, AccountManagerCallback, Handler) 936 * @hide 937 * @deprecated use 938 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)} 939 * instead 940 */ 941 @Deprecated 942 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account, 943 AccountManagerCallback<Boolean> callback, Handler handler, 944 final UserHandle userHandle) { 945 if (account == null) throw new IllegalArgumentException("account is null"); 946 if (userHandle == null) throw new IllegalArgumentException("userHandle is null"); 947 return new Future2Task<Boolean>(handler, callback) { 948 @Override 949 public void doWork() throws RemoteException { 950 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier()); 951 } 952 @Override 953 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 954 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 955 throw new AuthenticatorException("no result in response"); 956 } 957 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 958 } 959 }.start(); 960 } 961 962 /** 963 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler) 964 * @hide 965 */ 966 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account, 967 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler, 968 final UserHandle userHandle) { 969 if (account == null) 970 throw new IllegalArgumentException("account is null"); 971 if (userHandle == null) 972 throw new IllegalArgumentException("userHandle is null"); 973 return new AmsTask(activity, handler, callback) { 974 public void doWork() throws RemoteException { 975 mService.removeAccountAsUser(mResponse, account, activity != null, 976 userHandle.getIdentifier()); 977 } 978 }.start(); 979 } 980 981 /** 982 * Removes an account directly. Normally used by authenticators, not 983 * directly by applications. Does not delete the account from the server. 984 * The authenticator may have its own policies preventing account deletion, 985 * in which case the account will not be deleted. 986 * <p> 987 * It is safe to call this method from the main thread. 988 * <p>This method requires the caller to have a signature match with the 989 * authenticator that manages the specified account. 990 * 991 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 992 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator 993 * is needed for those platforms. See docs for this function in API level 22. 994 * 995 * @param account The {@link Account} to delete. 996 * @return True if the account was successfully deleted, false if the 997 * account did not exist, the account is null, or another error 998 * occurs. 999 */ 1000 public boolean removeAccountExplicitly(Account account) { 1001 if (account == null) throw new IllegalArgumentException("account is null"); 1002 try { 1003 return mService.removeAccountExplicitly(account); 1004 } catch (RemoteException e) { 1005 // May happen if the caller doesn't match the signature of the authenticator. 1006 throw new RuntimeException(e); 1007 } 1008 } 1009 1010 /** 1011 * Removes an auth token from the AccountManager's cache. Does nothing if 1012 * the auth token is not currently in the cache. Applications must call this 1013 * method when the auth token is found to have expired or otherwise become 1014 * invalid for authenticating requests. The AccountManager does not validate 1015 * or expire cached auth tokens otherwise. 1016 * 1017 * <p>It is safe to call this method from the main thread. 1018 * 1019 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1020 * MANAGE_ACCOUNTS or USE_CREDENTIALS permission is needed for those 1021 * platforms. See docs for this function in API level 22. 1022 * 1023 * @param accountType The account type of the auth token to invalidate, must not be null 1024 * @param authToken The auth token to invalidate, may be null 1025 */ 1026 public void invalidateAuthToken(final String accountType, final String authToken) { 1027 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1028 try { 1029 if (authToken != null) { 1030 mService.invalidateAuthToken(accountType, authToken); 1031 } 1032 } catch (RemoteException e) { 1033 // won't ever happen 1034 throw new RuntimeException(e); 1035 } 1036 } 1037 1038 /** 1039 * Gets an auth token from the AccountManager's cache. If no auth 1040 * token is cached for this account, null will be returned -- a new 1041 * auth token will not be generated, and the server will not be contacted. 1042 * Intended for use by the authenticator, not directly by applications. 1043 * 1044 * <p>It is safe to call this method from the main thread. 1045 * 1046 * <p>This method requires the caller to have a signature match with the 1047 * authenticator that manages the specified account. 1048 * 1049 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1050 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator 1051 * is needed for those platforms. See docs for this function in API level 22. 1052 * 1053 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}. 1054 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}. 1055 * @return The cached auth token for this account and type, or null if 1056 * no auth token is cached or the account does not exist. 1057 * @see #getAuthToken 1058 */ 1059 public String peekAuthToken(final Account account, final String authTokenType) { 1060 if (account == null) throw new IllegalArgumentException("account is null"); 1061 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1062 try { 1063 return mService.peekAuthToken(account, authTokenType); 1064 } catch (RemoteException e) { 1065 // won't ever happen 1066 throw new RuntimeException(e); 1067 } 1068 } 1069 1070 /** 1071 * Sets or forgets a saved password. This modifies the local copy of the 1072 * password used to automatically authenticate the user; it does not change 1073 * the user's account password on the server. Intended for use by the 1074 * authenticator, not directly by applications. 1075 * <p>Calling this method does not update the last authenticated timestamp, 1076 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call 1077 * {@link #notifyAccountAuthenticated(Account)} after getting success. 1078 * <p>It is safe to call this method from the main thread. 1079 * <p>This method requires the caller to have a signature match with the 1080 * authenticator that manages the specified account. 1081 * 1082 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1083 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator 1084 * is needed for those platforms. See docs for this function in API level 22. 1085 * 1086 * @param account The account whose password is to be set. Cannot be 1087 * {@code null}. 1088 * @param password The password to set, null to clear the password 1089 */ 1090 public void setPassword(final Account account, final String password) { 1091 if (account == null) throw new IllegalArgumentException("account is null"); 1092 try { 1093 mService.setPassword(account, password); 1094 } catch (RemoteException e) { 1095 // won't ever happen 1096 throw new RuntimeException(e); 1097 } 1098 } 1099 1100 /** 1101 * Forgets a saved password. This erases the local copy of the password; 1102 * it does not change the user's account password on the server. 1103 * Has the same effect as setPassword(account, null) but requires fewer 1104 * permissions, and may be used by applications or management interfaces 1105 * to "sign out" from an account. 1106 * 1107 * <p>This method only successfully clear the account's password when the 1108 * caller has the same signature as the authenticator that owns the 1109 * specified account. Otherwise, this method will silently fail. 1110 * 1111 * <p>It is safe to call this method from the main thread. 1112 * 1113 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1114 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 1115 * this function in API level 22. 1116 * 1117 * @param account The account whose password to clear 1118 */ 1119 public void clearPassword(final Account account) { 1120 if (account == null) throw new IllegalArgumentException("account is null"); 1121 try { 1122 mService.clearPassword(account); 1123 } catch (RemoteException e) { 1124 // won't ever happen 1125 throw new RuntimeException(e); 1126 } 1127 } 1128 1129 /** 1130 * Sets one userdata key for an account. Intended by use for the 1131 * authenticator to stash state for itself, not directly by applications. 1132 * The meaning of the keys and values is up to the authenticator. 1133 * 1134 * <p>It is safe to call this method from the main thread. 1135 * 1136 * <p>This method requires the caller to have a signature match with the 1137 * authenticator that manages the specified account. 1138 * 1139 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1140 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator 1141 * is needed for those platforms. See docs for this function in API level 22. 1142 * 1143 * @param account Account whose user data is to be set. Must not be {@code null}. 1144 * @param key String user data key to set. Must not be null 1145 * @param value String value to set, {@code null} to clear this user data key 1146 */ 1147 public void setUserData(final Account account, final String key, final String value) { 1148 if (account == null) throw new IllegalArgumentException("account is null"); 1149 if (key == null) throw new IllegalArgumentException("key is null"); 1150 try { 1151 mService.setUserData(account, key, value); 1152 } catch (RemoteException e) { 1153 // Will happen if there is not signature match. 1154 throw new RuntimeException(e); 1155 } 1156 } 1157 1158 /** 1159 * Adds an auth token to the AccountManager cache for an account. 1160 * If the account does not exist then this call has no effect. 1161 * Replaces any previous auth token for this account and auth token type. 1162 * Intended for use by the authenticator, not directly by applications. 1163 * 1164 * <p>It is safe to call this method from the main thread. 1165 * 1166 * <p>This method requires the caller to have a signature match with the 1167 * authenticator that manages the specified account. 1168 * 1169 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1170 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator 1171 * is needed for those platforms. See docs for this function in API level 22. 1172 * 1173 * @param account The account to set an auth token for 1174 * @param authTokenType The type of the auth token, see {#getAuthToken} 1175 * @param authToken The auth token to add to the cache 1176 */ 1177 public void setAuthToken(Account account, final String authTokenType, final String authToken) { 1178 if (account == null) throw new IllegalArgumentException("account is null"); 1179 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1180 try { 1181 mService.setAuthToken(account, authTokenType, authToken); 1182 } catch (RemoteException e) { 1183 // won't ever happen 1184 throw new RuntimeException(e); 1185 } 1186 } 1187 1188 /** 1189 * This convenience helper synchronously gets an auth token with 1190 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}. 1191 * 1192 * <p>This method may block while a network request completes, and must 1193 * never be made from the main thread. 1194 * 1195 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1196 * USE_CREDENTIALS permission is needed for those platforms. See docs for 1197 * this function in API level 22. 1198 * 1199 * @param account The account to fetch an auth token for 1200 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()} 1201 * @param notifyAuthFailure If true, display a notification and return null 1202 * if authentication fails; if false, prompt and wait for the user to 1203 * re-enter correct credentials before returning 1204 * @return An auth token of the specified type for this account, or null 1205 * if authentication fails or none can be fetched. 1206 * @throws AuthenticatorException if the authenticator failed to respond 1207 * @throws OperationCanceledException if the request was canceled for any 1208 * reason, including the user canceling a credential request 1209 * @throws java.io.IOException if the authenticator experienced an I/O problem 1210 * creating a new auth token, usually because of network trouble 1211 */ 1212 public String blockingGetAuthToken(Account account, String authTokenType, 1213 boolean notifyAuthFailure) 1214 throws OperationCanceledException, IOException, AuthenticatorException { 1215 if (account == null) throw new IllegalArgumentException("account is null"); 1216 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1217 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */, 1218 null /* handler */).getResult(); 1219 if (bundle == null) { 1220 // This should never happen, but it does, occasionally. If it does return null to 1221 // signify that we were not able to get the authtoken. 1222 // TODO: remove this when the bug is found that sometimes causes a null bundle to be 1223 // returned 1224 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for " 1225 + account + ", authTokenType " + authTokenType); 1226 return null; 1227 } 1228 return bundle.getString(KEY_AUTHTOKEN); 1229 } 1230 1231 /** 1232 * Gets an auth token of the specified type for a particular account, 1233 * prompting the user for credentials if necessary. This method is 1234 * intended for applications running in the foreground where it makes 1235 * sense to ask the user directly for a password. 1236 * 1237 * <p>If a previously generated auth token is cached for this account and 1238 * type, then it is returned. Otherwise, if a saved password is 1239 * available, it is sent to the server to generate a new auth token. 1240 * Otherwise, the user is prompted to enter a password. 1241 * 1242 * <p>Some authenticators have auth token <em>types</em>, whose value 1243 * is authenticator-dependent. Some services use different token types to 1244 * access different functionality -- for example, Google uses different auth 1245 * tokens to access Gmail and Google Calendar for the same account. 1246 * 1247 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1248 * USE_CREDENTIALS permission is needed for those platforms. See docs for 1249 * this function in API level 22. 1250 * 1251 * <p>This method may be called from any thread, but the returned 1252 * {@link AccountManagerFuture} must not be used on the main thread. 1253 * 1254 * @param account The account to fetch an auth token for 1255 * @param authTokenType The auth token type, an authenticator-dependent 1256 * string token, must not be null 1257 * @param options Authenticator-specific options for the request, 1258 * may be null or empty 1259 * @param activity The {@link Activity} context to use for launching a new 1260 * authenticator-defined sub-Activity to prompt the user for a password 1261 * if necessary; used only to call startActivity(); must not be null. 1262 * @param callback Callback to invoke when the request completes, 1263 * null for no callback 1264 * @param handler {@link Handler} identifying the callback thread, 1265 * null for the main thread 1266 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1267 * at least the following fields: 1268 * <ul> 1269 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 1270 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1271 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 1272 * </ul> 1273 * 1274 * (Other authenticator-specific values may be returned.) If an auth token 1275 * could not be fetched, {@link AccountManagerFuture#getResult()} throws: 1276 * <ul> 1277 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1278 * <li> {@link OperationCanceledException} if the operation is canceled for 1279 * any reason, incluidng the user canceling a credential request 1280 * <li> {@link IOException} if the authenticator experienced an I/O problem 1281 * creating a new auth token, usually because of network trouble 1282 * </ul> 1283 * If the account is no longer present on the device, the return value is 1284 * authenticator-dependent. The caller should verify the validity of the 1285 * account before requesting an auth token. 1286 */ 1287 public AccountManagerFuture<Bundle> getAuthToken( 1288 final Account account, final String authTokenType, final Bundle options, 1289 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { 1290 if (account == null) throw new IllegalArgumentException("account is null"); 1291 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1292 final Bundle optionsIn = new Bundle(); 1293 if (options != null) { 1294 optionsIn.putAll(options); 1295 } 1296 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1297 return new AmsTask(activity, handler, callback) { 1298 public void doWork() throws RemoteException { 1299 mService.getAuthToken(mResponse, account, authTokenType, 1300 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */, 1301 optionsIn); 1302 } 1303 }.start(); 1304 } 1305 1306 /** 1307 * Gets an auth token of the specified type for a particular account, 1308 * optionally raising a notification if the user must enter credentials. 1309 * This method is intended for background tasks and services where the 1310 * user should not be immediately interrupted with a password prompt. 1311 * 1312 * <p>If a previously generated auth token is cached for this account and 1313 * type, then it is returned. Otherwise, if a saved password is 1314 * available, it is sent to the server to generate a new auth token. 1315 * Otherwise, an {@link Intent} is returned which, when started, will 1316 * prompt the user for a password. If the notifyAuthFailure parameter is 1317 * set, a status bar notification is also created with the same Intent, 1318 * alerting the user that they need to enter a password at some point. 1319 * 1320 * <p>In that case, you may need to wait until the user responds, which 1321 * could take hours or days or forever. When the user does respond and 1322 * supply a new password, the account manager will broadcast the 1323 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can 1324 * use to try again. 1325 * 1326 * <p>If notifyAuthFailure is not set, it is the application's 1327 * responsibility to launch the returned Intent at some point. 1328 * Either way, the result from this call will not wait for user action. 1329 * 1330 * <p>Some authenticators have auth token <em>types</em>, whose value 1331 * is authenticator-dependent. Some services use different token types to 1332 * access different functionality -- for example, Google uses different auth 1333 * tokens to access Gmail and Google Calendar for the same account. 1334 * 1335 * <p>This method may be called from any thread, but the returned 1336 * {@link AccountManagerFuture} must not be used on the main thread. 1337 * 1338 * @param account The account to fetch an auth token for 1339 * @param authTokenType The auth token type, an authenticator-dependent 1340 * string token, must not be null 1341 * @param notifyAuthFailure True to add a notification to prompt the 1342 * user for a password if necessary, false to leave that to the caller 1343 * @param callback Callback to invoke when the request completes, 1344 * null for no callback 1345 * @param handler {@link Handler} identifying the callback thread, 1346 * null for the main thread 1347 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1348 * at least the following fields on success: 1349 * <ul> 1350 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 1351 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1352 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 1353 * </ul> 1354 * 1355 * (Other authenticator-specific values may be returned.) If the user 1356 * must enter credentials, the returned Bundle contains only 1357 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt. 1358 * 1359 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 1360 * <ul> 1361 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1362 * <li> {@link OperationCanceledException} if the operation is canceled for 1363 * any reason, incluidng the user canceling a credential request 1364 * <li> {@link IOException} if the authenticator experienced an I/O problem 1365 * creating a new auth token, usually because of network trouble 1366 * </ul> 1367 * If the account is no longer present on the device, the return value is 1368 * authenticator-dependent. The caller should verify the validity of the 1369 * account before requesting an auth token. 1370 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle, 1371 * boolean, AccountManagerCallback, android.os.Handler)} instead 1372 */ 1373 @Deprecated 1374 public AccountManagerFuture<Bundle> getAuthToken( 1375 final Account account, final String authTokenType, 1376 final boolean notifyAuthFailure, 1377 AccountManagerCallback<Bundle> callback, Handler handler) { 1378 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback, 1379 handler); 1380 } 1381 1382 /** 1383 * Gets an auth token of the specified type for a particular account, 1384 * optionally raising a notification if the user must enter credentials. 1385 * This method is intended for background tasks and services where the 1386 * user should not be immediately interrupted with a password prompt. 1387 * 1388 * <p>If a previously generated auth token is cached for this account and 1389 * type, then it is returned. Otherwise, if a saved password is 1390 * available, it is sent to the server to generate a new auth token. 1391 * Otherwise, an {@link Intent} is returned which, when started, will 1392 * prompt the user for a password. If the notifyAuthFailure parameter is 1393 * set, a status bar notification is also created with the same Intent, 1394 * alerting the user that they need to enter a password at some point. 1395 * 1396 * <p>In that case, you may need to wait until the user responds, which 1397 * could take hours or days or forever. When the user does respond and 1398 * supply a new password, the account manager will broadcast the 1399 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can 1400 * use to try again. 1401 * 1402 * <p>If notifyAuthFailure is not set, it is the application's 1403 * responsibility to launch the returned Intent at some point. 1404 * Either way, the result from this call will not wait for user action. 1405 * 1406 * <p>Some authenticators have auth token <em>types</em>, whose value 1407 * is authenticator-dependent. Some services use different token types to 1408 * access different functionality -- for example, Google uses different auth 1409 * tokens to access Gmail and Google Calendar for the same account. 1410 * 1411 * <p>This method may be called from any thread, but the returned 1412 * {@link AccountManagerFuture} must not be used on the main thread. 1413 * 1414 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1415 * USE_CREDENTIALS permission is needed for those platforms. See docs for 1416 * this function in API level 22. 1417 * 1418 * @param account The account to fetch an auth token for 1419 * @param authTokenType The auth token type, an authenticator-dependent 1420 * string token, must not be null 1421 * @param options Authenticator-specific options for the request, 1422 * may be null or empty 1423 * @param notifyAuthFailure True to add a notification to prompt the 1424 * user for a password if necessary, false to leave that to the caller 1425 * @param callback Callback to invoke when the request completes, 1426 * null for no callback 1427 * @param handler {@link Handler} identifying the callback thread, 1428 * null for the main thread 1429 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1430 * at least the following fields on success: 1431 * <ul> 1432 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied 1433 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1434 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 1435 * </ul> 1436 * 1437 * (Other authenticator-specific values may be returned.) If the user 1438 * must enter credentials, the returned Bundle contains only 1439 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt. 1440 * 1441 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 1442 * <ul> 1443 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1444 * <li> {@link OperationCanceledException} if the operation is canceled for 1445 * any reason, incluidng the user canceling a credential request 1446 * <li> {@link IOException} if the authenticator experienced an I/O problem 1447 * creating a new auth token, usually because of network trouble 1448 * </ul> 1449 * If the account is no longer present on the device, the return value is 1450 * authenticator-dependent. The caller should verify the validity of the 1451 * account before requesting an auth token. 1452 */ 1453 public AccountManagerFuture<Bundle> getAuthToken( 1454 final Account account, final String authTokenType, final Bundle options, 1455 final boolean notifyAuthFailure, 1456 AccountManagerCallback<Bundle> callback, Handler handler) { 1457 1458 if (account == null) throw new IllegalArgumentException("account is null"); 1459 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 1460 final Bundle optionsIn = new Bundle(); 1461 if (options != null) { 1462 optionsIn.putAll(options); 1463 } 1464 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1465 return new AmsTask(null, handler, callback) { 1466 public void doWork() throws RemoteException { 1467 mService.getAuthToken(mResponse, account, authTokenType, 1468 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn); 1469 } 1470 }.start(); 1471 } 1472 1473 /** 1474 * Asks the user to add an account of a specified type. The authenticator 1475 * for this account type processes this request with the appropriate user 1476 * interface. If the user does elect to create a new account, the account 1477 * name is returned. 1478 * 1479 * <p>This method may be called from any thread, but the returned 1480 * {@link AccountManagerFuture} must not be used on the main thread. 1481 * 1482 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1483 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 1484 * this function in API level 22. 1485 * 1486 * @param accountType The type of account to add; must not be null 1487 * @param authTokenType The type of auth token (see {@link #getAuthToken}) 1488 * this account will need to be able to generate, null for none 1489 * @param requiredFeatures The features (see {@link #hasFeatures}) this 1490 * account must have, null for none 1491 * @param addAccountOptions Authenticator-specific options for the request, 1492 * may be null or empty 1493 * @param activity The {@link Activity} context to use for launching a new 1494 * authenticator-defined sub-Activity to prompt the user to create an 1495 * account; used only to call startActivity(); if null, the prompt 1496 * will not be launched directly, but the necessary {@link Intent} 1497 * will be returned to the caller instead 1498 * @param callback Callback to invoke when the request completes, 1499 * null for no callback 1500 * @param handler {@link Handler} identifying the callback thread, 1501 * null for the main thread 1502 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 1503 * these fields if activity was specified and an account was created: 1504 * <ul> 1505 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created 1506 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1507 * </ul> 1508 * 1509 * If no activity was specified, the returned Bundle contains only 1510 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1511 * actual account creation process. If an error occurred, 1512 * {@link AccountManagerFuture#getResult()} throws: 1513 * <ul> 1514 * <li> {@link AuthenticatorException} if no authenticator was registered for 1515 * this account type or the authenticator failed to respond 1516 * <li> {@link OperationCanceledException} if the operation was canceled for 1517 * any reason, including the user canceling the creation process or adding accounts 1518 * (of this type) has been disabled by policy 1519 * <li> {@link IOException} if the authenticator experienced an I/O problem 1520 * creating a new account, usually because of network trouble 1521 * </ul> 1522 */ 1523 public AccountManagerFuture<Bundle> addAccount(final String accountType, 1524 final String authTokenType, final String[] requiredFeatures, 1525 final Bundle addAccountOptions, 1526 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) { 1527 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1528 final Bundle optionsIn = new Bundle(); 1529 if (addAccountOptions != null) { 1530 optionsIn.putAll(addAccountOptions); 1531 } 1532 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1533 1534 return new AmsTask(activity, handler, callback) { 1535 public void doWork() throws RemoteException { 1536 mService.addAccount(mResponse, accountType, authTokenType, 1537 requiredFeatures, activity != null, optionsIn); 1538 } 1539 }.start(); 1540 } 1541 1542 /** 1543 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler) 1544 * @hide 1545 */ 1546 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType, 1547 final String authTokenType, final String[] requiredFeatures, 1548 final Bundle addAccountOptions, final Activity activity, 1549 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) { 1550 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1551 if (userHandle == null) throw new IllegalArgumentException("userHandle is null"); 1552 final Bundle optionsIn = new Bundle(); 1553 if (addAccountOptions != null) { 1554 optionsIn.putAll(addAccountOptions); 1555 } 1556 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 1557 1558 return new AmsTask(activity, handler, callback) { 1559 public void doWork() throws RemoteException { 1560 mService.addAccountAsUser(mResponse, accountType, authTokenType, 1561 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier()); 1562 } 1563 }.start(); 1564 } 1565 1566 1567 /** 1568 * Adds shared accounts from a parent user to a secondary user. Adding the shared account 1569 * doesn't take effect immediately. When the target user starts up, any pending shared accounts 1570 * are attempted to be copied to the target user from the primary via calls to the 1571 * authenticator. 1572 * @param parentUser parent user 1573 * @param user target user 1574 * @hide 1575 */ 1576 public void addSharedAccountsFromParentUser(UserHandle parentUser, UserHandle user) { 1577 try { 1578 mService.addSharedAccountsFromParentUser(parentUser.getIdentifier(), 1579 user.getIdentifier()); 1580 } catch (RemoteException re) { 1581 throw new IllegalStateException(re); 1582 } 1583 } 1584 1585 /** 1586 * Copies an account from one user to another user. 1587 * @param account the account to copy 1588 * @param fromUser the user to copy the account from 1589 * @param toUser the target user 1590 * @param callback Callback to invoke when the request completes, 1591 * null for no callback 1592 * @param handler {@link Handler} identifying the callback thread, 1593 * null for the main thread 1594 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it 1595 * succeeded. 1596 * @hide 1597 */ 1598 public AccountManagerFuture<Boolean> copyAccountToUser( 1599 final Account account, final UserHandle fromUser, final UserHandle toUser, 1600 AccountManagerCallback<Boolean> callback, Handler handler) { 1601 if (account == null) throw new IllegalArgumentException("account is null"); 1602 if (toUser == null || fromUser == null) { 1603 throw new IllegalArgumentException("fromUser and toUser cannot be null"); 1604 } 1605 1606 return new Future2Task<Boolean>(handler, callback) { 1607 @Override 1608 public void doWork() throws RemoteException { 1609 mService.copyAccountToUser( 1610 mResponse, account, fromUser.getIdentifier(), toUser.getIdentifier()); 1611 } 1612 @Override 1613 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 1614 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 1615 throw new AuthenticatorException("no result in response"); 1616 } 1617 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 1618 } 1619 }.start(); 1620 } 1621 1622 /** 1623 * @hide 1624 * Removes the shared account. 1625 * @param account the account to remove 1626 * @param user the user to remove the account from 1627 * @return 1628 */ 1629 public boolean removeSharedAccount(final Account account, UserHandle user) { 1630 try { 1631 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier()); 1632 return val; 1633 } catch (RemoteException re) { 1634 // won't ever happen 1635 throw new RuntimeException(re); 1636 } 1637 } 1638 1639 /** 1640 * @hide 1641 * @param user 1642 * @return 1643 */ 1644 public Account[] getSharedAccounts(UserHandle user) { 1645 try { 1646 return mService.getSharedAccountsAsUser(user.getIdentifier()); 1647 } catch (RemoteException re) { 1648 // won't ever happen 1649 throw new RuntimeException(re); 1650 } 1651 } 1652 1653 /** 1654 * Confirms that the user knows the password for an account to make extra 1655 * sure they are the owner of the account. The user-entered password can 1656 * be supplied directly, otherwise the authenticator for this account type 1657 * prompts the user with the appropriate interface. This method is 1658 * intended for applications which want extra assurance; for example, the 1659 * phone lock screen uses this to let the user unlock the phone with an 1660 * account password if they forget the lock pattern. 1661 * 1662 * <p>If the user-entered password matches a saved password for this 1663 * account, the request is considered valid; otherwise the authenticator 1664 * verifies the password (usually by contacting the server). 1665 * 1666 * <p>This method may be called from any thread, but the returned 1667 * {@link AccountManagerFuture} must not be used on the main thread. 1668 * 1669 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1670 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs 1671 * for this function in API level 22. 1672 * 1673 * @param account The account to confirm password knowledge for 1674 * @param options Authenticator-specific options for the request; 1675 * if the {@link #KEY_PASSWORD} string field is present, the 1676 * authenticator may use it directly rather than prompting the user; 1677 * may be null or empty 1678 * @param activity The {@link Activity} context to use for launching a new 1679 * authenticator-defined sub-Activity to prompt the user to enter a 1680 * password; used only to call startActivity(); if null, the prompt 1681 * will not be launched directly, but the necessary {@link Intent} 1682 * will be returned to the caller instead 1683 * @param callback Callback to invoke when the request completes, 1684 * null for no callback 1685 * @param handler {@link Handler} identifying the callback thread, 1686 * null for the main thread 1687 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1688 * with these fields if activity or password was supplied and 1689 * the account was successfully verified: 1690 * <ul> 1691 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified 1692 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1693 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success 1694 * </ul> 1695 * 1696 * If no activity or password was specified, the returned Bundle contains 1697 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1698 * password prompt. 1699 * 1700 * <p>Also the returning Bundle may contain {@link 1701 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the 1702 * credential was validated/created. 1703 * 1704 * If an error occurred,{@link AccountManagerFuture#getResult()} throws: 1705 * <ul> 1706 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1707 * <li> {@link OperationCanceledException} if the operation was canceled for 1708 * any reason, including the user canceling the password prompt 1709 * <li> {@link IOException} if the authenticator experienced an I/O problem 1710 * verifying the password, usually because of network trouble 1711 * </ul> 1712 */ 1713 public AccountManagerFuture<Bundle> confirmCredentials(final Account account, 1714 final Bundle options, 1715 final Activity activity, 1716 final AccountManagerCallback<Bundle> callback, 1717 final Handler handler) { 1718 return confirmCredentialsAsUser(account, options, activity, callback, handler, 1719 Process.myUserHandle()); 1720 } 1721 1722 /** 1723 * @hide 1724 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)} 1725 * but for the specified user. 1726 */ 1727 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account, 1728 final Bundle options, 1729 final Activity activity, 1730 final AccountManagerCallback<Bundle> callback, 1731 final Handler handler, UserHandle userHandle) { 1732 if (account == null) throw new IllegalArgumentException("account is null"); 1733 final int userId = userHandle.getIdentifier(); 1734 return new AmsTask(activity, handler, callback) { 1735 public void doWork() throws RemoteException { 1736 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null, 1737 userId); 1738 } 1739 }.start(); 1740 } 1741 1742 /** 1743 * Asks the user to enter a new password for an account, updating the 1744 * saved credentials for the account. Normally this happens automatically 1745 * when the server rejects credentials during an auth token fetch, but this 1746 * can be invoked directly to ensure we have the correct credentials stored. 1747 * 1748 * <p>This method may be called from any thread, but the returned 1749 * {@link AccountManagerFuture} must not be used on the main thread. 1750 * 1751 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1752 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 1753 * this function in API level 22. 1754 * 1755 * @param account The account to update credentials for 1756 * @param authTokenType The credentials entered must allow an auth token 1757 * of this type to be created (but no actual auth token is returned); 1758 * may be null 1759 * @param options Authenticator-specific options for the request; 1760 * may be null or empty 1761 * @param activity The {@link Activity} context to use for launching a new 1762 * authenticator-defined sub-Activity to prompt the user to enter a 1763 * password; used only to call startActivity(); if null, the prompt 1764 * will not be launched directly, but the necessary {@link Intent} 1765 * will be returned to the caller instead 1766 * @param callback Callback to invoke when the request completes, 1767 * null for no callback 1768 * @param handler {@link Handler} identifying the callback thread, 1769 * null for the main thread 1770 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1771 * with these fields if an activity was supplied and the account 1772 * credentials were successfully updated: 1773 * <ul> 1774 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account 1775 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 1776 * </ul> 1777 * 1778 * If no activity was specified, the returned Bundle contains 1779 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 1780 * password prompt. If an error occurred, 1781 * {@link AccountManagerFuture#getResult()} throws: 1782 * <ul> 1783 * <li> {@link AuthenticatorException} if the authenticator failed to respond 1784 * <li> {@link OperationCanceledException} if the operation was canceled for 1785 * any reason, including the user canceling the password prompt 1786 * <li> {@link IOException} if the authenticator experienced an I/O problem 1787 * verifying the password, usually because of network trouble 1788 * </ul> 1789 */ 1790 public AccountManagerFuture<Bundle> updateCredentials(final Account account, 1791 final String authTokenType, 1792 final Bundle options, final Activity activity, 1793 final AccountManagerCallback<Bundle> callback, 1794 final Handler handler) { 1795 if (account == null) throw new IllegalArgumentException("account is null"); 1796 return new AmsTask(activity, handler, callback) { 1797 public void doWork() throws RemoteException { 1798 mService.updateCredentials(mResponse, account, authTokenType, activity != null, 1799 options); 1800 } 1801 }.start(); 1802 } 1803 1804 /** 1805 * Offers the user an opportunity to change an authenticator's settings. 1806 * These properties are for the authenticator in general, not a particular 1807 * account. Not all authenticators support this method. 1808 * 1809 * <p>This method may be called from any thread, but the returned 1810 * {@link AccountManagerFuture} must not be used on the main thread. 1811 * 1812 * <p>This method requires the caller to have the same signature as the 1813 * authenticator associated with the specified account type. 1814 * 1815 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 1816 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs 1817 * for this function in API level 22. 1818 * 1819 * @param accountType The account type associated with the authenticator 1820 * to adjust 1821 * @param activity The {@link Activity} context to use for launching a new 1822 * authenticator-defined sub-Activity to adjust authenticator settings; 1823 * used only to call startActivity(); if null, the settings dialog will 1824 * not be launched directly, but the necessary {@link Intent} will be 1825 * returned to the caller instead 1826 * @param callback Callback to invoke when the request completes, 1827 * null for no callback 1828 * @param handler {@link Handler} identifying the callback thread, 1829 * null for the main thread 1830 * @return An {@link AccountManagerFuture} which resolves to a Bundle 1831 * which is empty if properties were edited successfully, or 1832 * if no activity was specified, contains only {@link #KEY_INTENT} 1833 * needed to launch the authenticator's settings dialog. 1834 * If an error occurred, {@link AccountManagerFuture#getResult()} 1835 * throws: 1836 * <ul> 1837 * <li> {@link AuthenticatorException} if no authenticator was registered for 1838 * this account type or the authenticator failed to respond 1839 * <li> {@link OperationCanceledException} if the operation was canceled for 1840 * any reason, including the user canceling the settings dialog 1841 * <li> {@link IOException} if the authenticator experienced an I/O problem 1842 * updating settings, usually because of network trouble 1843 * </ul> 1844 */ 1845 public AccountManagerFuture<Bundle> editProperties(final String accountType, 1846 final Activity activity, final AccountManagerCallback<Bundle> callback, 1847 final Handler handler) { 1848 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 1849 return new AmsTask(activity, handler, callback) { 1850 public void doWork() throws RemoteException { 1851 mService.editProperties(mResponse, accountType, activity != null); 1852 } 1853 }.start(); 1854 } 1855 1856 /** 1857 * @hide 1858 * Checks if the given account exists on any of the users on the device. 1859 * Only the system process can call this method. 1860 * 1861 * @param account The account to check for existence. 1862 * @return whether any user has this account 1863 */ 1864 public boolean someUserHasAccount(@NonNull final Account account) { 1865 try { 1866 return mService.someUserHasAccount(account); 1867 } catch (RemoteException re) { 1868 throw new RuntimeException(re); 1869 } 1870 } 1871 1872 private void ensureNotOnMainThread() { 1873 final Looper looper = Looper.myLooper(); 1874 if (looper != null && looper == mContext.getMainLooper()) { 1875 final IllegalStateException exception = new IllegalStateException( 1876 "calling this from your main thread can lead to deadlock"); 1877 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs", 1878 exception); 1879 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) { 1880 throw exception; 1881 } 1882 } 1883 } 1884 1885 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback, 1886 final AccountManagerFuture<Bundle> future) { 1887 handler = handler == null ? mMainHandler : handler; 1888 handler.post(new Runnable() { 1889 public void run() { 1890 callback.run(future); 1891 } 1892 }); 1893 } 1894 1895 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener, 1896 final Account[] accounts) { 1897 final Account[] accountsCopy = new Account[accounts.length]; 1898 // send a copy to make sure that one doesn't 1899 // change what another sees 1900 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length); 1901 handler = (handler == null) ? mMainHandler : handler; 1902 handler.post(new Runnable() { 1903 public void run() { 1904 try { 1905 listener.onAccountsUpdated(accountsCopy); 1906 } catch (SQLException e) { 1907 // Better luck next time. If the problem was disk-full, 1908 // the STORAGE_OK intent will re-trigger the update. 1909 Log.e(TAG, "Can't update accounts", e); 1910 } 1911 } 1912 }); 1913 } 1914 1915 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> { 1916 final IAccountManagerResponse mResponse; 1917 final Handler mHandler; 1918 final AccountManagerCallback<Bundle> mCallback; 1919 final Activity mActivity; 1920 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) { 1921 super(new Callable<Bundle>() { 1922 public Bundle call() throws Exception { 1923 throw new IllegalStateException("this should never be called"); 1924 } 1925 }); 1926 1927 mHandler = handler; 1928 mCallback = callback; 1929 mActivity = activity; 1930 mResponse = new Response(); 1931 } 1932 1933 public final AccountManagerFuture<Bundle> start() { 1934 try { 1935 doWork(); 1936 } catch (RemoteException e) { 1937 setException(e); 1938 } 1939 return this; 1940 } 1941 1942 protected void set(Bundle bundle) { 1943 // TODO: somehow a null is being set as the result of the Future. Log this 1944 // case to help debug where this is occurring. When this bug is fixed this 1945 // condition statement should be removed. 1946 if (bundle == null) { 1947 Log.e(TAG, "the bundle must not be null", new Exception()); 1948 } 1949 super.set(bundle); 1950 } 1951 1952 public abstract void doWork() throws RemoteException; 1953 1954 private Bundle internalGetResult(Long timeout, TimeUnit unit) 1955 throws OperationCanceledException, IOException, AuthenticatorException { 1956 if (!isDone()) { 1957 ensureNotOnMainThread(); 1958 } 1959 try { 1960 if (timeout == null) { 1961 return get(); 1962 } else { 1963 return get(timeout, unit); 1964 } 1965 } catch (CancellationException e) { 1966 throw new OperationCanceledException(); 1967 } catch (TimeoutException e) { 1968 // fall through and cancel 1969 } catch (InterruptedException e) { 1970 // fall through and cancel 1971 } catch (ExecutionException e) { 1972 final Throwable cause = e.getCause(); 1973 if (cause instanceof IOException) { 1974 throw (IOException) cause; 1975 } else if (cause instanceof UnsupportedOperationException) { 1976 throw new AuthenticatorException(cause); 1977 } else if (cause instanceof AuthenticatorException) { 1978 throw (AuthenticatorException) cause; 1979 } else if (cause instanceof RuntimeException) { 1980 throw (RuntimeException) cause; 1981 } else if (cause instanceof Error) { 1982 throw (Error) cause; 1983 } else { 1984 throw new IllegalStateException(cause); 1985 } 1986 } finally { 1987 cancel(true /* interrupt if running */); 1988 } 1989 throw new OperationCanceledException(); 1990 } 1991 1992 public Bundle getResult() 1993 throws OperationCanceledException, IOException, AuthenticatorException { 1994 return internalGetResult(null, null); 1995 } 1996 1997 public Bundle getResult(long timeout, TimeUnit unit) 1998 throws OperationCanceledException, IOException, AuthenticatorException { 1999 return internalGetResult(timeout, unit); 2000 } 2001 2002 protected void done() { 2003 if (mCallback != null) { 2004 postToHandler(mHandler, mCallback, this); 2005 } 2006 } 2007 2008 /** Handles the responses from the AccountManager */ 2009 private class Response extends IAccountManagerResponse.Stub { 2010 public void onResult(Bundle bundle) { 2011 Intent intent = bundle.getParcelable(KEY_INTENT); 2012 if (intent != null && mActivity != null) { 2013 // since the user provided an Activity we will silently start intents 2014 // that we see 2015 mActivity.startActivity(intent); 2016 // leave the Future running to wait for the real response to this request 2017 } else if (bundle.getBoolean("retry")) { 2018 try { 2019 doWork(); 2020 } catch (RemoteException e) { 2021 // this will only happen if the system process is dead, which means 2022 // we will be dying ourselves 2023 } 2024 } else { 2025 set(bundle); 2026 } 2027 } 2028 2029 public void onError(int code, String message) { 2030 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED 2031 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) { 2032 // the authenticator indicated that this request was canceled or we were 2033 // forbidden to fulfill; cancel now 2034 cancel(true /* mayInterruptIfRunning */); 2035 return; 2036 } 2037 setException(convertErrorToException(code, message)); 2038 } 2039 } 2040 2041 } 2042 2043 private abstract class BaseFutureTask<T> extends FutureTask<T> { 2044 final public IAccountManagerResponse mResponse; 2045 final Handler mHandler; 2046 2047 public BaseFutureTask(Handler handler) { 2048 super(new Callable<T>() { 2049 public T call() throws Exception { 2050 throw new IllegalStateException("this should never be called"); 2051 } 2052 }); 2053 mHandler = handler; 2054 mResponse = new Response(); 2055 } 2056 2057 public abstract void doWork() throws RemoteException; 2058 2059 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException; 2060 2061 protected void postRunnableToHandler(Runnable runnable) { 2062 Handler handler = (mHandler == null) ? mMainHandler : mHandler; 2063 handler.post(runnable); 2064 } 2065 2066 protected void startTask() { 2067 try { 2068 doWork(); 2069 } catch (RemoteException e) { 2070 setException(e); 2071 } 2072 } 2073 2074 protected class Response extends IAccountManagerResponse.Stub { 2075 public void onResult(Bundle bundle) { 2076 try { 2077 T result = bundleToResult(bundle); 2078 if (result == null) { 2079 return; 2080 } 2081 set(result); 2082 return; 2083 } catch (ClassCastException e) { 2084 // we will set the exception below 2085 } catch (AuthenticatorException e) { 2086 // we will set the exception below 2087 } 2088 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response"); 2089 } 2090 2091 public void onError(int code, String message) { 2092 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED 2093 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) { 2094 // the authenticator indicated that this request was canceled or we were 2095 // forbidden to fulfill; cancel now 2096 cancel(true /* mayInterruptIfRunning */); 2097 return; 2098 } 2099 setException(convertErrorToException(code, message)); 2100 } 2101 } 2102 } 2103 2104 private abstract class Future2Task<T> 2105 extends BaseFutureTask<T> implements AccountManagerFuture<T> { 2106 final AccountManagerCallback<T> mCallback; 2107 public Future2Task(Handler handler, AccountManagerCallback<T> callback) { 2108 super(handler); 2109 mCallback = callback; 2110 } 2111 2112 protected void done() { 2113 if (mCallback != null) { 2114 postRunnableToHandler(new Runnable() { 2115 public void run() { 2116 mCallback.run(Future2Task.this); 2117 } 2118 }); 2119 } 2120 } 2121 2122 public Future2Task<T> start() { 2123 startTask(); 2124 return this; 2125 } 2126 2127 private T internalGetResult(Long timeout, TimeUnit unit) 2128 throws OperationCanceledException, IOException, AuthenticatorException { 2129 if (!isDone()) { 2130 ensureNotOnMainThread(); 2131 } 2132 try { 2133 if (timeout == null) { 2134 return get(); 2135 } else { 2136 return get(timeout, unit); 2137 } 2138 } catch (InterruptedException e) { 2139 // fall through and cancel 2140 } catch (TimeoutException e) { 2141 // fall through and cancel 2142 } catch (CancellationException e) { 2143 // fall through and cancel 2144 } catch (ExecutionException e) { 2145 final Throwable cause = e.getCause(); 2146 if (cause instanceof IOException) { 2147 throw (IOException) cause; 2148 } else if (cause instanceof UnsupportedOperationException) { 2149 throw new AuthenticatorException(cause); 2150 } else if (cause instanceof AuthenticatorException) { 2151 throw (AuthenticatorException) cause; 2152 } else if (cause instanceof RuntimeException) { 2153 throw (RuntimeException) cause; 2154 } else if (cause instanceof Error) { 2155 throw (Error) cause; 2156 } else { 2157 throw new IllegalStateException(cause); 2158 } 2159 } finally { 2160 cancel(true /* interrupt if running */); 2161 } 2162 throw new OperationCanceledException(); 2163 } 2164 2165 public T getResult() 2166 throws OperationCanceledException, IOException, AuthenticatorException { 2167 return internalGetResult(null, null); 2168 } 2169 2170 public T getResult(long timeout, TimeUnit unit) 2171 throws OperationCanceledException, IOException, AuthenticatorException { 2172 return internalGetResult(timeout, unit); 2173 } 2174 2175 } 2176 2177 private Exception convertErrorToException(int code, String message) { 2178 if (code == ERROR_CODE_NETWORK_ERROR) { 2179 return new IOException(message); 2180 } 2181 2182 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) { 2183 return new UnsupportedOperationException(message); 2184 } 2185 2186 if (code == ERROR_CODE_INVALID_RESPONSE) { 2187 return new AuthenticatorException(message); 2188 } 2189 2190 if (code == ERROR_CODE_BAD_ARGUMENTS) { 2191 return new IllegalArgumentException(message); 2192 } 2193 2194 return new AuthenticatorException(message); 2195 } 2196 2197 private class GetAuthTokenByTypeAndFeaturesTask 2198 extends AmsTask implements AccountManagerCallback<Bundle> { 2199 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType, 2200 final String[] features, Activity activityForPrompting, 2201 final Bundle addAccountOptions, final Bundle loginOptions, 2202 AccountManagerCallback<Bundle> callback, Handler handler) { 2203 super(activityForPrompting, handler, callback); 2204 if (accountType == null) throw new IllegalArgumentException("account type is null"); 2205 mAccountType = accountType; 2206 mAuthTokenType = authTokenType; 2207 mFeatures = features; 2208 mAddAccountOptions = addAccountOptions; 2209 mLoginOptions = loginOptions; 2210 mMyCallback = this; 2211 } 2212 volatile AccountManagerFuture<Bundle> mFuture = null; 2213 final String mAccountType; 2214 final String mAuthTokenType; 2215 final String[] mFeatures; 2216 final Bundle mAddAccountOptions; 2217 final Bundle mLoginOptions; 2218 final AccountManagerCallback<Bundle> mMyCallback; 2219 private volatile int mNumAccounts = 0; 2220 2221 public void doWork() throws RemoteException { 2222 getAccountsByTypeAndFeatures(mAccountType, mFeatures, 2223 new AccountManagerCallback<Account[]>() { 2224 public void run(AccountManagerFuture<Account[]> future) { 2225 Account[] accounts; 2226 try { 2227 accounts = future.getResult(); 2228 } catch (OperationCanceledException e) { 2229 setException(e); 2230 return; 2231 } catch (IOException e) { 2232 setException(e); 2233 return; 2234 } catch (AuthenticatorException e) { 2235 setException(e); 2236 return; 2237 } 2238 2239 mNumAccounts = accounts.length; 2240 2241 if (accounts.length == 0) { 2242 if (mActivity != null) { 2243 // no accounts, add one now. pretend that the user directly 2244 // made this request 2245 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures, 2246 mAddAccountOptions, mActivity, mMyCallback, mHandler); 2247 } else { 2248 // send result since we can't prompt to add an account 2249 Bundle result = new Bundle(); 2250 result.putString(KEY_ACCOUNT_NAME, null); 2251 result.putString(KEY_ACCOUNT_TYPE, null); 2252 result.putString(KEY_AUTHTOKEN, null); 2253 try { 2254 mResponse.onResult(result); 2255 } catch (RemoteException e) { 2256 // this will never happen 2257 } 2258 // we are done 2259 } 2260 } else if (accounts.length == 1) { 2261 // have a single account, return an authtoken for it 2262 if (mActivity == null) { 2263 mFuture = getAuthToken(accounts[0], mAuthTokenType, 2264 false /* notifyAuthFailure */, mMyCallback, mHandler); 2265 } else { 2266 mFuture = getAuthToken(accounts[0], 2267 mAuthTokenType, mLoginOptions, 2268 mActivity, mMyCallback, mHandler); 2269 } 2270 } else { 2271 if (mActivity != null) { 2272 IAccountManagerResponse chooseResponse = 2273 new IAccountManagerResponse.Stub() { 2274 public void onResult(Bundle value) throws RemoteException { 2275 Account account = new Account( 2276 value.getString(KEY_ACCOUNT_NAME), 2277 value.getString(KEY_ACCOUNT_TYPE)); 2278 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions, 2279 mActivity, mMyCallback, mHandler); 2280 } 2281 2282 public void onError(int errorCode, String errorMessage) 2283 throws RemoteException { 2284 mResponse.onError(errorCode, errorMessage); 2285 } 2286 }; 2287 // have many accounts, launch the chooser 2288 Intent intent = new Intent(); 2289 ComponentName componentName = ComponentName.unflattenFromString( 2290 Resources.getSystem().getString( 2291 R.string.config_chooseAccountActivity)); 2292 intent.setClassName(componentName.getPackageName(), 2293 componentName.getClassName()); 2294 intent.putExtra(KEY_ACCOUNTS, accounts); 2295 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE, 2296 new AccountManagerResponse(chooseResponse)); 2297 mActivity.startActivity(intent); 2298 // the result will arrive via the IAccountManagerResponse 2299 } else { 2300 // send result since we can't prompt to select an account 2301 Bundle result = new Bundle(); 2302 result.putString(KEY_ACCOUNTS, null); 2303 try { 2304 mResponse.onResult(result); 2305 } catch (RemoteException e) { 2306 // this will never happen 2307 } 2308 // we are done 2309 } 2310 } 2311 }}, mHandler); 2312 } 2313 2314 public void run(AccountManagerFuture<Bundle> future) { 2315 try { 2316 final Bundle result = future.getResult(); 2317 if (mNumAccounts == 0) { 2318 final String accountName = result.getString(KEY_ACCOUNT_NAME); 2319 final String accountType = result.getString(KEY_ACCOUNT_TYPE); 2320 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) { 2321 setException(new AuthenticatorException("account not in result")); 2322 return; 2323 } 2324 final Account account = new Account(accountName, accountType); 2325 mNumAccounts = 1; 2326 getAuthToken(account, mAuthTokenType, null /* options */, mActivity, 2327 mMyCallback, mHandler); 2328 return; 2329 } 2330 set(result); 2331 } catch (OperationCanceledException e) { 2332 cancel(true /* mayInterruptIfRUnning */); 2333 } catch (IOException e) { 2334 setException(e); 2335 } catch (AuthenticatorException e) { 2336 setException(e); 2337 } 2338 } 2339 } 2340 2341 /** 2342 * This convenience helper combines the functionality of 2343 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and 2344 * {@link #addAccount}. 2345 * 2346 * <p>This method gets a list of the accounts matching the 2347 * specified type and feature set; if there is exactly one, it is 2348 * used; if there are more than one, the user is prompted to pick one; 2349 * if there are none, the user is prompted to add one. Finally, 2350 * an auth token is acquired for the chosen account. 2351 * 2352 * <p>This method may be called from any thread, but the returned 2353 * {@link AccountManagerFuture} must not be used on the main thread. 2354 * 2355 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 2356 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 2357 * this function in API level 22. 2358 * 2359 * @param accountType The account type required 2360 * (see {@link #getAccountsByType}), must not be null 2361 * @param authTokenType The desired auth token type 2362 * (see {@link #getAuthToken}), must not be null 2363 * @param features Required features for the account 2364 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty 2365 * @param activity The {@link Activity} context to use for launching new 2366 * sub-Activities to prompt to add an account, select an account, 2367 * and/or enter a password, as necessary; used only to call 2368 * startActivity(); should not be null 2369 * @param addAccountOptions Authenticator-specific options to use for 2370 * adding new accounts; may be null or empty 2371 * @param getAuthTokenOptions Authenticator-specific options to use for 2372 * getting auth tokens; may be null or empty 2373 * @param callback Callback to invoke when the request completes, 2374 * null for no callback 2375 * @param handler {@link Handler} identifying the callback thread, 2376 * null for the main thread 2377 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2378 * at least the following fields: 2379 * <ul> 2380 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account 2381 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 2382 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 2383 * </ul> 2384 * 2385 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 2386 * <ul> 2387 * <li> {@link AuthenticatorException} if no authenticator was registered for 2388 * this account type or the authenticator failed to respond 2389 * <li> {@link OperationCanceledException} if the operation was canceled for 2390 * any reason, including the user canceling any operation 2391 * <li> {@link IOException} if the authenticator experienced an I/O problem 2392 * updating settings, usually because of network trouble 2393 * </ul> 2394 */ 2395 public AccountManagerFuture<Bundle> getAuthTokenByFeatures( 2396 final String accountType, final String authTokenType, final String[] features, 2397 final Activity activity, final Bundle addAccountOptions, 2398 final Bundle getAuthTokenOptions, 2399 final AccountManagerCallback<Bundle> callback, final Handler handler) { 2400 if (accountType == null) throw new IllegalArgumentException("account type is null"); 2401 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 2402 final GetAuthTokenByTypeAndFeaturesTask task = 2403 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features, 2404 activity, addAccountOptions, getAuthTokenOptions, callback, handler); 2405 task.start(); 2406 return task; 2407 } 2408 2409 /** 2410 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String, 2411 * String, String[], Bundle)}. 2412 * 2413 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of 2414 * accounts. 2415 * The caller will then typically start the activity by calling 2416 * <code>startActivityForResult(intent, ...);</code>. 2417 * <p> 2418 * On success the activity returns a Bundle with the account name and type specified using 2419 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}. 2420 * <p> 2421 * The most common case is to call this with one account type, e.g.: 2422 * <p> 2423 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, 2424 * null, null, null);</pre> 2425 * @param selectedAccount if specified, indicates that the {@link Account} is the currently 2426 * selected one, according to the caller's definition of selected. 2427 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be 2428 * shown. If not specified then this field will not limit the displayed accounts. 2429 * @param allowableAccountTypes an optional string array of account types. These are used 2430 * both to filter the shown accounts and to filter the list of account types that are shown 2431 * when adding an account. If not specified then this field will not limit the displayed 2432 * account types when adding an account. 2433 * @param alwaysPromptForAccount boolean that is ignored. 2434 * @param descriptionOverrideText if non-null this string is used as the description in the 2435 * accounts chooser screen rather than the default 2436 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount} 2437 * authTokenType parameter 2438 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount} 2439 * requiredFeatures parameter 2440 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options 2441 * parameter 2442 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow. 2443 */ 2444 @Deprecated 2445 static public Intent newChooseAccountIntent( 2446 Account selectedAccount, 2447 ArrayList<Account> allowableAccounts, 2448 String[] allowableAccountTypes, 2449 boolean alwaysPromptForAccount, 2450 String descriptionOverrideText, 2451 String addAccountAuthTokenType, 2452 String[] addAccountRequiredFeatures, 2453 Bundle addAccountOptions) { 2454 return newChooseAccountIntent( 2455 selectedAccount, 2456 allowableAccounts, 2457 allowableAccountTypes, 2458 descriptionOverrideText, 2459 addAccountAuthTokenType, 2460 addAccountRequiredFeatures, 2461 addAccountOptions); 2462 } 2463 2464 /** 2465 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of 2466 * accounts. 2467 * The caller will then typically start the activity by calling 2468 * <code>startActivityForResult(intent, ...);</code>. 2469 * <p> 2470 * On success the activity returns a Bundle with the account name and type specified using 2471 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}. 2472 * <p> 2473 * The most common case is to call this with one account type, e.g.: 2474 * <p> 2475 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null, 2476 * null);</pre> 2477 * @param selectedAccount if specified, indicates that the {@link Account} is the currently 2478 * selected one, according to the caller's definition of selected. 2479 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be 2480 * shown. If not specified then this field will not limit the displayed accounts. 2481 * @param allowableAccountTypes an optional string array of account types. These are used 2482 * both to filter the shown accounts and to filter the list of account types that are shown 2483 * when adding an account. If not specified then this field will not limit the displayed 2484 * account types when adding an account. 2485 * @param descriptionOverrideText if non-null this string is used as the description in the 2486 * accounts chooser screen rather than the default 2487 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount} 2488 * authTokenType parameter 2489 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount} 2490 * requiredFeatures parameter 2491 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options 2492 * parameter 2493 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow. 2494 */ 2495 static public Intent newChooseAccountIntent( 2496 Account selectedAccount, 2497 List<Account> allowableAccounts, 2498 String[] allowableAccountTypes, 2499 String descriptionOverrideText, 2500 String addAccountAuthTokenType, 2501 String[] addAccountRequiredFeatures, 2502 Bundle addAccountOptions) { 2503 Intent intent = new Intent(); 2504 ComponentName componentName = ComponentName.unflattenFromString( 2505 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity)); 2506 intent.setClassName(componentName.getPackageName(), 2507 componentName.getClassName()); 2508 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST, 2509 allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts)); 2510 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY, 2511 allowableAccountTypes); 2512 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE, 2513 addAccountOptions); 2514 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount); 2515 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE, 2516 descriptionOverrideText); 2517 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING, 2518 addAccountAuthTokenType); 2519 intent.putExtra( 2520 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY, 2521 addAccountRequiredFeatures); 2522 return intent; 2523 } 2524 2525 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners = 2526 Maps.newHashMap(); 2527 2528 /** 2529 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent 2530 * so that it can read the updated list of accounts and send them to the listener 2531 * in mAccountsUpdatedListeners. 2532 */ 2533 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() { 2534 public void onReceive(final Context context, final Intent intent) { 2535 final Account[] accounts = getAccounts(); 2536 // send the result to the listeners 2537 synchronized (mAccountsUpdatedListeners) { 2538 for (Map.Entry<OnAccountsUpdateListener, Handler> entry : 2539 mAccountsUpdatedListeners.entrySet()) { 2540 postToHandler(entry.getValue(), entry.getKey(), accounts); 2541 } 2542 } 2543 } 2544 }; 2545 2546 /** 2547 * Adds an {@link OnAccountsUpdateListener} to this instance of the 2548 * {@link AccountManager}. This listener will be notified whenever the 2549 * list of accounts on the device changes. 2550 * 2551 * <p>As long as this listener is present, the AccountManager instance 2552 * will not be garbage-collected, and neither will the {@link Context} 2553 * used to retrieve it, which may be a large Activity instance. To avoid 2554 * memory leaks, you must remove this listener before then. Normally 2555 * listeners are added in an Activity or Service's {@link Activity#onCreate} 2556 * and removed in {@link Activity#onDestroy}. 2557 * 2558 * <p>The listener will only be informed of accounts that would be returned 2559 * to the caller via {@link #getAccounts()}. Typically this means that to 2560 * get any accounts, the caller will need to be grated the GET_ACCOUNTS 2561 * permission. 2562 * 2563 * <p>It is safe to call this method from the main thread. 2564 * 2565 * @param listener The listener to send notifications to 2566 * @param handler {@link Handler} identifying the thread to use 2567 * for notifications, null for the main thread 2568 * @param updateImmediately If true, the listener will be invoked 2569 * (on the handler thread) right away with the current account list 2570 * @throws IllegalArgumentException if listener is null 2571 * @throws IllegalStateException if listener was already added 2572 */ 2573 @RequiresPermission(GET_ACCOUNTS) 2574 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener, 2575 Handler handler, boolean updateImmediately) { 2576 if (listener == null) { 2577 throw new IllegalArgumentException("the listener is null"); 2578 } 2579 synchronized (mAccountsUpdatedListeners) { 2580 if (mAccountsUpdatedListeners.containsKey(listener)) { 2581 throw new IllegalStateException("this listener is already added"); 2582 } 2583 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty(); 2584 2585 mAccountsUpdatedListeners.put(listener, handler); 2586 2587 if (wasEmpty) { 2588 // Register a broadcast receiver to monitor account changes 2589 IntentFilter intentFilter = new IntentFilter(); 2590 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION); 2591 // To recover from disk-full. 2592 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); 2593 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter); 2594 } 2595 } 2596 2597 if (updateImmediately) { 2598 postToHandler(handler, listener, getAccounts()); 2599 } 2600 } 2601 2602 /** 2603 * Removes an {@link OnAccountsUpdateListener} previously registered with 2604 * {@link #addOnAccountsUpdatedListener}. The listener will no longer 2605 * receive notifications of account changes. 2606 * 2607 * <p>It is safe to call this method from the main thread. 2608 * 2609 * <p>No permission is required to call this method. 2610 * 2611 * @param listener The previously added listener to remove 2612 * @throws IllegalArgumentException if listener is null 2613 * @throws IllegalStateException if listener was not already added 2614 */ 2615 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) { 2616 if (listener == null) throw new IllegalArgumentException("listener is null"); 2617 synchronized (mAccountsUpdatedListeners) { 2618 if (!mAccountsUpdatedListeners.containsKey(listener)) { 2619 Log.e(TAG, "Listener was not previously added"); 2620 return; 2621 } 2622 mAccountsUpdatedListeners.remove(listener); 2623 if (mAccountsUpdatedListeners.isEmpty()) { 2624 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver); 2625 } 2626 } 2627 } 2628 2629 /** 2630 * Asks the user to authenticate with an account of a specified type. The 2631 * authenticator for this account type processes this request with the 2632 * appropriate user interface. If the user does elect to authenticate with a 2633 * new account, a bundle of session data for installing the account later is 2634 * returned with optional account password and account status token. 2635 * <p> 2636 * This method may be called from any thread, but the returned 2637 * {@link AccountManagerFuture} must not be used on the main thread. 2638 * <p> 2639 * <p> 2640 * <b>NOTE:</b> The account will not be installed to the device by calling 2641 * this api alone. #finishSession should be called after this to install the 2642 * account on device. 2643 * 2644 * @param accountType The type of account to add; must not be null 2645 * @param authTokenType The type of auth token (see {@link #getAuthToken}) 2646 * this account will need to be able to generate, null for none 2647 * @param requiredFeatures The features (see {@link #hasFeatures}) this 2648 * account must have, null for none 2649 * @param options Authenticator-specific options for the request, may be 2650 * null or empty 2651 * @param activity The {@link Activity} context to use for launching a new 2652 * authenticator-defined sub-Activity to prompt the user to 2653 * create an account; used only to call startActivity(); if null, 2654 * the prompt will not be launched directly, but the necessary 2655 * {@link Intent} will be returned to the caller instead 2656 * @param callback Callback to invoke when the request completes, null for 2657 * no callback 2658 * @param handler {@link Handler} identifying the callback thread, null for 2659 * the main thread 2660 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2661 * these fields if activity was specified and user was authenticated 2662 * with an account: 2663 * <ul> 2664 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for 2665 * adding the the to the device later. 2666 * <li>{@link #KEY_PASSWORD} - optional, the password or password 2667 * hash of the account. 2668 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check 2669 * status of the account 2670 * </ul> 2671 * If no activity was specified, the returned Bundle contains only 2672 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 2673 * actual account creation process. If authenticator doesn't support 2674 * this method, the returned Bundle contains only 2675 * {@link #KEY_ACCOUNT_SESSION_BUNDLE} with encrypted 2676 * {@code options} needed to add account later. If an error 2677 * occurred, {@link AccountManagerFuture#getResult()} throws: 2678 * <ul> 2679 * <li>{@link AuthenticatorException} if no authenticator was 2680 * registered for this account type or the authenticator failed to 2681 * respond 2682 * <li>{@link OperationCanceledException} if the operation was 2683 * canceled for any reason, including the user canceling the 2684 * creation process or adding accounts (of this type) has been 2685 * disabled by policy 2686 * <li>{@link IOException} if the authenticator experienced an I/O 2687 * problem creating a new account, usually because of network 2688 * trouble 2689 * </ul> 2690 * @see #finishSession 2691 * @hide 2692 */ 2693 @SystemApi 2694 public AccountManagerFuture<Bundle> startAddAccountSession( 2695 final String accountType, 2696 final String authTokenType, 2697 final String[] requiredFeatures, 2698 final Bundle options, 2699 final Activity activity, 2700 AccountManagerCallback<Bundle> callback, 2701 Handler handler) { 2702 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 2703 final Bundle optionsIn = new Bundle(); 2704 if (options != null) { 2705 optionsIn.putAll(options); 2706 } 2707 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 2708 2709 return new AmsTask(activity, handler, callback) { 2710 @Override 2711 public void doWork() throws RemoteException { 2712 mService.startAddAccountSession( 2713 mResponse, 2714 accountType, 2715 authTokenType, 2716 requiredFeatures, 2717 activity != null, 2718 optionsIn); 2719 } 2720 }.start(); 2721 } 2722 2723 /** 2724 * Asks the user to enter a new password for an account but not updating the 2725 * saved credentials for the account until {@link #finishSession} is called. 2726 * <p> 2727 * This method may be called from any thread, but the returned 2728 * {@link AccountManagerFuture} must not be used on the main thread. 2729 * <p> 2730 * <b>NOTE:</b> The saved credentials for the account alone will not be 2731 * updated by calling this API alone. #finishSession should be called after 2732 * this to update local credentials 2733 * 2734 * @param account The account to update credentials for 2735 * @param authTokenType The credentials entered must allow an auth token of 2736 * this type to be created (but no actual auth token is 2737 * returned); may be null 2738 * @param options Authenticator-specific options for the request; may be 2739 * null or empty 2740 * @param activity The {@link Activity} context to use for launching a new 2741 * authenticator-defined sub-Activity to prompt the user to enter 2742 * a password; used only to call startActivity(); if null, the 2743 * prompt will not be launched directly, but the necessary 2744 * {@link Intent} will be returned to the caller instead 2745 * @param callback Callback to invoke when the request completes, null for 2746 * no callback 2747 * @param handler {@link Handler} identifying the callback thread, null for 2748 * the main thread 2749 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2750 * these fields if an activity was supplied and user was 2751 * successfully re-authenticated to the account: 2752 * <ul> 2753 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for 2754 * updating the local credentials on device later. 2755 * <li>{@link #KEY_PASSWORD} - optional, the password or password 2756 * hash of the account 2757 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check 2758 * status of the account 2759 * </ul> 2760 * If no activity was specified, the returned Bundle contains 2761 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 2762 * password prompt. If an error occurred, 2763 * {@link AccountManagerFuture#getResult()} throws: 2764 * <ul> 2765 * <li>{@link AuthenticatorException} if the authenticator failed to 2766 * respond 2767 * <li>{@link OperationCanceledException} if the operation was 2768 * canceled for any reason, including the user canceling the 2769 * password prompt 2770 * <li>{@link IOException} if the authenticator experienced an I/O 2771 * problem verifying the password, usually because of network 2772 * trouble 2773 * </ul> 2774 * @see #finishSession 2775 * @hide 2776 */ 2777 @SystemApi 2778 public AccountManagerFuture<Bundle> startUpdateCredentialsSession( 2779 final Account account, 2780 final String authTokenType, 2781 final Bundle options, 2782 final Activity activity, 2783 final AccountManagerCallback<Bundle> callback, 2784 final Handler handler) { 2785 if (account == null) { 2786 throw new IllegalArgumentException("account is null"); 2787 } 2788 return new AmsTask(activity, handler, callback) { 2789 @Override 2790 public void doWork() throws RemoteException { 2791 mService.startUpdateCredentialsSession( 2792 mResponse, 2793 account, 2794 authTokenType, 2795 activity != null, 2796 options); 2797 } 2798 }.start(); 2799 } 2800 2801 /** 2802 * Finishes the session started by {@link #startAddAccountSession} or 2803 * {@link #startUpdateCredentialsSession}. This will either add the account 2804 * to AccountManager or update the local credentials stored. 2805 * <p> 2806 * This method may be called from any thread, but the returned 2807 * {@link AccountManagerFuture} must not be used on the main thread. 2808 * 2809 * @param sessionBundle a {@link Bundle} created by {@link #startAddAccountSession} or 2810 * {@link #startUpdateCredentialsSession} 2811 * @param activity The {@link Activity} context to use for launching a new 2812 * authenticator-defined sub-Activity to prompt the user to 2813 * create an account or reauthenticate existing account; used 2814 * only to call startActivity(); if null, the prompt will not 2815 * be launched directly, but the necessary {@link Intent} will 2816 * be returned to the caller instead 2817 * @param callback Callback to invoke when the request completes, null for 2818 * no callback 2819 * @param handler {@link Handler} identifying the callback thread, null for 2820 * the main thread 2821 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2822 * these fields if an activity was supplied and an account was added 2823 * to device or local credentials were updated:: 2824 * <ul> 2825 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account created 2826 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account 2827 * </ul> 2828 * If no activity was specified and additional information is needed 2829 * from user, the returned Bundle may contains only 2830 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 2831 * actual account creation process. If an error occurred, 2832 * {@link AccountManagerFuture#getResult()} throws: 2833 * <ul> 2834 * <li>{@link AuthenticatorException} if no authenticator was 2835 * registered for this account type or the authenticator failed to 2836 * respond 2837 * <li>{@link OperationCanceledException} if the operation was 2838 * canceled for any reason, including the user canceling the 2839 * creation process or adding accounts (of this type) has been 2840 * disabled by policy 2841 * <li>{@link IOException} if the authenticator experienced an I/O 2842 * problem creating a new account, usually because of network 2843 * trouble 2844 * </ul> 2845 * @see #startAddAccountSession and #startUpdateCredentialsSession 2846 * @hide 2847 */ 2848 @SystemApi 2849 public AccountManagerFuture<Bundle> finishSession( 2850 final Bundle sessionBundle, 2851 final Activity activity, 2852 AccountManagerCallback<Bundle> callback, 2853 Handler handler) { 2854 if (sessionBundle == null) { 2855 throw new IllegalArgumentException("sessionBundle is null"); 2856 } 2857 2858 /* Add information required by add account flow */ 2859 final Bundle appInfo = new Bundle(); 2860 appInfo.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 2861 2862 return new AmsTask(activity, handler, callback) { 2863 @Override 2864 public void doWork() throws RemoteException { 2865 mService.finishSession(mResponse, sessionBundle, activity != null, appInfo); 2866 } 2867 }.start(); 2868 } 2869 2870 /** 2871 * Checks whether {@link #updateCredentials} or {@link #startUpdateCredentialsSession} should be 2872 * called with respect to the specified account. 2873 * <p> 2874 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must 2875 * not be used on the main thread. 2876 * 2877 * @param account The {@link Account} to be checked whether {@link #updateCredentials} or 2878 * {@link #startUpdateCredentialsSession} should be called 2879 * @param statusToken a String of token to check account staus 2880 * @param callback Callback to invoke when the request completes, null for no callback 2881 * @param handler {@link Handler} identifying the callback thread, null for the main thread 2882 * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the credentials 2883 * of the account should be updated. 2884 * @hide 2885 */ 2886 @SystemApi 2887 public AccountManagerFuture<Boolean> isCredentialsUpdateSuggested( 2888 final Account account, 2889 final String statusToken, 2890 AccountManagerCallback<Boolean> callback, 2891 Handler handler) { 2892 if (account == null) { 2893 throw new IllegalArgumentException("account is null"); 2894 } 2895 2896 if (TextUtils.isEmpty(statusToken)) { 2897 throw new IllegalArgumentException("status token is empty"); 2898 } 2899 2900 return new Future2Task<Boolean>(handler, callback) { 2901 public void doWork() throws RemoteException { 2902 mService.isCredentialsUpdateSuggested( 2903 mResponse, 2904 account, 2905 statusToken); 2906 } 2907 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException { 2908 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) { 2909 throw new AuthenticatorException("no result in response"); 2910 } 2911 return bundle.getBoolean(KEY_BOOLEAN_RESULT); 2912 } 2913 }.start(); 2914 } 2915} 2916