AccountManager.java revision a578d11470d2c782bc8b54bc2a9154e7f5b68354
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.accounts; 18 19import android.annotation.NonNull; 20import android.annotation.RequiresPermission; 21import android.annotation.Size; 22import android.annotation.SystemApi; 23import android.app.Activity; 24import android.content.BroadcastReceiver; 25import android.content.ComponentName; 26import android.content.Context; 27import android.content.Intent; 28import android.content.IntentFilter; 29import android.content.res.Resources; 30import android.database.SQLException; 31import android.os.Build; 32import android.os.Bundle; 33import android.os.Handler; 34import android.os.Looper; 35import android.os.Parcelable; 36import android.os.Process; 37import android.os.RemoteException; 38import android.os.UserHandle; 39import android.text.TextUtils; 40import android.util.Log; 41 42import com.android.internal.R; 43import com.google.android.collect.Maps; 44 45import java.io.IOException; 46import java.util.ArrayList; 47import java.util.HashMap; 48import java.util.List; 49import java.util.Map; 50import java.util.concurrent.Callable; 51import java.util.concurrent.CancellationException; 52import java.util.concurrent.ExecutionException; 53import java.util.concurrent.FutureTask; 54import java.util.concurrent.TimeUnit; 55import java.util.concurrent.TimeoutException; 56 57import static android.Manifest.permission.GET_ACCOUNTS; 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 private void ensureNotOnMainThread() { 1857 final Looper looper = Looper.myLooper(); 1858 if (looper != null && looper == mContext.getMainLooper()) { 1859 final IllegalStateException exception = new IllegalStateException( 1860 "calling this from your main thread can lead to deadlock"); 1861 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs", 1862 exception); 1863 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) { 1864 throw exception; 1865 } 1866 } 1867 } 1868 1869 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback, 1870 final AccountManagerFuture<Bundle> future) { 1871 handler = handler == null ? mMainHandler : handler; 1872 handler.post(new Runnable() { 1873 public void run() { 1874 callback.run(future); 1875 } 1876 }); 1877 } 1878 1879 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener, 1880 final Account[] accounts) { 1881 final Account[] accountsCopy = new Account[accounts.length]; 1882 // send a copy to make sure that one doesn't 1883 // change what another sees 1884 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length); 1885 handler = (handler == null) ? mMainHandler : handler; 1886 handler.post(new Runnable() { 1887 public void run() { 1888 try { 1889 listener.onAccountsUpdated(accountsCopy); 1890 } catch (SQLException e) { 1891 // Better luck next time. If the problem was disk-full, 1892 // the STORAGE_OK intent will re-trigger the update. 1893 Log.e(TAG, "Can't update accounts", e); 1894 } 1895 } 1896 }); 1897 } 1898 1899 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> { 1900 final IAccountManagerResponse mResponse; 1901 final Handler mHandler; 1902 final AccountManagerCallback<Bundle> mCallback; 1903 final Activity mActivity; 1904 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) { 1905 super(new Callable<Bundle>() { 1906 public Bundle call() throws Exception { 1907 throw new IllegalStateException("this should never be called"); 1908 } 1909 }); 1910 1911 mHandler = handler; 1912 mCallback = callback; 1913 mActivity = activity; 1914 mResponse = new Response(); 1915 } 1916 1917 public final AccountManagerFuture<Bundle> start() { 1918 try { 1919 doWork(); 1920 } catch (RemoteException e) { 1921 setException(e); 1922 } 1923 return this; 1924 } 1925 1926 protected void set(Bundle bundle) { 1927 // TODO: somehow a null is being set as the result of the Future. Log this 1928 // case to help debug where this is occurring. When this bug is fixed this 1929 // condition statement should be removed. 1930 if (bundle == null) { 1931 Log.e(TAG, "the bundle must not be null", new Exception()); 1932 } 1933 super.set(bundle); 1934 } 1935 1936 public abstract void doWork() throws RemoteException; 1937 1938 private Bundle internalGetResult(Long timeout, TimeUnit unit) 1939 throws OperationCanceledException, IOException, AuthenticatorException { 1940 if (!isDone()) { 1941 ensureNotOnMainThread(); 1942 } 1943 try { 1944 if (timeout == null) { 1945 return get(); 1946 } else { 1947 return get(timeout, unit); 1948 } 1949 } catch (CancellationException e) { 1950 throw new OperationCanceledException(); 1951 } catch (TimeoutException e) { 1952 // fall through and cancel 1953 } catch (InterruptedException e) { 1954 // fall through and cancel 1955 } catch (ExecutionException e) { 1956 final Throwable cause = e.getCause(); 1957 if (cause instanceof IOException) { 1958 throw (IOException) cause; 1959 } else if (cause instanceof UnsupportedOperationException) { 1960 throw new AuthenticatorException(cause); 1961 } else if (cause instanceof AuthenticatorException) { 1962 throw (AuthenticatorException) cause; 1963 } else if (cause instanceof RuntimeException) { 1964 throw (RuntimeException) cause; 1965 } else if (cause instanceof Error) { 1966 throw (Error) cause; 1967 } else { 1968 throw new IllegalStateException(cause); 1969 } 1970 } finally { 1971 cancel(true /* interrupt if running */); 1972 } 1973 throw new OperationCanceledException(); 1974 } 1975 1976 public Bundle getResult() 1977 throws OperationCanceledException, IOException, AuthenticatorException { 1978 return internalGetResult(null, null); 1979 } 1980 1981 public Bundle getResult(long timeout, TimeUnit unit) 1982 throws OperationCanceledException, IOException, AuthenticatorException { 1983 return internalGetResult(timeout, unit); 1984 } 1985 1986 protected void done() { 1987 if (mCallback != null) { 1988 postToHandler(mHandler, mCallback, this); 1989 } 1990 } 1991 1992 /** Handles the responses from the AccountManager */ 1993 private class Response extends IAccountManagerResponse.Stub { 1994 public void onResult(Bundle bundle) { 1995 Intent intent = bundle.getParcelable(KEY_INTENT); 1996 if (intent != null && mActivity != null) { 1997 // since the user provided an Activity we will silently start intents 1998 // that we see 1999 mActivity.startActivity(intent); 2000 // leave the Future running to wait for the real response to this request 2001 } else if (bundle.getBoolean("retry")) { 2002 try { 2003 doWork(); 2004 } catch (RemoteException e) { 2005 // this will only happen if the system process is dead, which means 2006 // we will be dying ourselves 2007 } 2008 } else { 2009 set(bundle); 2010 } 2011 } 2012 2013 public void onError(int code, String message) { 2014 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED 2015 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) { 2016 // the authenticator indicated that this request was canceled or we were 2017 // forbidden to fulfill; cancel now 2018 cancel(true /* mayInterruptIfRunning */); 2019 return; 2020 } 2021 setException(convertErrorToException(code, message)); 2022 } 2023 } 2024 2025 } 2026 2027 private abstract class BaseFutureTask<T> extends FutureTask<T> { 2028 final public IAccountManagerResponse mResponse; 2029 final Handler mHandler; 2030 2031 public BaseFutureTask(Handler handler) { 2032 super(new Callable<T>() { 2033 public T call() throws Exception { 2034 throw new IllegalStateException("this should never be called"); 2035 } 2036 }); 2037 mHandler = handler; 2038 mResponse = new Response(); 2039 } 2040 2041 public abstract void doWork() throws RemoteException; 2042 2043 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException; 2044 2045 protected void postRunnableToHandler(Runnable runnable) { 2046 Handler handler = (mHandler == null) ? mMainHandler : mHandler; 2047 handler.post(runnable); 2048 } 2049 2050 protected void startTask() { 2051 try { 2052 doWork(); 2053 } catch (RemoteException e) { 2054 setException(e); 2055 } 2056 } 2057 2058 protected class Response extends IAccountManagerResponse.Stub { 2059 public void onResult(Bundle bundle) { 2060 try { 2061 T result = bundleToResult(bundle); 2062 if (result == null) { 2063 return; 2064 } 2065 set(result); 2066 return; 2067 } catch (ClassCastException e) { 2068 // we will set the exception below 2069 } catch (AuthenticatorException e) { 2070 // we will set the exception below 2071 } 2072 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response"); 2073 } 2074 2075 public void onError(int code, String message) { 2076 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED 2077 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) { 2078 // the authenticator indicated that this request was canceled or we were 2079 // forbidden to fulfill; cancel now 2080 cancel(true /* mayInterruptIfRunning */); 2081 return; 2082 } 2083 setException(convertErrorToException(code, message)); 2084 } 2085 } 2086 } 2087 2088 private abstract class Future2Task<T> 2089 extends BaseFutureTask<T> implements AccountManagerFuture<T> { 2090 final AccountManagerCallback<T> mCallback; 2091 public Future2Task(Handler handler, AccountManagerCallback<T> callback) { 2092 super(handler); 2093 mCallback = callback; 2094 } 2095 2096 protected void done() { 2097 if (mCallback != null) { 2098 postRunnableToHandler(new Runnable() { 2099 public void run() { 2100 mCallback.run(Future2Task.this); 2101 } 2102 }); 2103 } 2104 } 2105 2106 public Future2Task<T> start() { 2107 startTask(); 2108 return this; 2109 } 2110 2111 private T internalGetResult(Long timeout, TimeUnit unit) 2112 throws OperationCanceledException, IOException, AuthenticatorException { 2113 if (!isDone()) { 2114 ensureNotOnMainThread(); 2115 } 2116 try { 2117 if (timeout == null) { 2118 return get(); 2119 } else { 2120 return get(timeout, unit); 2121 } 2122 } catch (InterruptedException e) { 2123 // fall through and cancel 2124 } catch (TimeoutException e) { 2125 // fall through and cancel 2126 } catch (CancellationException e) { 2127 // fall through and cancel 2128 } catch (ExecutionException e) { 2129 final Throwable cause = e.getCause(); 2130 if (cause instanceof IOException) { 2131 throw (IOException) cause; 2132 } else if (cause instanceof UnsupportedOperationException) { 2133 throw new AuthenticatorException(cause); 2134 } else if (cause instanceof AuthenticatorException) { 2135 throw (AuthenticatorException) cause; 2136 } else if (cause instanceof RuntimeException) { 2137 throw (RuntimeException) cause; 2138 } else if (cause instanceof Error) { 2139 throw (Error) cause; 2140 } else { 2141 throw new IllegalStateException(cause); 2142 } 2143 } finally { 2144 cancel(true /* interrupt if running */); 2145 } 2146 throw new OperationCanceledException(); 2147 } 2148 2149 public T getResult() 2150 throws OperationCanceledException, IOException, AuthenticatorException { 2151 return internalGetResult(null, null); 2152 } 2153 2154 public T getResult(long timeout, TimeUnit unit) 2155 throws OperationCanceledException, IOException, AuthenticatorException { 2156 return internalGetResult(timeout, unit); 2157 } 2158 2159 } 2160 2161 private Exception convertErrorToException(int code, String message) { 2162 if (code == ERROR_CODE_NETWORK_ERROR) { 2163 return new IOException(message); 2164 } 2165 2166 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) { 2167 return new UnsupportedOperationException(message); 2168 } 2169 2170 if (code == ERROR_CODE_INVALID_RESPONSE) { 2171 return new AuthenticatorException(message); 2172 } 2173 2174 if (code == ERROR_CODE_BAD_ARGUMENTS) { 2175 return new IllegalArgumentException(message); 2176 } 2177 2178 return new AuthenticatorException(message); 2179 } 2180 2181 private class GetAuthTokenByTypeAndFeaturesTask 2182 extends AmsTask implements AccountManagerCallback<Bundle> { 2183 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType, 2184 final String[] features, Activity activityForPrompting, 2185 final Bundle addAccountOptions, final Bundle loginOptions, 2186 AccountManagerCallback<Bundle> callback, Handler handler) { 2187 super(activityForPrompting, handler, callback); 2188 if (accountType == null) throw new IllegalArgumentException("account type is null"); 2189 mAccountType = accountType; 2190 mAuthTokenType = authTokenType; 2191 mFeatures = features; 2192 mAddAccountOptions = addAccountOptions; 2193 mLoginOptions = loginOptions; 2194 mMyCallback = this; 2195 } 2196 volatile AccountManagerFuture<Bundle> mFuture = null; 2197 final String mAccountType; 2198 final String mAuthTokenType; 2199 final String[] mFeatures; 2200 final Bundle mAddAccountOptions; 2201 final Bundle mLoginOptions; 2202 final AccountManagerCallback<Bundle> mMyCallback; 2203 private volatile int mNumAccounts = 0; 2204 2205 public void doWork() throws RemoteException { 2206 getAccountsByTypeAndFeatures(mAccountType, mFeatures, 2207 new AccountManagerCallback<Account[]>() { 2208 public void run(AccountManagerFuture<Account[]> future) { 2209 Account[] accounts; 2210 try { 2211 accounts = future.getResult(); 2212 } catch (OperationCanceledException e) { 2213 setException(e); 2214 return; 2215 } catch (IOException e) { 2216 setException(e); 2217 return; 2218 } catch (AuthenticatorException e) { 2219 setException(e); 2220 return; 2221 } 2222 2223 mNumAccounts = accounts.length; 2224 2225 if (accounts.length == 0) { 2226 if (mActivity != null) { 2227 // no accounts, add one now. pretend that the user directly 2228 // made this request 2229 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures, 2230 mAddAccountOptions, mActivity, mMyCallback, mHandler); 2231 } else { 2232 // send result since we can't prompt to add an account 2233 Bundle result = new Bundle(); 2234 result.putString(KEY_ACCOUNT_NAME, null); 2235 result.putString(KEY_ACCOUNT_TYPE, null); 2236 result.putString(KEY_AUTHTOKEN, null); 2237 try { 2238 mResponse.onResult(result); 2239 } catch (RemoteException e) { 2240 // this will never happen 2241 } 2242 // we are done 2243 } 2244 } else if (accounts.length == 1) { 2245 // have a single account, return an authtoken for it 2246 if (mActivity == null) { 2247 mFuture = getAuthToken(accounts[0], mAuthTokenType, 2248 false /* notifyAuthFailure */, mMyCallback, mHandler); 2249 } else { 2250 mFuture = getAuthToken(accounts[0], 2251 mAuthTokenType, mLoginOptions, 2252 mActivity, mMyCallback, mHandler); 2253 } 2254 } else { 2255 if (mActivity != null) { 2256 IAccountManagerResponse chooseResponse = 2257 new IAccountManagerResponse.Stub() { 2258 public void onResult(Bundle value) throws RemoteException { 2259 Account account = new Account( 2260 value.getString(KEY_ACCOUNT_NAME), 2261 value.getString(KEY_ACCOUNT_TYPE)); 2262 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions, 2263 mActivity, mMyCallback, mHandler); 2264 } 2265 2266 public void onError(int errorCode, String errorMessage) 2267 throws RemoteException { 2268 mResponse.onError(errorCode, errorMessage); 2269 } 2270 }; 2271 // have many accounts, launch the chooser 2272 Intent intent = new Intent(); 2273 ComponentName componentName = ComponentName.unflattenFromString( 2274 Resources.getSystem().getString( 2275 R.string.config_chooseAccountActivity)); 2276 intent.setClassName(componentName.getPackageName(), 2277 componentName.getClassName()); 2278 intent.putExtra(KEY_ACCOUNTS, accounts); 2279 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE, 2280 new AccountManagerResponse(chooseResponse)); 2281 mActivity.startActivity(intent); 2282 // the result will arrive via the IAccountManagerResponse 2283 } else { 2284 // send result since we can't prompt to select an account 2285 Bundle result = new Bundle(); 2286 result.putString(KEY_ACCOUNTS, null); 2287 try { 2288 mResponse.onResult(result); 2289 } catch (RemoteException e) { 2290 // this will never happen 2291 } 2292 // we are done 2293 } 2294 } 2295 }}, mHandler); 2296 } 2297 2298 public void run(AccountManagerFuture<Bundle> future) { 2299 try { 2300 final Bundle result = future.getResult(); 2301 if (mNumAccounts == 0) { 2302 final String accountName = result.getString(KEY_ACCOUNT_NAME); 2303 final String accountType = result.getString(KEY_ACCOUNT_TYPE); 2304 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) { 2305 setException(new AuthenticatorException("account not in result")); 2306 return; 2307 } 2308 final Account account = new Account(accountName, accountType); 2309 mNumAccounts = 1; 2310 getAuthToken(account, mAuthTokenType, null /* options */, mActivity, 2311 mMyCallback, mHandler); 2312 return; 2313 } 2314 set(result); 2315 } catch (OperationCanceledException e) { 2316 cancel(true /* mayInterruptIfRUnning */); 2317 } catch (IOException e) { 2318 setException(e); 2319 } catch (AuthenticatorException e) { 2320 setException(e); 2321 } 2322 } 2323 } 2324 2325 /** 2326 * This convenience helper combines the functionality of 2327 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and 2328 * {@link #addAccount}. 2329 * 2330 * <p>This method gets a list of the accounts matching the 2331 * specified type and feature set; if there is exactly one, it is 2332 * used; if there are more than one, the user is prompted to pick one; 2333 * if there are none, the user is prompted to add one. Finally, 2334 * an auth token is acquired for the chosen account. 2335 * 2336 * <p>This method may be called from any thread, but the returned 2337 * {@link AccountManagerFuture} must not be used on the main thread. 2338 * 2339 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before, 2340 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for 2341 * this function in API level 22. 2342 * 2343 * @param accountType The account type required 2344 * (see {@link #getAccountsByType}), must not be null 2345 * @param authTokenType The desired auth token type 2346 * (see {@link #getAuthToken}), must not be null 2347 * @param features Required features for the account 2348 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty 2349 * @param activity The {@link Activity} context to use for launching new 2350 * sub-Activities to prompt to add an account, select an account, 2351 * and/or enter a password, as necessary; used only to call 2352 * startActivity(); should not be null 2353 * @param addAccountOptions Authenticator-specific options to use for 2354 * adding new accounts; may be null or empty 2355 * @param getAuthTokenOptions Authenticator-specific options to use for 2356 * getting auth tokens; may be null or empty 2357 * @param callback Callback to invoke when the request completes, 2358 * null for no callback 2359 * @param handler {@link Handler} identifying the callback thread, 2360 * null for the main thread 2361 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2362 * at least the following fields: 2363 * <ul> 2364 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account 2365 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account 2366 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted 2367 * </ul> 2368 * 2369 * If an error occurred, {@link AccountManagerFuture#getResult()} throws: 2370 * <ul> 2371 * <li> {@link AuthenticatorException} if no authenticator was registered for 2372 * this account type or the authenticator failed to respond 2373 * <li> {@link OperationCanceledException} if the operation was canceled for 2374 * any reason, including the user canceling any operation 2375 * <li> {@link IOException} if the authenticator experienced an I/O problem 2376 * updating settings, usually because of network trouble 2377 * </ul> 2378 */ 2379 public AccountManagerFuture<Bundle> getAuthTokenByFeatures( 2380 final String accountType, final String authTokenType, final String[] features, 2381 final Activity activity, final Bundle addAccountOptions, 2382 final Bundle getAuthTokenOptions, 2383 final AccountManagerCallback<Bundle> callback, final Handler handler) { 2384 if (accountType == null) throw new IllegalArgumentException("account type is null"); 2385 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); 2386 final GetAuthTokenByTypeAndFeaturesTask task = 2387 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features, 2388 activity, addAccountOptions, getAuthTokenOptions, callback, handler); 2389 task.start(); 2390 return task; 2391 } 2392 2393 /** 2394 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String, 2395 * String, String[], Bundle)}. 2396 * 2397 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of 2398 * accounts. 2399 * The caller will then typically start the activity by calling 2400 * <code>startActivityForResult(intent, ...);</code>. 2401 * <p> 2402 * On success the activity returns a Bundle with the account name and type specified using 2403 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}. 2404 * <p> 2405 * The most common case is to call this with one account type, e.g.: 2406 * <p> 2407 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, 2408 * null, null, null);</pre> 2409 * @param selectedAccount if specified, indicates that the {@link Account} is the currently 2410 * selected one, according to the caller's definition of selected. 2411 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be 2412 * shown. If not specified then this field will not limit the displayed accounts. 2413 * @param allowableAccountTypes an optional string array of account types. These are used 2414 * both to filter the shown accounts and to filter the list of account types that are shown 2415 * when adding an account. If not specified then this field will not limit the displayed 2416 * account types when adding an account. 2417 * @param alwaysPromptForAccount boolean that is ignored. 2418 * @param descriptionOverrideText if non-null this string is used as the description in the 2419 * accounts chooser screen rather than the default 2420 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount} 2421 * authTokenType parameter 2422 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount} 2423 * requiredFeatures parameter 2424 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options 2425 * parameter 2426 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow. 2427 */ 2428 @Deprecated 2429 static public Intent newChooseAccountIntent( 2430 Account selectedAccount, 2431 ArrayList<Account> allowableAccounts, 2432 String[] allowableAccountTypes, 2433 boolean alwaysPromptForAccount, 2434 String descriptionOverrideText, 2435 String addAccountAuthTokenType, 2436 String[] addAccountRequiredFeatures, 2437 Bundle addAccountOptions) { 2438 return newChooseAccountIntent( 2439 selectedAccount, 2440 allowableAccounts, 2441 allowableAccountTypes, 2442 descriptionOverrideText, 2443 addAccountAuthTokenType, 2444 addAccountRequiredFeatures, 2445 addAccountOptions); 2446 } 2447 2448 /** 2449 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of 2450 * accounts. 2451 * The caller will then typically start the activity by calling 2452 * <code>startActivityForResult(intent, ...);</code>. 2453 * <p> 2454 * On success the activity returns a Bundle with the account name and type specified using 2455 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}. 2456 * <p> 2457 * The most common case is to call this with one account type, e.g.: 2458 * <p> 2459 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null, 2460 * null);</pre> 2461 * @param selectedAccount if specified, indicates that the {@link Account} is the currently 2462 * selected one, according to the caller's definition of selected. 2463 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be 2464 * shown. If not specified then this field will not limit the displayed accounts. 2465 * @param allowableAccountTypes an optional string array of account types. These are used 2466 * both to filter the shown accounts and to filter the list of account types that are shown 2467 * when adding an account. If not specified then this field will not limit the displayed 2468 * account types when adding an account. 2469 * @param descriptionOverrideText if non-null this string is used as the description in the 2470 * accounts chooser screen rather than the default 2471 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount} 2472 * authTokenType parameter 2473 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount} 2474 * requiredFeatures parameter 2475 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options 2476 * parameter 2477 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow. 2478 */ 2479 static public Intent newChooseAccountIntent( 2480 Account selectedAccount, 2481 List<Account> allowableAccounts, 2482 String[] allowableAccountTypes, 2483 String descriptionOverrideText, 2484 String addAccountAuthTokenType, 2485 String[] addAccountRequiredFeatures, 2486 Bundle addAccountOptions) { 2487 Intent intent = new Intent(); 2488 ComponentName componentName = ComponentName.unflattenFromString( 2489 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity)); 2490 intent.setClassName(componentName.getPackageName(), 2491 componentName.getClassName()); 2492 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST, 2493 allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts)); 2494 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY, 2495 allowableAccountTypes); 2496 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE, 2497 addAccountOptions); 2498 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount); 2499 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE, 2500 descriptionOverrideText); 2501 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING, 2502 addAccountAuthTokenType); 2503 intent.putExtra( 2504 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY, 2505 addAccountRequiredFeatures); 2506 return intent; 2507 } 2508 2509 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners = 2510 Maps.newHashMap(); 2511 2512 /** 2513 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent 2514 * so that it can read the updated list of accounts and send them to the listener 2515 * in mAccountsUpdatedListeners. 2516 */ 2517 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() { 2518 public void onReceive(final Context context, final Intent intent) { 2519 final Account[] accounts = getAccounts(); 2520 // send the result to the listeners 2521 synchronized (mAccountsUpdatedListeners) { 2522 for (Map.Entry<OnAccountsUpdateListener, Handler> entry : 2523 mAccountsUpdatedListeners.entrySet()) { 2524 postToHandler(entry.getValue(), entry.getKey(), accounts); 2525 } 2526 } 2527 } 2528 }; 2529 2530 /** 2531 * Adds an {@link OnAccountsUpdateListener} to this instance of the 2532 * {@link AccountManager}. This listener will be notified whenever the 2533 * list of accounts on the device changes. 2534 * 2535 * <p>As long as this listener is present, the AccountManager instance 2536 * will not be garbage-collected, and neither will the {@link Context} 2537 * used to retrieve it, which may be a large Activity instance. To avoid 2538 * memory leaks, you must remove this listener before then. Normally 2539 * listeners are added in an Activity or Service's {@link Activity#onCreate} 2540 * and removed in {@link Activity#onDestroy}. 2541 * 2542 * <p>The listener will only be informed of accounts that would be returned 2543 * to the caller via {@link #getAccounts()}. Typically this means that to 2544 * get any accounts, the caller will need to be grated the GET_ACCOUNTS 2545 * permission. 2546 * 2547 * <p>It is safe to call this method from the main thread. 2548 * 2549 * @param listener The listener to send notifications to 2550 * @param handler {@link Handler} identifying the thread to use 2551 * for notifications, null for the main thread 2552 * @param updateImmediately If true, the listener will be invoked 2553 * (on the handler thread) right away with the current account list 2554 * @throws IllegalArgumentException if listener is null 2555 * @throws IllegalStateException if listener was already added 2556 */ 2557 @RequiresPermission(GET_ACCOUNTS) 2558 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener, 2559 Handler handler, boolean updateImmediately) { 2560 if (listener == null) { 2561 throw new IllegalArgumentException("the listener is null"); 2562 } 2563 synchronized (mAccountsUpdatedListeners) { 2564 if (mAccountsUpdatedListeners.containsKey(listener)) { 2565 throw new IllegalStateException("this listener is already added"); 2566 } 2567 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty(); 2568 2569 mAccountsUpdatedListeners.put(listener, handler); 2570 2571 if (wasEmpty) { 2572 // Register a broadcast receiver to monitor account changes 2573 IntentFilter intentFilter = new IntentFilter(); 2574 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION); 2575 // To recover from disk-full. 2576 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK); 2577 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter); 2578 } 2579 } 2580 2581 if (updateImmediately) { 2582 postToHandler(handler, listener, getAccounts()); 2583 } 2584 } 2585 2586 /** 2587 * Removes an {@link OnAccountsUpdateListener} previously registered with 2588 * {@link #addOnAccountsUpdatedListener}. The listener will no longer 2589 * receive notifications of account changes. 2590 * 2591 * <p>It is safe to call this method from the main thread. 2592 * 2593 * <p>No permission is required to call this method. 2594 * 2595 * @param listener The previously added listener to remove 2596 * @throws IllegalArgumentException if listener is null 2597 * @throws IllegalStateException if listener was not already added 2598 */ 2599 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) { 2600 if (listener == null) throw new IllegalArgumentException("listener is null"); 2601 synchronized (mAccountsUpdatedListeners) { 2602 if (!mAccountsUpdatedListeners.containsKey(listener)) { 2603 Log.e(TAG, "Listener was not previously added"); 2604 return; 2605 } 2606 mAccountsUpdatedListeners.remove(listener); 2607 if (mAccountsUpdatedListeners.isEmpty()) { 2608 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver); 2609 } 2610 } 2611 } 2612 2613 /** 2614 * Asks the user to authenticate with an account of a specified type. The 2615 * authenticator for this account type processes this request with the 2616 * appropriate user interface. If the user does elect to authenticate with a 2617 * new account, a bundle of session data for installing the account later is 2618 * returned with optional account password and account status token. 2619 * <p> 2620 * This method may be called from any thread, but the returned 2621 * {@link AccountManagerFuture} must not be used on the main thread. 2622 * <p> 2623 * <p> 2624 * <b>NOTE:</b> The account will not be installed to the device by calling 2625 * this api alone. #finishSession should be called after this to install the 2626 * account on device. 2627 * 2628 * @param accountType The type of account to add; must not be null 2629 * @param authTokenType The type of auth token (see {@link #getAuthToken}) 2630 * this account will need to be able to generate, null for none 2631 * @param requiredFeatures The features (see {@link #hasFeatures}) this 2632 * account must have, null for none 2633 * @param options Authenticator-specific options for the request, may be 2634 * null or empty 2635 * @param activity The {@link Activity} context to use for launching a new 2636 * authenticator-defined sub-Activity to prompt the user to 2637 * create an account; used only to call startActivity(); if null, 2638 * the prompt will not be launched directly, but the necessary 2639 * {@link Intent} will be returned to the caller instead 2640 * @param callback Callback to invoke when the request completes, null for 2641 * no callback 2642 * @param handler {@link Handler} identifying the callback thread, null for 2643 * the main thread 2644 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2645 * these fields if activity was specified and user was authenticated 2646 * with an account: 2647 * <ul> 2648 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for 2649 * adding the the to the device later. 2650 * <li>{@link #KEY_PASSWORD} - optional, the password or password 2651 * hash of the account. 2652 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check 2653 * status of the account 2654 * </ul> 2655 * If no activity was specified, the returned Bundle contains only 2656 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 2657 * actual account creation process. If authenticator doesn't support 2658 * this method, the returned Bundle contains only 2659 * {@link #KEY_ACCOUNT_SESSION_BUNDLE} with encrypted 2660 * {@code options} needed to add account later. If an error 2661 * occurred, {@link AccountManagerFuture#getResult()} throws: 2662 * <ul> 2663 * <li>{@link AuthenticatorException} if no authenticator was 2664 * registered for this account type or the authenticator failed to 2665 * respond 2666 * <li>{@link OperationCanceledException} if the operation was 2667 * canceled for any reason, including the user canceling the 2668 * creation process or adding accounts (of this type) has been 2669 * disabled by policy 2670 * <li>{@link IOException} if the authenticator experienced an I/O 2671 * problem creating a new account, usually because of network 2672 * trouble 2673 * </ul> 2674 * @see #finishSession 2675 * @hide 2676 */ 2677 @SystemApi 2678 public AccountManagerFuture<Bundle> startAddAccountSession( 2679 final String accountType, 2680 final String authTokenType, 2681 final String[] requiredFeatures, 2682 final Bundle options, 2683 final Activity activity, 2684 AccountManagerCallback<Bundle> callback, 2685 Handler handler) { 2686 if (accountType == null) throw new IllegalArgumentException("accountType is null"); 2687 final Bundle optionsIn = new Bundle(); 2688 if (options != null) { 2689 optionsIn.putAll(options); 2690 } 2691 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 2692 2693 return new AmsTask(activity, handler, callback) { 2694 @Override 2695 public void doWork() throws RemoteException { 2696 mService.startAddAccountSession( 2697 mResponse, 2698 accountType, 2699 authTokenType, 2700 requiredFeatures, 2701 activity != null, 2702 optionsIn); 2703 } 2704 }.start(); 2705 } 2706 2707 /** 2708 * Asks the user to enter a new password for an account but not updating the 2709 * saved credentials for the account until {@link #finishSession} is called. 2710 * <p> 2711 * This method may be called from any thread, but the returned 2712 * {@link AccountManagerFuture} must not be used on the main thread. 2713 * <p> 2714 * <b>NOTE:</b> The saved credentials for the account alone will not be 2715 * updated by calling this API alone. #finishSession should be called after 2716 * this to update local credentials 2717 * 2718 * @param account The account to update credentials for 2719 * @param authTokenType The credentials entered must allow an auth token of 2720 * this type to be created (but no actual auth token is 2721 * returned); may be null 2722 * @param options Authenticator-specific options for the request; may be 2723 * null or empty 2724 * @param activity The {@link Activity} context to use for launching a new 2725 * authenticator-defined sub-Activity to prompt the user to enter 2726 * a password; used only to call startActivity(); if null, the 2727 * prompt will not be launched directly, but the necessary 2728 * {@link Intent} will be returned to the caller instead 2729 * @param callback Callback to invoke when the request completes, null for 2730 * no callback 2731 * @param handler {@link Handler} identifying the callback thread, null for 2732 * the main thread 2733 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2734 * these fields if an activity was supplied and user was 2735 * successfully re-authenticated to the account: 2736 * <ul> 2737 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for 2738 * updating the local credentials on device later. 2739 * <li>{@link #KEY_PASSWORD} - optional, the password or password 2740 * hash of the account 2741 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check 2742 * status of the account 2743 * </ul> 2744 * If no activity was specified, the returned Bundle contains 2745 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 2746 * password prompt. If an error occurred, 2747 * {@link AccountManagerFuture#getResult()} throws: 2748 * <ul> 2749 * <li>{@link AuthenticatorException} if the authenticator failed to 2750 * respond 2751 * <li>{@link OperationCanceledException} if the operation was 2752 * canceled for any reason, including the user canceling the 2753 * password prompt 2754 * <li>{@link IOException} if the authenticator experienced an I/O 2755 * problem verifying the password, usually because of network 2756 * trouble 2757 * </ul> 2758 * @see #finishSession 2759 * @hide 2760 */ 2761 @SystemApi 2762 public AccountManagerFuture<Bundle> startUpdateCredentialsSession( 2763 final Account account, 2764 final String authTokenType, 2765 final Bundle options, 2766 final Activity activity, 2767 final AccountManagerCallback<Bundle> callback, 2768 final Handler handler) { 2769 if (account == null) { 2770 throw new IllegalArgumentException("account is null"); 2771 } 2772 return new AmsTask(activity, handler, callback) { 2773 @Override 2774 public void doWork() throws RemoteException { 2775 mService.startUpdateCredentialsSession( 2776 mResponse, 2777 account, 2778 authTokenType, 2779 activity != null, 2780 options); 2781 } 2782 }.start(); 2783 } 2784 2785 /** 2786 * Finishes the session started by {@link #startAddAccountSession} or 2787 * {@link #startUpdateCredentialsSession}. This will either add the account 2788 * to AccountManager or update the local credentials stored. 2789 * <p> 2790 * This method may be called from any thread, but the returned 2791 * {@link AccountManagerFuture} must not be used on the main thread. 2792 * 2793 * @param sessionBundle a {@link Bundle} created by {@link #startAddAccountSession} or 2794 * {@link #startUpdateCredentialsSession} 2795 * @param activity The {@link Activity} context to use for launching a new 2796 * authenticator-defined sub-Activity to prompt the user to 2797 * create an account or reauthenticate existing account; used 2798 * only to call startActivity(); if null, the prompt will not 2799 * be launched directly, but the necessary {@link Intent} will 2800 * be returned to the caller instead 2801 * @param callback Callback to invoke when the request completes, null for 2802 * no callback 2803 * @param handler {@link Handler} identifying the callback thread, null for 2804 * the main thread 2805 * @return An {@link AccountManagerFuture} which resolves to a Bundle with 2806 * these fields if an activity was supplied and an account was added 2807 * to device or local credentials were updated:: 2808 * <ul> 2809 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account created 2810 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account 2811 * </ul> 2812 * If no activity was specified and additional information is needed 2813 * from user, the returned Bundle may contains only 2814 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the 2815 * actual account creation process. If an error occurred, 2816 * {@link AccountManagerFuture#getResult()} throws: 2817 * <ul> 2818 * <li>{@link AuthenticatorException} if no authenticator was 2819 * registered for this account type or the authenticator failed to 2820 * respond 2821 * <li>{@link OperationCanceledException} if the operation was 2822 * canceled for any reason, including the user canceling the 2823 * creation process or adding accounts (of this type) has been 2824 * disabled by policy 2825 * <li>{@link IOException} if the authenticator experienced an I/O 2826 * problem creating a new account, usually because of network 2827 * trouble 2828 * </ul> 2829 * @see #startAddAccountSession and #startUpdateCredentialsSession 2830 * @hide 2831 */ 2832 @SystemApi 2833 public AccountManagerFuture<Bundle> finishSession( 2834 final Bundle sessionBundle, 2835 final Activity activity, 2836 AccountManagerCallback<Bundle> callback, 2837 Handler handler) { 2838 if (sessionBundle == null) { 2839 throw new IllegalArgumentException("sessionBundle is null"); 2840 } 2841 2842 /* Add information required by add account flow */ 2843 final Bundle appInfo = new Bundle(); 2844 appInfo.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName()); 2845 2846 return new AmsTask(activity, handler, callback) { 2847 @Override 2848 public void doWork() throws RemoteException { 2849 mService.finishSession(mResponse, sessionBundle, activity != null, appInfo); 2850 } 2851 }.start(); 2852 } 2853} 2854