blob: a446296fe393e3cdea529ea3765974874d62948f [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.accounts;
18
Sandra Kwan390c9d22016-01-12 14:13:37 -080019import static android.Manifest.permission.GET_ACCOUNTS;
20
Dmitry Dementyev52745472016-12-02 10:27:45 -080021import android.annotation.IntDef;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070022import android.annotation.NonNull;
Tor Norbye80b530a2015-04-23 16:36:09 -070023import android.annotation.RequiresPermission;
Jeff Sharkey32ee8ee2017-03-08 20:17:51 -070024import android.annotation.SdkConstant;
Tor Norbye80b530a2015-04-23 16:36:09 -070025import android.annotation.Size;
Sandra Kwana578d112015-12-16 16:01:43 -080026import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060027import android.annotation.SystemService;
Jeff Sharkey32ee8ee2017-03-08 20:17:51 -070028import android.annotation.SdkConstant.SdkConstantType;
29import android.annotation.BroadcastBehavior;
Fred Quintana60307342009-03-24 22:48:12 -070030import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080031import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070032import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070033import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080034import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070035import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070036import android.content.IntentSender;
Amith Yamasani12b8e132013-03-14 10:48:07 -070037import android.content.res.Resources;
Dmitry Dementyev52745472016-12-02 10:27:45 -080038import android.content.pm.ApplicationInfo;
39import android.content.pm.PackageManager;
Costin Manolacheb6437242009-09-10 16:14:12 -070040import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080041import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.os.Bundle;
43import android.os.Handler;
44import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070045import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080046import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080047import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080048import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080049import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080050import android.util.Log;
51
52import com.android.internal.R;
53import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070054
Fred Quintanaa698f422009-04-08 19:14:54 -070055import java.io.IOException;
Dmitry Dementyev52745472016-12-02 10:27:45 -080056import java.lang.annotation.Retention;
57import java.lang.annotation.RetentionPolicy;
58import java.lang.SuppressWarnings;
Fred Quintana1121bb52011-09-14 23:19:35 -070059import java.util.ArrayList;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080060import java.util.Arrays;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080061import java.util.HashMap;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080062import java.util.HashSet;
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -070063import java.util.List;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080064import java.util.Map;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080065import java.util.Set;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import java.util.concurrent.Callable;
67import java.util.concurrent.CancellationException;
68import java.util.concurrent.ExecutionException;
69import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080071import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070072
73/**
Dan Egnor661f0132010-02-19 11:23:00 -080074 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070075 * online accounts. The user enters credentials (username and password) once
76 * per account, granting applications access to online resources with
77 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070078 *
Dan Egnor661f0132010-02-19 11:23:00 -080079 * <p>Different online services have different ways of handling accounts and
80 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070081 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -080085 *
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
Dan Egnor8e4378b2010-08-02 18:22:09 -070090 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -080095 *
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 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700114 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -0800119 * <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
Dan Egnor8e4378b2010-08-02 18:22:09 -0700125 * service you are accessing. The application may use whatever network and
126 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800127 *
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 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700138 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800139 * 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
Dan Egnor8e4378b2010-08-02 18:22:09 -0700148 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800149 * 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.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700152 * 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
Dan Egnor661f0132010-02-19 11:23:00 -0800157 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700158 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800159 *
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.
Fred Quintana60307342009-03-24 22:48:12 -0700164 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600165@SystemService(Context.ACCOUNT_SERVICE)
Fred Quintana60307342009-03-24 22:48:12 -0700166public class AccountManager {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800167
Fred Quintana60307342009-03-24 22:48:12 -0700168 private static final String TAG = "AccountManager";
169
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700170 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;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700177 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700178
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800179 /** @hide */
180 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100181 /** @hide */
182 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800183
Dan Egnor661f0132010-02-19 11:23:00 -0800184 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700185 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800186 * from methods which return information about a particular account.
187 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700188 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800189
190 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700191 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800192 * from methods which return information about a particular account.
193 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700194 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800195
196 /**
Svet Ganovd4696122016-09-24 13:57:45 -0700197 * Bundle key used for the account access id used for noting the
198 * account was accessed when unmarshaled from a parcel.
Svet Ganovf6d424f12016-09-20 20:18:53 -0700199 *
200 * @hide
201 */
Svet Ganovd4696122016-09-24 13:57:45 -0700202 public static final String KEY_ACCOUNT_ACCESS_ID = "accountAccessId";
Svet Ganovf6d424f12016-09-20 20:18:53 -0700203
204 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700205 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800206 * from {@link #getAuthToken} and friends.
207 */
208 public static final String KEY_AUTHTOKEN = "authtoken";
209
210 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700211 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800212 * may require the caller to interact with the user. The Intent can
213 * be used to start the corresponding user interface activity.
214 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700215 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800216
217 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700218 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800219 * {@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";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700225
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700226 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
227 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800228 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700229 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
230 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800231 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";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700235
Costin Manolachea40c6302010-12-13 14:50:45 -0800236 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800237 * Bundle key used to supply the last time the credentials of the account
238 * were authenticated successfully. Time is specified in milliseconds since
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700239 * epoch. Associated time is updated on successful authentication of account
240 * on adding account, confirming credentials, or updating credentials.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800241 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700242 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800243
244 /**
Costin Manolachea40c6302010-12-13 14:50:45 -0800245 * 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";
Dan Egnor661f0132010-02-19 11:23:00 -0800250
Costin Manolached6060452011-01-24 16:11:36 -0800251 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700252 * 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 /**
Costin Manolached6060452011-01-24 16:11:36 -0800262 * 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
Sandra Kwan78812282015-11-04 11:19:47 -0800268 /**
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
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700282 public static final String ACTION_AUTHENTICATOR_INTENT =
283 "android.accounts.AccountAuthenticator";
284 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800285 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700286 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
287
Dmitry Dementyev52745472016-12-02 10:27:45 -0800288 /** @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 /**
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800296 * 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}
Dmitry Dementyev52745472016-12-02 10:27:45 -0800298 */
299 public static final int VISIBILITY_UNDEFINED = 0;
300
301 /**
302 * Account is always visible to given application and only authenticator can revoke visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800303 */
304 public static final int VISIBILITY_VISIBLE = 1;
305
306 /**
307 * Account is visible to given application, but user can revoke visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800308 */
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.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800313 */
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)}
Dmitry Dementyev52745472016-12-02 10:27:45 -0800319 */
320 public static final int VISIBILITY_USER_MANAGED_NOT_VISIBLE = 4;
321
322 /**
Svet Ganovf6d424f12016-09-20 20:18:53 -0700323 * Token type for the special case where a UID has access only to an account
324 * but no authenticator specific auth token types.
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +0000325 *
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700326 * @hide
327 */
Svet Ganovf6d424f12016-09-20 20:18:53 -0700328 public static final String ACCOUNT_ACCESS_TOKEN_TYPE =
329 "com.android.AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE";
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700330
Fred Quintana60307342009-03-24 22:48:12 -0700331 private final Context mContext;
332 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700333 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800334
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700335 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800336 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -0800338 *
339 * @see #addOnAccountsUpdatedListener
Dmitry Dementyeva461e302017-04-12 11:00:48 -0700340 * @see #ACTION_ACCOUNT_REMOVED
Dmitry Dementyev52745472016-12-02 10:27:45 -0800341 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700342 * @deprecated use {@link #addOnAccountsUpdatedListener} to get account updates in runtime.
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700343 */
Jeff Sharkey32ee8ee2017-03-08 20:17:51 -0700344 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
345 @BroadcastBehavior(includeBackground = true)
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700346 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
347 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700348
Fred Quintana33269202009-04-20 16:05:10 -0700349 /**
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700350 * 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>
Dmitry Dementyeva461e302017-04-12 11:00:48 -0700357 */
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 /**
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700364 * 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 /**
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700375 * 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
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800388 * {@link #VISIBILITY_USER_MANAGED_VISIBLE} is used.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800389 */
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700390 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 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800398 public static final String PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE =
Dmitry Dementyevcbe1bd12017-04-25 17:02:47 -0700399 "android:accounts:key_legacy_not_visible";
Dmitry Dementyev52745472016-12-02 10:27:45 -0800400
401 /**
Fred Quintana33269202009-04-20 16:05:10 -0700402 * @hide
403 */
Fred Quintana60307342009-03-24 22:48:12 -0700404 public AccountManager(Context context, IAccountManager service) {
405 mContext = context;
406 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700407 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700408 }
409
Fred Quintana0eabf022009-04-27 15:08:17 -0700410 /**
411 * @hide used for testing only
412 */
413 public AccountManager(Context context, IAccountManager service, Handler handler) {
414 mContext = context;
415 mService = service;
416 mMainHandler = handler;
417 }
418
Fred Quintana756b7352009-10-21 13:43:10 -0700419 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800420 * @hide for internal use only
421 */
422 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700423 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 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800430 }
431 return result;
432 }
433
434 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800435 * 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 *
Fred Quintana756b7352009-10-21 13:43:10 -0700445 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800446 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700447 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700448 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700449 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700450 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
451 }
452
Fred Quintana756b7352009-10-21 13:43:10 -0700453 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800454 * Gets the saved password associated with the account. This is intended for authenticators and
455 * related code; applications should get an auth token instead.
Dan Egnor661f0132010-02-19 11:23:00 -0800456 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800457 * <p>
458 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800459 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800460 * <p>
461 * This method requires the caller to have a signature match with the authenticator that owns
462 * the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800463 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800464 * <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}.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700469 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700470 * @param account The account to query for a password. Must not be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800471 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700472 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700473 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700474 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700475 try {
476 return mService.getPassword(account);
477 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700478 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700479 }
480 }
481
Fred Quintana756b7352009-10-21 13:43:10 -0700482 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800483 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -0800486 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800487 * <p>
488 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800489 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800490 * <p>
491 * This method requires the caller to have a signature match with the authenticator that owns
492 * the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800493 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800494 * <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}.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700499 *
Dan Egnor661f0132010-02-19 11:23:00 -0800500 * @param account The account to query for user data
501 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700502 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700503 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700504 if (account == null) throw new IllegalArgumentException("account is null");
505 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700506 try {
507 return mService.getUserData(account, key);
508 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700509 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700510 }
511 }
512
Fred Quintana756b7352009-10-21 13:43:10 -0700513 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800514 * 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.
Fred Quintana756b7352009-10-21 13:43:10 -0700523 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700524 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700525 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100526 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
527 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700528 throw e.rethrowFromSystemServer();
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100529 }
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 */
545 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
546 try {
547 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700548 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700549 throw e.rethrowFromSystemServer();
Fred Quintanaa698f422009-04-08 19:14:54 -0700550 }
551 }
552
Fred Quintana756b7352009-10-21 13:43:10 -0700553 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800554 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -0800558 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800559 * <p>
560 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800561 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800562 * @return An array of {@link Account}, one for each account. Empty (never null) if no accounts
563 * have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700564 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700565 @NonNull
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700566 public Account[] getAccounts() {
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000567 try {
568 return mService.getAccounts(null, mContext.getOpPackageName());
569 } catch (RemoteException e) {
570 throw e.rethrowFromSystemServer();
571 }
Fred Quintana60307342009-03-24 22:48:12 -0700572 }
573
Fred Quintana756b7352009-10-21 13:43:10 -0700574 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700575 * @hide
Dmitry Dementyev52745472016-12-02 10:27:45 -0800576 * Lists all accounts visible to caller regardless of type for a given user id. Equivalent to
577 * getAccountsByType(null).
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100578 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800579 * <p>
580 * It is safe to call this method from the main thread.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100581 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800582 * @return An array of {@link Account}, one for each account. Empty (never null) if no accounts
583 * have been added.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100584 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700585 @NonNull
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100586 public Account[] getAccountsAsUser(int userId) {
587 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700588 return mService.getAccountsAsUser(null, userId, mContext.getOpPackageName());
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100589 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700590 throw e.rethrowFromSystemServer();
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100591 }
592 }
593
594 /**
595 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700596 * 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 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700602 @NonNull
Amith Yamasani27db4682013-03-30 17:07:47 -0700603 public Account[] getAccountsForPackage(String packageName, int uid) {
604 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700605 return mService.getAccountsForPackage(packageName, uid, mContext.getOpPackageName());
Amith Yamasani27db4682013-03-30 17:07:47 -0700606 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700607 throw re.rethrowFromSystemServer();
Amith Yamasani27db4682013-03-30 17:07:47 -0700608 }
609 }
610
611 /**
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700612 * Returns the accounts visible to the specified package in an environment where some apps are
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800613 * not authorized to view all accounts. This method can only be called by system apps and
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700614 * 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}).
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800617 *
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700618 * @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
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800620 * @return An array of {@link Account}, one per matching account. Empty (never null) if no
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700621 * accounts of the specified type can be accessed by the package.
622 *
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700623 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700624 @NonNull
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700625 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
626 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700627 return mService.getAccountsByTypeForPackage(type, packageName,
628 mContext.getOpPackageName());
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700629 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700630 throw re.rethrowFromSystemServer();
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700631 }
632 }
633
634 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800635 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -0800639 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800640 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -0800645 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800646 * <p>
647 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800648 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800649 * <p>
650 * Caller targeting API level {@link android.os.Build.VERSION_CODES#O} and above, will get list
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700651 * 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}.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800655 * {@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
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800664 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before,
665 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is
Dmitry Dementyev52745472016-12-02 10:27:45 -0800666 * 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}.
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000668 *
669 * @param type The type of accounts to return, null to retrieve all accounts
Dmitry Dementyev52745472016-12-02 10:27:45 -0800670 * @return An array of {@link Account}, one per matching account. Empty (never null) if no
671 * accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700672 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700673 @NonNull
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700674 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800675 return getAccountsByTypeAsUser(type, Process.myUserHandle());
676 }
677
678 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700679 @NonNull
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800680 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700681 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700682 return mService.getAccountsAsUser(type, userHandle.getIdentifier(),
683 mContext.getOpPackageName());
Fred Quintana60307342009-03-24 22:48:12 -0700684 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700685 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700686 }
687 }
688
Fred Quintana756b7352009-10-21 13:43:10 -0700689 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700690 * 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 */
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) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700704 throw e.rethrowFromSystemServer();
Fred Quintanad9640ec2012-05-23 12:37:00 -0700705 }
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 */
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) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800723 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -0700724 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 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800739 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -0800744 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800745 * <p>
746 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
747 * not be used on the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800748 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800749 * <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.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800753 *
754 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800755 * @param features An array of the account features to check
Dmitry Dementyev52745472016-12-02 10:27:45 -0800756 * @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.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800760 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800761 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800762 final String[] features,
763 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700764 if (account == null) throw new IllegalArgumentException("account is null");
765 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800766 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800767 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800768 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700769 mService.hasFeatures(mResponse, account, features, mContext.getOpPackageName());
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800770 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800771 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800772 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 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800782 * 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}).
Fred Quintana756b7352009-10-21 13:43:10 -0700785 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800786 * <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}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700790 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800791 * <p>
792 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
793 * not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700794 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800795 * <p>
796 * Caller targeting API level {@link android.os.Build.VERSION_CODES#O} and above, will get list
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700797 * 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}.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800801 * {@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
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800809 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before,
810 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is
Dmitry Dementyev52745472016-12-02 10:27:45 -0800811 * 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 *
Fred Quintana756b7352009-10-21 13:43:10 -0700814 *
Dan Egnor661f0132010-02-19 11:23:00 -0800815 * @param type The type of accounts to return, must not be null
Dmitry Dementyev52745472016-12-02 10:27:45 -0800816 * @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.
Fred Quintana8570f742010-02-18 10:32:54 -0800821 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700822 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
823 final String type, final String[] features,
824 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700825 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700826 return new Future2Task<Account[]>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800827 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700828 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700829 mService.getAccountsByFeatures(mResponse, type, features,
830 mContext.getOpPackageName());
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700831 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800832 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700833 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700834 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700835 throw new AuthenticatorException("no result in response");
836 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700837 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700838 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
Fred Quintana756b7352009-10-21 13:43:10 -0700847 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700848 * Adds an account directly to the AccountManager. Normally used by sign-up
Dan Egnor661f0132010-02-19 11:23:00 -0800849 * wizards associated with authenticators, not directly by applications.
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700850 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -0800857 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700858 * <p>This method requires the caller to have a signature match with the
859 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800860 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700861 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -0800865 * @param account The {@link Account} to add
866 * @param password The password to associate with the account, null for none
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700867 * @param userdata String values to use for the account's userdata, null for
868 * none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700869 * @return True if the account was successfully added, false if the account
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700870 * already exists, the account is null, or another error occurs.
Dan Egnor661f0132010-02-19 11:23:00 -0800871 */
872 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700873 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800874 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700875 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800876 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700877 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -0800878 }
879 }
880
881 /**
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700882 * Adds an account directly to the AccountManager. Additionally it specifies Account visibility
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800883 * for given list of packages.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800884 * <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
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700890 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800891 * <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.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700896 *
897 * @param account The {@link Account} to add
898 * @param password The password to associate with the account, null for none
Dmitry Dementyev52745472016-12-02 10:27:45 -0800899 * @param extras String values to use for the account's userdata, null for none
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800900 * @param visibility Map from packageName to visibility values which will be set before account
901 * is added. See {@link #getAccountVisibility} for possible values.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800902 *
903 * @return True if the account was successfully added, false if the account already exists, the
904 * account is null, or another error occurs.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800905 */
906 public boolean addAccountExplicitly(Account account, String password, Bundle extras,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800907 Map<String, Integer> visibility) {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800908 if (account == null)
909 throw new IllegalArgumentException("account is null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700910 try {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800911 return mService.addAccountExplicitlyWithVisibility(account, password, extras,
912 visibility);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700913 } catch (RemoteException e) {
914 throw e.rethrowFromSystemServer();
915 }
916 }
917
918 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800919 * Returns package names and visibility which were explicitly set for given account.
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800920 * <p>
921 * This method requires the caller to have a signature match with the authenticator that owns
922 * the specified account.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700923 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700924 * @param account The account for which visibility data should be returned
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700925 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700926 * @return Map from package names to visibility for given account
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700927 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800928 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800929 try {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800930 if (account == null)
931 throw new IllegalArgumentException("account is null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800932 @SuppressWarnings("unchecked")
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800933 Map<String, Integer> result = (Map<String, Integer>) mService
934 .getPackagesAndVisibilityForAccount(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800935 return result;
936 } catch (RemoteException re) {
937 throw re.rethrowFromSystemServer();
938 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700939 }
940
941 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800942 * 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 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700949 * @param packageName Package name
950 * @param accountType {@link Account} type
Dmitry Dementyev52745472016-12-02 10:27:45 -0800951 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700952 * @return Map with visibility for all accounts of given type
953 * See {@link #getAccountVisibility} for possible values
Dmitry Dementyev52745472016-12-02 10:27:45 -0800954 */
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 /**
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700968 * Set visibility value of given account to certain package.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800969 * 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}.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800971 * <p>
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800972 * 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>
Dmitry Dementyev52745472016-12-02 10:27:45 -0800980 * <p>
981 * This method requires the caller to have a signature match with the authenticator that owns
982 * the specified account.
983 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700984 * @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
Dmitry Dementyev52745472016-12-02 10:27:45 -0800987 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700988 * @return True, if visibility value was successfully updated.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800989 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800990 public boolean setAccountVisibility(Account account, String packageName,
Dmitry Dementyev52745472016-12-02 10:27:45 -0800991 @AccountVisibility int visibility) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800992 if (account == null)
993 throw new IllegalArgumentException("account is null");
Dmitry Dementyev52745472016-12-02 10:27:45 -0800994 try {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800995 return mService.setAccountVisibility(account, packageName, visibility);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800996 } catch (RemoteException re) {
997 throw re.rethrowFromSystemServer();
998 }
999 }
1000
1001 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001002 * Get visibility of certain account for given application. Possible returned values are:
Dmitry Dementyev52745472016-12-02 10:27:45 -08001003 * <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 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -07001014 * @param account {@link Account} to get visibility
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001015 * @param packageName Package name of the application to get account visibility
Dmitry Dementyev52745472016-12-02 10:27:45 -08001016 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -07001017 * @return int Visibility of given account.
Dmitry Dementyev52745472016-12-02 10:27:45 -08001018 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001019 public @AccountVisibility int getAccountVisibility(Account account, String packageName) {
1020 if (account == null)
1021 throw new IllegalArgumentException("account is null");
Dmitry Dementyev52745472016-12-02 10:27:45 -08001022 try {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001023 return mService.getAccountVisibility(account, packageName);
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001024 } catch (RemoteException re) {
1025 throw re.rethrowFromSystemServer();
1026 }
1027 }
1028
1029 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001030 * Notifies the system that the account has just been authenticated. This
1031 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001032 * 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.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001037 * <p>This method requires the caller to have a signature match with the
1038 * authenticator that owns the specified account.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001039 *
1040 * @param account The {@link Account} to be updated.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001041 * @return boolean {@code true} if the authentication of the account has been successfully
1042 * acknowledged. Otherwise {@code false}.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001043 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001044 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001045 if (account == null)
1046 throw new IllegalArgumentException("account is null");
1047 try {
1048 return mService.accountAuthenticated(account);
1049 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001050 throw e.rethrowFromSystemServer();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001051 }
1052 }
1053
1054 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001055 * 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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001061 * <p>This method requires the caller to have a signature match with the
1062 * authenticator that manages the specified account.
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001063 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001064 * <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 *
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001068 * @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,
Tor Norbye80b530a2015-04-23 16:36:09 -07001080 @Size(min = 1) final String newName,
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001081 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);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001096 String accessId = bundle.getString(KEY_ACCOUNT_ACCESS_ID);
1097 return new Account(name, type, accessId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001098 }
1099 }.start();
1100 }
1101
1102 /**
1103 * Gets the previous name associated with the account or {@code null}, if
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001104 * none. This is intended so that clients of
1105 * {@link OnAccountsUpdateListener} can determine if an
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001106 * 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) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001119 throw e.rethrowFromSystemServer();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001120 }
1121 }
1122
1123 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001124 * 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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001129 * <p>This method requires the caller to have a signature match with the
1130 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001131 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001132 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08001136 * @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,
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001142 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001143 * @deprecated use
1144 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
1145 * instead
Dan Egnor661f0132010-02-19 11:23:00 -08001146 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001147 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001148 public AccountManagerFuture<Boolean> removeAccount(final Account account,
1149 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001150 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001151 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001152 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001153 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001154 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -08001155 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001156 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001157 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 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001167 * 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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001175 * <p>This method requires the caller to have a signature match with the
1176 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001177 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001178 * <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 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001182 * @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) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001211 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001212 public void doWork() throws RemoteException {
1213 mService.removeAccount(mResponse, account, activity != null);
1214 }
1215 }.start();
1216 }
1217
1218 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001219 * @see #removeAccount(Account, AccountManagerCallback, Handler)
1220 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001221 * @deprecated use
1222 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
1223 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001224 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001225 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001226 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) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001232 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001233 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001234 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001235 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001236 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001237 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 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001247 * @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) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001258 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001259 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.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001273 * <p>This method requires the caller to have a signature match with the
1274 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001275 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001276 * <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 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001280 * @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) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001290 throw e.rethrowFromSystemServer();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001291 }
1292 }
1293
1294 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001295 * 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 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001303 * <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 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001307 * @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
Dan Egnor661f0132010-02-19 11:23:00 -08001309 */
1310 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001311 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001312 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001313 if (authToken != null) {
1314 mService.invalidateAuthToken(accountType, authToken);
1315 }
Dan Egnor661f0132010-02-19 11:23:00 -08001316 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001317 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001318 }
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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001329 * <p>This method requires the caller to have a signature match with the
1330 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001331 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001332 * <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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001336 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001337 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001338 * @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.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001340 * @see #getAuthToken
Dan Egnor661f0132010-02-19 11:23:00 -08001341 */
1342 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -07001343 if (account == null) throw new IllegalArgumentException("account is null");
1344 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001345 try {
1346 return mService.peekAuthToken(account, authTokenType);
1347 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001348 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001349 }
1350 }
1351
1352 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001353 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -08001360 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001361 * <p>This method requires the caller to have a signature match with the
1362 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001363 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001364 * <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 *
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001368 * @param account The account whose password is to be set. Cannot be
1369 * {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001370 * @param password The password to set, null to clear the password
1371 */
1372 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -07001373 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001374 try {
1375 mService.setPassword(account, password);
1376 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001377 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001378 }
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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001388 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -08001391 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001392 * <p>It is safe to call this method from the main thread.
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001393 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001394 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08001398 * @param account The account whose password to clear
1399 */
1400 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001401 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001402 try {
1403 mService.clearPassword(account);
1404 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001405 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001406 }
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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001416 * <p>This method requires the caller to have a signature match with the
1417 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001418 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001419 * <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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001423 * @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
Dan Egnor661f0132010-02-19 11:23:00 -08001426 */
1427 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001428 if (account == null) throw new IllegalArgumentException("account is null");
1429 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001430 try {
1431 mService.setUserData(account, key, value);
1432 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001433 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001434 }
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 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001445 * <p>This method requires the caller to have a signature match with the
1446 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001447 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001448 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08001452 * @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) {
Fred Quintana382601f2010-03-25 12:25:10 -07001457 if (account == null) throw new IllegalArgumentException("account is null");
1458 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001459 try {
1460 mService.setAuthToken(account, authTokenType, authToken);
1461 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001462 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001463 }
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 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001473 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08001477 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001478 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001479 * @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 {
Fred Quintana382601f2010-03-25 12:25:10 -07001493 if (account == null) throw new IllegalArgumentException("account is null");
1494 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001495 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1496 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001497 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 }
Dan Egnor661f0132010-02-19 11:23:00 -08001506 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
Dan Egnor8e4378b2010-08-02 18:22:09 -07001516 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -08001519 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001520 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -08001524 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001525 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001526 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001527 * this function in API level 22.
1528 *
Dan Egnor661f0132010-02-19 11:23:00 -08001529 * <p>This method may be called from any thread, but the returned
1530 * {@link AccountManagerFuture} must not be used on the main thread.
1531 *
Dan Egnor661f0132010-02-19 11:23:00 -08001532 * @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:
Fred Quintana756b7352009-10-21 13:43:10 -07001546 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001547 * <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
Fred Quintana756b7352009-10-21 13:43:10 -07001550 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001551 *
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>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001561 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -08001564 */
1565 public AccountManagerFuture<Bundle> getAuthToken(
1566 final Account account, final String authTokenType, final Bundle options,
1567 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001568 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001569 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001570 final Bundle optionsIn = new Bundle();
1571 if (options != null) {
1572 optionsIn.putAll(options);
1573 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001574 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001575 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001576 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001577 public void doWork() throws RemoteException {
1578 mService.getAuthToken(mResponse, account, authTokenType,
1579 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001580 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001581 }
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
Dan Egnor8e4378b2010-08-02 18:22:09 -07001592 * 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,
Dan Egnor661f0132010-02-19 11:23:00 -08001597 * alerting the user that they need to enter a password at some point.
1598 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001599 * <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
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001602 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent and
1603 * notify {@link OnAccountsUpdateListener} which applications can
Dan Egnor8e4378b2010-08-02 18:22:09 -07001604 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001605 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001606 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -08001609 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001610 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -08001614 *
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 *
Dan Egnor661f0132010-02-19 11:23:00 -08001618 * @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
Dan Egnor661f0132010-02-19 11:23:00 -08001621 * @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 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001639 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001640 * <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>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001647 * 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.
Fred Quintanaad93a322011-09-08 13:21:01 -07001650 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1651 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001652 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001653 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001654 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001655 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001656 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001657 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001658 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001659 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001660 }
1661
1662 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001663 * 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
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001679 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent and
1680 * notify {@link OnAccountsUpdateListener} which applications can
Fred Quintanaad93a322011-09-08 13:21:01 -07001681 * 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 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001695 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001696 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001697 * this function in API level 22.
1698 *
Fred Quintanaad93a322011-09-08 13:21:01 -07001699 * @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(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001735 final Account account, final String authTokenType, final Bundle options,
1736 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001737 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001738
Fred Quintanaad93a322011-09-08 13:21:01 -07001739 if (account == null) throw new IllegalArgumentException("account is null");
1740 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001741 final Bundle optionsIn = new Bundle();
1742 if (options != null) {
1743 optionsIn.putAll(options);
1744 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001745 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001746 return new AmsTask(null, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001747 @Override
Fred Quintanaad93a322011-09-08 13:21:01 -07001748 public void doWork() throws RemoteException {
1749 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001750 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001751 }
1752 }.start();
1753 }
1754
1755 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001756 * 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.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001763 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001764 * <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.
Dan Egnor661f0132010-02-19 11:23:00 -08001767 *
Dan Egnor661f0132010-02-19 11:23:00 -08001768 * @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
Doug Zongkerff592dc2010-02-23 12:26:33 -08001784 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001785 * 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
Dan Egnor8e4378b2010-08-02 18:22:09 -07001793 * actual account creation process. If an error occurred,
1794 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001795 * <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
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001799 * any reason, including the user canceling the creation process or adding accounts
1800 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001801 * <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) {
Fred Quintana382601f2010-03-25 12:25:10 -07001809 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001810 final Bundle optionsIn = new Bundle();
1811 if (addAccountOptions != null) {
1812 optionsIn.putAll(addAccountOptions);
1813 }
1814 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001815
Dan Egnor661f0132010-02-19 11:23:00 -08001816 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001817 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001818 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001819 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001820 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001821 }
1822 }.start();
1823 }
1824
1825 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001826 * @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) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001842 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001843 public void doWork() throws RemoteException {
1844 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1845 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1846 }
1847 }.start();
1848 }
1849
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001850
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001851 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001852 * Adds shared accounts from a parent user to a secondary user. Adding the shared account
Amith Yamasani67df64b2012-12-14 12:09:36 -08001853 * 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.
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001856 * @param parentUser parent user
1857 * @param user target user
Amith Yamasani67df64b2012-12-14 12:09:36 -08001858 * @hide
1859 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001860 public void addSharedAccountsFromParentUser(UserHandle parentUser, UserHandle user) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001861 try {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001862 mService.addSharedAccountsFromParentUser(parentUser.getIdentifier(),
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08001863 user.getIdentifier(), mContext.getOpPackageName());
Amith Yamasani67df64b2012-12-14 12:09:36 -08001864 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001865 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001866 }
1867 }
1868
1869 /**
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001870 * Copies an account from one user to another user.
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001871 * @param account the account to copy
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001872 * @param fromUser the user to copy the account from
1873 * @param toUser the target user
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001874 * @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(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001883 final Account account, final UserHandle fromUser, final UserHandle toUser,
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001884 AccountManagerCallback<Boolean> callback, Handler handler) {
1885 if (account == null) throw new IllegalArgumentException("account is null");
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001886 if (toUser == null || fromUser == null) {
1887 throw new IllegalArgumentException("fromUser and toUser cannot be null");
1888 }
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001889
1890 return new Future2Task<Boolean>(handler, callback) {
1891 @Override
1892 public void doWork() throws RemoteException {
1893 mService.copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001894 mResponse, account, fromUser.getIdentifier(), toUser.getIdentifier());
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001895 }
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 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001907 * @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) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001918 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001919 }
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) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001931 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001932 }
1933 }
1934
1935 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001936 * 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 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001951 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08001955 * @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>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001973 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001974 * <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
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001979 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1980 * password prompt.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001981 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001982 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001983 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001984 * credential was validated/created.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001985 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001986 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001987 * <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>
Fred Quintana756b7352009-10-21 13:43:10 -07001994 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001995 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1996 final Bundle options,
1997 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001998 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002000 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) {
Fred Quintana382601f2010-03-25 12:25:10 -07002014 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002015 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07002016 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002017 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002018 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002019 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
2020 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07002021 }
Fred Quintana33269202009-04-20 16:05:10 -07002022 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002023 }
2024
Fred Quintana756b7352009-10-21 13:43:10 -07002025 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002026 * 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.
Fred Quintana756b7352009-10-21 13:43:10 -07002030 *
Dan Egnor661f0132010-02-19 11:23:00 -08002031 * <p>This method may be called from any thread, but the returned
2032 * {@link AccountManagerFuture} must not be used on the main thread.
2033 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002034 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08002038 * @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:
Fred Quintana756b7352009-10-21 13:43:10 -07002056 * <ul>
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002057 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
Dan Egnor661f0132010-02-19 11:23:00 -08002058 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07002059 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002060 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002061 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08002062 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002063 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07002064 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002065 * <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>
Fred Quintana756b7352009-10-21 13:43:10 -07002072 */
2073 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
2074 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07002075 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002076 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002077 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07002078 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07002079 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002080 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002081 public void doWork() throws RemoteException {
2082 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07002083 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07002084 }
Fred Quintana33269202009-04-20 16:05:10 -07002085 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002086 }
2087
Fred Quintana756b7352009-10-21 13:43:10 -07002088 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002089 * 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.
Fred Quintana756b7352009-10-21 13:43:10 -07002092 *
Dan Egnor661f0132010-02-19 11:23:00 -08002093 * <p>This method may be called from any thread, but the returned
2094 * {@link AccountManagerFuture} must not be used on the main thread.
2095 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002096 * <p>This method requires the caller to have the same signature as the
2097 * authenticator associated with the specified account type.
Dan Egnor661f0132010-02-19 11:23:00 -08002098 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002099 * <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 *
Dan Egnor661f0132010-02-19 11:23:00 -08002103 * @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.
Dan Egnor8e4378b2010-08-02 18:22:09 -07002118 * If an error occurred, {@link AccountManagerFuture#getResult()}
2119 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07002120 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002121 * <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
Fred Quintana756b7352009-10-21 13:43:10 -07002127 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002128 */
2129 public AccountManagerFuture<Bundle> editProperties(final String accountType,
2130 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002131 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07002132 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07002133 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002134 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002135 public void doWork() throws RemoteException {
2136 mService.editProperties(mResponse, accountType, activity != null);
2137 }
Fred Quintana33269202009-04-20 16:05:10 -07002138 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002139 }
2140
Amith Yamasani12747872015-12-07 14:19:49 -08002141 /**
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) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002153 throw re.rethrowFromSystemServer();
Amith Yamasani12747872015-12-07 14:19:49 -08002154 }
2155 }
2156
Fred Quintanaa698f422009-04-08 19:14:54 -07002157 private void ensureNotOnMainThread() {
2158 final Looper looper = Looper.myLooper();
2159 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08002160 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);
Fred Quintana751fdc02010-02-09 14:13:18 -08002164 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2165 throw exception;
2166 }
Fred Quintana60307342009-03-24 22:48:12 -07002167 }
2168 }
2169
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002170 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
2171 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07002172 handler = handler == null ? mMainHandler : handler;
2173 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002174 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002175 public void run() {
2176 callback.run(future);
2177 }
2178 });
2179 }
Fred Quintana60307342009-03-24 22:48:12 -07002180
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002181 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002182 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002183 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;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002188 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002189 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002190 public void run() {
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002191 synchronized (mAccountsUpdatedListeners) {
2192 try {
2193 if (mAccountsUpdatedListeners.containsKey(listener)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002194 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 }
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002208 }
2209 } catch (SQLException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002210 // Better luck next time. If the problem was disk-full,
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002211 // the STORAGE_OK intent will re-trigger the update.
2212 Log.e(TAG, "Can't update accounts", e);
2213 }
Costin Manolacheb6437242009-09-10 16:14:12 -07002214 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002215 }
2216 });
2217 }
2218
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002219 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07002220 final IAccountManagerResponse mResponse;
2221 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002222 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07002223 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002224 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002225 super(new Callable<Bundle>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002226 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002227 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();
Fred Quintana33269202009-04-20 16:05:10 -07002236 }
2237
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002238 public final AccountManagerFuture<Bundle> start() {
2239 try {
2240 doWork();
2241 } catch (RemoteException e) {
2242 setException(e);
2243 }
Fred Quintana33269202009-04-20 16:05:10 -07002244 return this;
Fred Quintana60307342009-03-24 22:48:12 -07002245 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002246
Sandra Kwan0b84b452016-01-20 15:25:42 -08002247 @Override
Fred Quintana96580e02010-03-04 13:42:42 -08002248 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
Fred Quintanaa698f422009-04-08 19:14:54 -07002258 public abstract void doWork() throws RemoteException;
2259
2260 private Bundle internalGetResult(Long timeout, TimeUnit unit)
2261 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08002262 if (!isDone()) {
2263 ensureNotOnMainThread();
2264 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002265 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
Sandra Kwan0b84b452016-01-20 15:25:42 -08002298 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002299 public Bundle getResult()
2300 throws OperationCanceledException, IOException, AuthenticatorException {
2301 return internalGetResult(null, null);
2302 }
2303
Sandra Kwan0b84b452016-01-20 15:25:42 -08002304 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002305 public Bundle getResult(long timeout, TimeUnit unit)
2306 throws OperationCanceledException, IOException, AuthenticatorException {
2307 return internalGetResult(timeout, unit);
2308 }
2309
Sandra Kwan0b84b452016-01-20 15:25:42 -08002310 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002311 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 {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002319 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002320 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07002321 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07002322 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
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002327 } else if (bundle.getBoolean("retry")) {
2328 try {
2329 doWork();
2330 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002331 throw e.rethrowFromSystemServer();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002332 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002333 } else {
2334 set(bundle);
2335 }
2336 }
2337
Sandra Kwan0b84b452016-01-20 15:25:42 -08002338 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002339 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002340 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
Fred Quintanaa698f422009-04-08 19:14:54 -07002344 cancel(true /* mayInterruptIfRunning */);
2345 return;
2346 }
2347 setException(convertErrorToException(code, message));
2348 }
2349 }
2350
Fred Quintana60307342009-03-24 22:48:12 -07002351 }
2352
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002353 private abstract class BaseFutureTask<T> extends FutureTask<T> {
2354 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002355 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002356
2357 public BaseFutureTask(Handler handler) {
2358 super(new Callable<T>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002359 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002360 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07002361 throw new IllegalStateException("this should never be called");
2362 }
2363 });
Fred Quintanaa698f422009-04-08 19:14:54 -07002364 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002365 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07002366 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002367
2368 public abstract void doWork() throws RemoteException;
2369
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002370 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07002371
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002372 protected void postRunnableToHandler(Runnable runnable) {
2373 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
2374 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07002375 }
2376
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002377 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002378 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002379 doWork();
2380 } catch (RemoteException e) {
2381 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07002382 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002383 }
2384
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002385 protected class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002386 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002387 public void onResult(Bundle bundle) {
2388 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002389 T result = bundleToResult(bundle);
2390 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002391 return;
2392 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002393 set(result);
2394 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002395 } catch (ClassCastException e) {
2396 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002397 } catch (AuthenticatorException e) {
2398 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07002399 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002400 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07002401 }
2402
Sandra Kwan0b84b452016-01-20 15:25:42 -08002403 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002404 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002405 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
Fred Quintanaa698f422009-04-08 19:14:54 -07002409 cancel(true /* mayInterruptIfRunning */);
2410 return;
2411 }
2412 setException(convertErrorToException(code, message));
2413 }
2414 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002415 }
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
Sandra Kwan0b84b452016-01-20 15:25:42 -08002425 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002426 protected void done() {
2427 if (mCallback != null) {
2428 postRunnableToHandler(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002429 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002430 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 {
Fred Quintana53bd2522010-02-05 15:28:12 -08002444 if (!isDone()) {
2445 ensureNotOnMainThread();
2446 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002447 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
Sandra Kwan0b84b452016-01-20 15:25:42 -08002480 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002481 public T getResult()
2482 throws OperationCanceledException, IOException, AuthenticatorException {
2483 return internalGetResult(null, null);
2484 }
2485
Sandra Kwan0b84b452016-01-20 15:25:42 -08002486 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002487 public T getResult(long timeout, TimeUnit unit)
2488 throws OperationCanceledException, IOException, AuthenticatorException {
2489 return internalGetResult(timeout, unit);
2490 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002491
Fred Quintana60307342009-03-24 22:48:12 -07002492 }
2493
Fred Quintanaa698f422009-04-08 19:14:54 -07002494 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002495 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002496 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002497 }
Fred Quintana60307342009-03-24 22:48:12 -07002498
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002499 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002500 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002501 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002502
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002503 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002504 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002505 }
2506
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002507 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002508 return new IllegalArgumentException(message);
2509 }
2510
2511 return new AuthenticatorException(message);
2512 }
2513
sunjianf29d5492017-05-11 15:42:31 -07002514 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
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002526 private class GetAuthTokenByTypeAndFeaturesTask
2527 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002528 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2529 final String[] features, Activity activityForPrompting,
2530 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002531 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002532 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 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002541 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002542 final String mAccountType;
2543 final String mAuthTokenType;
2544 final String[] mFeatures;
2545 final Bundle mAddAccountOptions;
2546 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002547 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002548 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002549
Sandra Kwan0b84b452016-01-20 15:25:42 -08002550 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002551 public void doWork() throws RemoteException {
sunjianf29d5492017-05-11 15:42:31 -07002552 getAccountByTypeAndFeatures(mAccountType, mFeatures,
2553 new AccountManagerCallback<Bundle>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002554 @Override
sunjianf29d5492017-05-11 15:42:31 -07002555 public void run(AccountManagerFuture<Bundle> future) {
2556 String accountName = null;
2557 String accountType = null;
Fred Quintana33269202009-04-20 16:05:10 -07002558 try {
sunjianf29d5492017-05-11 15:42:31 -07002559 Bundle result = future.getResult();
2560 accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2561 accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002562 } 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;
Fred Quintana33269202009-04-20 16:05:10 -07002571 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002572
sunjianf29d5492017-05-11 15:42:31 -07002573 if (accountName == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002574 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();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002582 result.putString(KEY_ACCOUNT_NAME, null);
2583 result.putString(KEY_ACCOUNT_TYPE, null);
2584 result.putString(KEY_AUTHTOKEN, null);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002585 result.putBinder(KEY_ACCOUNT_ACCESS_ID, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002586 try {
2587 mResponse.onResult(result);
2588 } catch (RemoteException e) {
2589 // this will never happen
2590 }
2591 // we are done
2592 }
sunjianf29d5492017-05-11 15:42:31 -07002593 } else {
2594 mNumAccounts = 1;
2595 Account account = new Account(accountName, accountType);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002596 // have a single account, return an authtoken for it
2597 if (mActivity == null) {
sunjianf29d5492017-05-11 15:42:31 -07002598 mFuture = getAuthToken(account, mAuthTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002599 false /* notifyAuthFailure */, mMyCallback, mHandler);
2600 } else {
sunjianf29d5492017-05-11 15:42:31 -07002601 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002602 mActivity, mMyCallback, mHandler);
2603 }
Fred Quintana33269202009-04-20 16:05:10 -07002604 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002605 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002606 }
2607
Sandra Kwan0b84b452016-01-20 15:25:42 -08002608 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002609 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002610 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002611 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 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002619 final String accessId = result.getString(KEY_ACCOUNT_ACCESS_ID);
2620 final Account account = new Account(accountName, accountType, accessId);
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002621 mNumAccounts = 1;
2622 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2623 mMyCallback, mHandler);
2624 return;
2625 }
2626 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002627 } catch (OperationCanceledException e) {
2628 cancel(true /* mayInterruptIfRUnning */);
2629 } catch (IOException e) {
2630 setException(e);
2631 } catch (AuthenticatorException e) {
2632 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002633 }
2634 }
2635 }
2636
Fred Quintana756b7352009-10-21 13:43:10 -07002637 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -08002638 * This convenience helper combines the functionality of {@link #getAccountsByTypeAndFeatures},
2639 * {@link #getAuthToken}, and {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002640 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002641 * <p>
2642 * This method gets a list of the accounts matching specific type and feature set which are
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002643 * 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
Dmitry Dementyev52745472016-12-02 10:27:45 -08002645 * 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.
Dan Egnor661f0132010-02-19 11:23:00 -08002648 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002649 * <p>
2650 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
2651 * not be used on the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -08002652 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002653 * <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.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002656 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002657 * @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>
Dan Egnor661f0132010-02-19 11:23:00 -08002679 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002680 * 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>
Fred Quintana756b7352009-10-21 13:43:10 -07002689 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002690 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002691 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002692 final Activity activity, final Bundle addAccountOptions,
sunjianf29d5492017-05-11 15:42:31 -07002693 final Bundle getAuthTokenOptions, final AccountManagerCallback<Bundle> callback,
2694 final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002695 if (accountType == null) throw new IllegalArgumentException("account type is null");
2696 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002697 final GetAuthTokenByTypeAndFeaturesTask task =
2698 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002699 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002700 task.start();
2701 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002702 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002703
Fred Quintana1121bb52011-09-14 23:19:35 -07002704 /**
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002705 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
2706 * String, String[], Bundle)}.
2707 *
Fred Quintana1121bb52011-09-14 23:19:35 -07002708 * 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
Mark Fickettab249e02012-09-05 09:45:47 -04002711 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002712 * <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}.
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002715 * 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.
Fred Quintana1121bb52011-09-14 23:19:35 -07002718 * <p>
2719 * The most common case is to call this with one account type, e.g.:
2720 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002721 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002722 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002723 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2724 * selected one, according to the caller's definition of selected.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002725 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
Fred Quintana1121bb52011-09-14 23:19:35 -07002726 * 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
Simranjit Singh Kohli734f8fb2015-05-22 14:00:32 -07002729 * when adding an account. If not specified then this field will not limit the displayed
2730 * account types when adding an account.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002731 * @param alwaysPromptForAccount boolean that is ignored.
Fred Quintanad88324d2011-09-19 11:43:05 -07002732 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002733 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002734 * @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
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002738 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002739 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002740 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002741 */
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002742 @Deprecated
2743 static public Intent newChooseAccountIntent(
2744 Account selectedAccount,
Baligh Uddinf2d248d2015-07-10 03:01:47 +00002745 ArrayList<Account> allowableAccounts,
Fred Quintana1121bb52011-09-14 23:19:35 -07002746 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002747 boolean alwaysPromptForAccount,
2748 String descriptionOverrideText,
2749 String addAccountAuthTokenType,
2750 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002751 Bundle addAccountOptions) {
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002752 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}.
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002770 * 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.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002773 * <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) {
Fred Quintana1121bb52011-09-14 23:19:35 -07002804 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002805 ComponentName componentName = ComponentName.unflattenFromString(
2806 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2807 intent.setClassName(componentName.getPackageName(),
2808 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002809 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
Craig Lafayette3c9c71d2015-07-14 10:48:46 -04002810 allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts));
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002811 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2812 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002813 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2814 addAccountOptions);
2815 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002816 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);
Fred Quintana1121bb52011-09-14 23:19:35 -07002823 return intent;
2824 }
2825
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002826 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002827 Maps.newHashMap();
2828
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002829 private final HashMap<OnAccountsUpdateListener, Set<String> > mAccountsUpdatedListenersTypes =
2830 Maps.newHashMap();
2831
Fred Quintanad9d2f112009-04-23 13:36:27 -07002832 /**
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002833 * BroadcastReceiver that listens for the ACTION_VISIBLE_ACCOUNTS_CHANGED intent
Fred Quintanad9d2f112009-04-23 13:36:27 -07002834 * 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() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002838 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002839 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002840 final Account[] accounts = getAccounts();
2841 // send the result to the listeners
2842 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002843 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002844 mAccountsUpdatedListeners.entrySet()) {
2845 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002846 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002847 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002848 }
2849 };
2850
2851 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -08002852 * Adds an {@link OnAccountsUpdateListener} to this instance of the {@link AccountManager}. This
2853 * listener will be notified whenever user or AbstractAcccountAuthenticator made changes to
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002854 * accounts of any type related to the caller. This method is equivalent to
2855 * addOnAccountsUpdatedListener(listener, handler, updateImmediately, null)
Dan Egnor661f0132010-02-19 11:23:00 -08002856 *
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002857 * @see #addOnAccountsUpdatedListener(OnAccountsUpdateListener, Handler, boolean,
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002858 * 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.
Dmitry Dementyev52745472016-12-02 10:27:45 -08002871 * <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}.
Dmitry Dementyev52745472016-12-02 10:27:45 -08002877 * <p>
2878 * It is safe to call this method from the main thread.
Ian Pedowitz845d14d2015-08-04 07:47:37 -07002879 *
Dan Egnor661f0132010-02-19 11:23:00 -08002880 * @param listener The listener to send notifications to
Dmitry Dementyev52745472016-12-02 10:27:45 -08002881 * @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
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002885 * @param accountTypes If set, only changes to accounts of given types will be reported.
Fred Quintanad9d2f112009-04-23 13:36:27 -07002886 * @throws IllegalArgumentException if listener is null
2887 * @throws IllegalStateException if listener was already added
2888 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002889 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002890 Handler handler, boolean updateImmediately, String[] accountTypes) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07002891 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);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002901 if (accountTypes != null) {
2902 mAccountsUpdatedListenersTypes.put(listener,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002903 new HashSet<String>(Arrays.asList(accountTypes)));
2904 } else {
2905 mAccountsUpdatedListenersTypes.put(listener, null);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002906 }
Dmitry Dementyev52745472016-12-02 10:27:45 -08002907
Fred Quintanad9d2f112009-04-23 13:36:27 -07002908 if (wasEmpty) {
2909 // Register a broadcast receiver to monitor account changes
2910 IntentFilter intentFilter = new IntentFilter();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002911 intentFilter.addAction(ACTION_VISIBLE_ACCOUNTS_CHANGED);
Costin Manolacheb6437242009-09-10 16:14:12 -07002912 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002913 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002914 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2915 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002916
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 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002924 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002925 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002926 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002927 }
2928 }
2929
2930 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002931 * 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
Fred Quintanad9d2f112009-04-23 13:36:27 -07002940 * @throws IllegalArgumentException if listener is null
2941 * @throws IllegalStateException if listener was not already added
2942 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002943 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002944 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002945 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002946 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002947 Log.e(TAG, "Listener was not previously added");
2948 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002949 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002950 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 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002957 mAccountsUpdatedListeners.remove(listener);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002958 mAccountsUpdatedListenersTypes.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002959 if (mAccountsUpdatedListeners.isEmpty()) {
2960 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2961 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002962 try {
2963 mService.unregisterAccountListener(accountsArray, mContext.getOpPackageName());
2964 } catch (RemoteException e) {
2965 throw e.rethrowFromSystemServer();
2966 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002967 }
2968 }
Sandra Kwan78812282015-11-04 11:19:47 -08002969
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
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002982 * this api alone. #finishSession should be called after this to install the
2983 * account on device.
Sandra Kwan78812282015-11-04 11:19:47 -08002984 *
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.
Sandra Kwan78812282015-11-04 11:19:47 -08003007 * <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>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003029 * @see #finishSession
Sandra Kwan78812282015-11-04 11:19:47 -08003030 */
Sandra Kwane68c37e2015-11-12 17:11:49 -08003031 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) {
Sandra Kwan78812282015-11-04 11:19:47 -08003039 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 {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003049 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
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003062 * saved credentials for the account until {@link #finishSession} is called.
Sandra Kwane68c37e2015-11-12 17:11:49 -08003063 * <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
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003068 * updated by calling this API alone. #finishSession should be called after
3069 * this to update local credentials
Sandra Kwane68c37e2015-11-12 17:11:49 -08003070 *
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
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003088 * successfully re-authenticated to the account:
Sandra Kwane68c37e2015-11-12 17:11:49 -08003089 * <ul>
3090 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
3091 * updating the local credentials on device later.
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003092 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3093 * status of the account
Sandra Kwane68c37e2015-11-12 17:11:49 -08003094 * </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>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003109 * @see #finishSession
Sandra Kwane68c37e2015-11-12 17:11:49 -08003110 */
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 }
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003121
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
Sandra Kwane68c37e2015-11-12 17:11:49 -08003130 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,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003138 optionsIn);
Sandra Kwan78812282015-11-04 11:19:47 -08003139 }
3140 }.start();
3141 }
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003142
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
Hongming Jin8b442752016-06-26 10:36:21 -07003169 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3170 * status of the account
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003171 * </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) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003196 return finishSessionAsUser(
3197 sessionBundle,
3198 activity,
3199 Process.myUserHandle(),
3200 callback,
3201 handler);
3202 }
3203
3204 /**
3205 * @see #finishSession
3206 * @hide
3207 */
3208 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06003209 @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
Sandra Kwan0b84b452016-01-20 15:25:42 -08003210 public AccountManagerFuture<Bundle> finishSessionAsUser(
3211 final Bundle sessionBundle,
3212 final Activity activity,
3213 final UserHandle userHandle,
3214 AccountManagerCallback<Bundle> callback,
3215 Handler handler) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003216 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 {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003227 mService.finishSessionAsUser(
3228 mResponse,
3229 sessionBundle,
3230 activity != null,
3231 appInfo,
3232 userHandle.getIdentifier());
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003233 }
3234 }.start();
3235 }
Sandra Kwan390c9d22016-01-12 14:13:37 -08003236
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.
Sandra Kwan390c9d22016-01-12 14:13:37 -08003251 */
Sandra Kwan390c9d22016-01-12 14:13:37 -08003252 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) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003266 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003267 public void doWork() throws RemoteException {
3268 mService.isCredentialsUpdateSuggested(
3269 mResponse,
3270 account,
3271 statusToken);
3272 }
Sandra Kwan0b84b452016-01-20 15:25:42 -08003273 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003274 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 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003282
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 }
Fred Quintana60307342009-03-24 22:48:12 -07003327}