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