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