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