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