blob: bb182f2b29486a05a6bb95d3a20bd030c38f69b3 [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;
Mathew Inwoodad576cc2018-08-06 16:51:18 +010030import android.annotation.UnsupportedAppUsage;
Fred Quintana60307342009-03-24 22:48:12 -070031import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080032import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070033import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070034import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080035import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070036import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070037import android.content.IntentSender;
Amith Yamasani12b8e132013-03-14 10:48:07 -070038import android.content.res.Resources;
Dmitry Dementyev52745472016-12-02 10:27:45 -080039import android.content.pm.ApplicationInfo;
40import android.content.pm.PackageManager;
Costin Manolacheb6437242009-09-10 16:14:12 -070041import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080042import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.os.Bundle;
44import android.os.Handler;
45import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070046import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080047import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080048import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080049import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080050import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080051import android.util.Log;
52
53import com.android.internal.R;
54import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070055
Fred Quintanaa698f422009-04-08 19:14:54 -070056import java.io.IOException;
Dmitry Dementyev52745472016-12-02 10:27:45 -080057import java.lang.annotation.Retention;
58import java.lang.annotation.RetentionPolicy;
59import java.lang.SuppressWarnings;
Fred Quintana1121bb52011-09-14 23:19:35 -070060import java.util.ArrayList;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080061import java.util.Arrays;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080062import java.util.HashMap;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080063import java.util.HashSet;
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -070064import java.util.List;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080065import java.util.Map;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080066import java.util.Set;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import java.util.concurrent.Callable;
68import java.util.concurrent.CancellationException;
69import java.util.concurrent.ExecutionException;
70import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080072import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070073
74/**
Dan Egnor661f0132010-02-19 11:23:00 -080075 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070076 * online accounts. The user enters credentials (username and password) once
77 * per account, granting applications access to online resources with
78 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070079 *
Dan Egnor661f0132010-02-19 11:23:00 -080080 * <p>Different online services have different ways of handling accounts and
81 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070082 * modules for different <em>account types</em>. Authenticators (which may be
83 * written by third parties) handle the actual details of validating account
84 * credentials and storing account information. For example, Google, Facebook,
85 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080086 *
87 * <p>Many servers support some notion of an <em>authentication token</em>,
88 * which can be used to authenticate a request to the server without sending
89 * the user's actual password. (Auth tokens are normally created with a
90 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070091 * can generate auth tokens for applications, so the application doesn't need to
92 * handle passwords directly. Auth tokens are normally reusable and cached by
93 * AccountManager, but must be refreshed periodically. It's the responsibility
94 * of applications to <em>invalidate</em> auth tokens when they stop working so
95 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080096 *
97 * <p>Applications accessing a server normally go through these steps:
98 *
99 * <ul>
100 * <li>Get an instance of AccountManager using {@link #get(Context)}.
101 *
102 * <li>List the available accounts using {@link #getAccountsByType} or
103 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
104 * be interested in accounts with one particular <em>type</em>, which
105 * identifies the authenticator. Account <em>features</em> are used to
106 * identify particular account subtypes and capabilities. Both the account
107 * type and features are authenticator-specific strings, and must be known by
108 * the application in coordination with its preferred authenticators.
109 *
110 * <li>Select one or more of the available accounts, possibly by asking the
111 * user for their preference. If no suitable accounts are available,
112 * {@link #addAccount} may be called to prompt the user to create an
113 * account of the appropriate type.
114 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700115 * <li><b>Important:</b> If the application is using a previously remembered
116 * account selection, it must make sure the account is still in the list
117 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
118 * for an account no longer on the device results in an undefined failure.
119 *
Dan Egnor661f0132010-02-19 11:23:00 -0800120 * <li>Request an auth token for the selected account(s) using one of the
121 * {@link #getAuthToken} methods or related helpers. Refer to the description
122 * of each method for exact usage and error handling details.
123 *
124 * <li>Make the request using the auth token. The form of the auth token,
125 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700126 * service you are accessing. The application may use whatever network and
127 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800128 *
129 * <li><b>Important:</b> If the request fails with an authentication error,
130 * it could be that a cached auth token is stale and no longer honored by
131 * the server. The application must call {@link #invalidateAuthToken} to remove
132 * the token from the cache, otherwise requests will continue failing! After
133 * invalidating the auth token, immediately go back to the "Request an auth
134 * token" step above. If the process fails the second time, then it can be
135 * treated as a "genuine" authentication failure and the user notified or other
136 * appropriate actions taken.
137 * </ul>
138 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700139 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800140 * prompt for credentials, present options, or ask the user to add an account.
141 * The caller may choose whether to allow AccountManager to directly launch the
142 * necessary user interface and wait for the user, or to return an Intent which
143 * the caller may use to launch the interface, or (in some cases) to install a
144 * notification which the user can select at any time to launch the interface.
145 * To have AccountManager launch the interface directly, the caller must supply
146 * the current foreground {@link Activity} context.
147 *
148 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700149 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800150 * run asynchronously. If a callback is provided then
151 * {@link AccountManagerCallback#run} will be invoked on the Handler's
152 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700153 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
154 * on the {@link AccountManagerFuture} returned by the method (and also passed
155 * to the callback). This method waits for the operation to complete (if
156 * necessary) and either returns the result or throws an exception if an error
157 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800158 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700159 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800160 *
161 * <p>Requests which may block, including
162 * {@link AccountManagerFuture#getResult()}, must never be called on
163 * the application's main event thread. These operations throw
164 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700165 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600166@SystemService(Context.ACCOUNT_SERVICE)
Fred Quintana60307342009-03-24 22:48:12 -0700167public class AccountManager {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800168
Fred Quintana60307342009-03-24 22:48:12 -0700169 private static final String TAG = "AccountManager";
170
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700171 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
172 public static final int ERROR_CODE_NETWORK_ERROR = 3;
173 public static final int ERROR_CODE_CANCELED = 4;
174 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
175 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
176 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
177 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700178 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700179
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800180 /** @hide */
181 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100182 /** @hide */
183 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800184
Dan Egnor661f0132010-02-19 11:23:00 -0800185 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700186 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800187 * from methods which return information about a particular account.
188 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700189 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800190
191 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700192 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800193 * from methods which return information about a particular account.
194 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700195 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800196
197 /**
Svet Ganovd4696122016-09-24 13:57:45 -0700198 * Bundle key used for the account access id used for noting the
199 * account was accessed when unmarshaled from a parcel.
Svet Ganovf6d424f12016-09-20 20:18:53 -0700200 *
201 * @hide
202 */
Svet Ganovd4696122016-09-24 13:57:45 -0700203 public static final String KEY_ACCOUNT_ACCESS_ID = "accountAccessId";
Svet Ganovf6d424f12016-09-20 20:18:53 -0700204
205 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700206 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800207 * from {@link #getAuthToken} and friends.
208 */
209 public static final String KEY_AUTHTOKEN = "authtoken";
210
211 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700212 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800213 * may require the caller to interact with the user. The Intent can
214 * be used to start the corresponding user interface activity.
215 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700216 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800217
218 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700219 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800220 * {@link #confirmCredentials}, rather than prompting the user with
221 * the standard password prompt.
222 */
223 public static final String KEY_PASSWORD = "password";
224
225 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700226
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700227 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
228 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800229 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700230 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
231 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800232 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
233 public static final String KEY_ERROR_CODE = "errorCode";
234 public static final String KEY_ERROR_MESSAGE = "errorMessage";
235 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700236
Costin Manolachea40c6302010-12-13 14:50:45 -0800237 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800238 * Bundle key used to supply the last time the credentials of the account
239 * were authenticated successfully. Time is specified in milliseconds since
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700240 * epoch. Associated time is updated on successful authentication of account
241 * on adding account, confirming credentials, or updating credentials.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800242 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700243 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800244
245 /**
sunjian87d0c3c2017-07-14 11:54:46 -0700246 * The UID of caller app.
Costin Manolachea40c6302010-12-13 14:50:45 -0800247 */
248 public static final String KEY_CALLER_UID = "callerUid";
sunjian87d0c3c2017-07-14 11:54:46 -0700249
250 /**
251 * The process id of caller app.
252 */
Costin Manolachea40c6302010-12-13 14:50:45 -0800253 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800254
Costin Manolached6060452011-01-24 16:11:36 -0800255 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700256 * The Android package of the caller will be set in the options bundle by the
257 * {@link AccountManager} and will be passed to the AccountManagerService and
258 * to the AccountAuthenticators. The uid of the caller will be known by the
259 * AccountManagerService as well as the AccountAuthenticators so they will be able to
260 * verify that the package is consistent with the uid (a uid might be shared by many
261 * packages).
262 */
263 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
264
265 /**
Costin Manolached6060452011-01-24 16:11:36 -0800266 * Boolean, if set and 'customTokens' the authenticator is responsible for
267 * notifications.
268 * @hide
269 */
270 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
271
Sandra Kwan78812282015-11-04 11:19:47 -0800272 /**
273 * Bundle key used for a {@link Bundle} in result from
274 * {@link #startAddAccountSession} and friends which returns session data
275 * for installing an account later.
276 */
277 public static final String KEY_ACCOUNT_SESSION_BUNDLE = "accountSessionBundle";
278
279 /**
280 * Bundle key used for the {@link String} account status token in result
281 * from {@link #startAddAccountSession} and friends which returns
282 * information about a particular account.
283 */
284 public static final String KEY_ACCOUNT_STATUS_TOKEN = "accountStatusToken";
285
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700286 public static final String ACTION_AUTHENTICATOR_INTENT =
287 "android.accounts.AccountAuthenticator";
288 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800289 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700290 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
291
Dmitry Dementyev52745472016-12-02 10:27:45 -0800292 /** @hide */
293 @Retention(RetentionPolicy.SOURCE)
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700294 @IntDef(prefix = { "VISIBILITY_" }, value = {
295 VISIBILITY_UNDEFINED,
296 VISIBILITY_VISIBLE,
297 VISIBILITY_USER_MANAGED_VISIBLE,
298 VISIBILITY_NOT_VISIBLE,
299 VISIBILITY_USER_MANAGED_NOT_VISIBLE
300 })
Dmitry Dementyev52745472016-12-02 10:27:45 -0800301 public @interface AccountVisibility {
302 }
303
304 /**
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800305 * Account visibility was not set. Default visibility value will be used.
306 * See {@link #PACKAGE_NAME_KEY_LEGACY_VISIBLE}, {@link #PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE}
Dmitry Dementyev52745472016-12-02 10:27:45 -0800307 */
308 public static final int VISIBILITY_UNDEFINED = 0;
309
310 /**
311 * Account is always visible to given application and only authenticator can revoke visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800312 */
313 public static final int VISIBILITY_VISIBLE = 1;
314
315 /**
316 * Account is visible to given application, but user can revoke visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800317 */
318 public static final int VISIBILITY_USER_MANAGED_VISIBLE = 2;
319
320 /**
321 * Account is not visible to given application and only authenticator can grant visibility.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800322 */
323 public static final int VISIBILITY_NOT_VISIBLE = 3;
324
325 /**
326 * Account is not visible to given application, but user can reveal it, for example, using
327 * {@link #newChooseAccountIntent(Account, List, String[], String, String, String[], Bundle)}
Dmitry Dementyev52745472016-12-02 10:27:45 -0800328 */
329 public static final int VISIBILITY_USER_MANAGED_NOT_VISIBLE = 4;
330
331 /**
Svet Ganovf6d424f12016-09-20 20:18:53 -0700332 * Token type for the special case where a UID has access only to an account
333 * but no authenticator specific auth token types.
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +0000334 *
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700335 * @hide
336 */
Svet Ganovf6d424f12016-09-20 20:18:53 -0700337 public static final String ACCOUNT_ACCESS_TOKEN_TYPE =
338 "com.android.AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE";
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700339
Mathew Inwoodad576cc2018-08-06 16:51:18 +0100340 @UnsupportedAppUsage
Fred Quintana60307342009-03-24 22:48:12 -0700341 private final Context mContext;
342 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700343 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800344
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700345 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800346 * Action sent as a broadcast Intent by the AccountsService when accounts are added, accounts
347 * are removed, or an account's credentials (saved password, etc) are changed.
Dan Egnor661f0132010-02-19 11:23:00 -0800348 *
349 * @see #addOnAccountsUpdatedListener
Dmitry Dementyeva461e302017-04-12 11:00:48 -0700350 * @see #ACTION_ACCOUNT_REMOVED
Dmitry Dementyev52745472016-12-02 10:27:45 -0800351 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700352 * @deprecated use {@link #addOnAccountsUpdatedListener} to get account updates in runtime.
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700353 */
Jeff Sharkey32ee8ee2017-03-08 20:17:51 -0700354 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
355 @BroadcastBehavior(includeBackground = true)
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700356 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
357 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700358
Fred Quintana33269202009-04-20 16:05:10 -0700359 /**
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700360 * Action sent as a broadcast Intent by the AccountsService when any account is removed
361 * or renamed. Only applications which were able to see the account will receive the intent.
362 * Intent extra will include the following fields:
363 * <ul>
364 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the removed account
365 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
366 * </ul>
Dmitry Dementyeva461e302017-04-12 11:00:48 -0700367 */
368 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
369 @BroadcastBehavior(includeBackground = true)
370 public static final String ACTION_ACCOUNT_REMOVED =
371 "android.accounts.action.ACCOUNT_REMOVED";
372
373 /**
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700374 * Action sent as a broadcast Intent to specific package by the AccountsService
375 * when account visibility or account's credentials (saved password, etc) are changed.
376 *
377 * @see #addOnAccountsUpdatedListener
378 *
379 * @hide
380 */
381 public static final String ACTION_VISIBLE_ACCOUNTS_CHANGED =
382 "android.accounts.action.VISIBLE_ACCOUNTS_CHANGED";
383
384 /**
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700385 * Key to set visibility for applications which satisfy one of the following conditions:
386 * <ul>
387 * <li>Target API level below {@link android.os.Build.VERSION_CODES#O} and have
388 * deprecated {@link android.Manifest.permission#GET_ACCOUNTS} permission.
389 * </li>
390 * <li> Have {@link android.Manifest.permission#GET_ACCOUNTS_PRIVILEGED} permission. </li>
391 * <li> Have the same signature as authenticator. </li>
392 * <li> Have {@link android.Manifest.permission#READ_CONTACTS} permission and
393 * account type may be associated with contacts data - (verified by
394 * {@link android.Manifest.permission#WRITE_CONTACTS} permission check for the authenticator).
395 * </li>
396 * </ul>
397 * See {@link #getAccountVisibility}. If the value was not set by authenticator
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800398 * {@link #VISIBILITY_USER_MANAGED_VISIBLE} is used.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800399 */
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700400 public static final String PACKAGE_NAME_KEY_LEGACY_VISIBLE =
401 "android:accounts:key_legacy_visible";
402
403 /**
404 * Key to set default visibility for applications which don't satisfy conditions in
Jeff Sharkey67f9d502017-08-05 13:49:13 -0600405 * {@link #PACKAGE_NAME_KEY_LEGACY_VISIBLE}. If the value was not set by authenticator
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700406 * {@link #VISIBILITY_USER_MANAGED_NOT_VISIBLE} is used.
407 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800408 public static final String PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE =
Dmitry Dementyevcbe1bd12017-04-25 17:02:47 -0700409 "android:accounts:key_legacy_not_visible";
Dmitry Dementyev52745472016-12-02 10:27:45 -0800410
411 /**
Fred Quintana33269202009-04-20 16:05:10 -0700412 * @hide
413 */
Mathew Inwoodad576cc2018-08-06 16:51:18 +0100414 @UnsupportedAppUsage
Fred Quintana60307342009-03-24 22:48:12 -0700415 public AccountManager(Context context, IAccountManager service) {
416 mContext = context;
417 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700418 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700419 }
420
Fred Quintana0eabf022009-04-27 15:08:17 -0700421 /**
422 * @hide used for testing only
423 */
Mathew Inwoodad576cc2018-08-06 16:51:18 +0100424 @UnsupportedAppUsage
Fred Quintana0eabf022009-04-27 15:08:17 -0700425 public AccountManager(Context context, IAccountManager service, Handler handler) {
426 mContext = context;
427 mService = service;
428 mMainHandler = handler;
429 }
430
Fred Quintana756b7352009-10-21 13:43:10 -0700431 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800432 * @hide for internal use only
433 */
434 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700435 if (result != null) {
436 if (result.containsKey(KEY_AUTHTOKEN)
437 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
438 final Bundle newResult = new Bundle(result);
439 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
440 return newResult;
441 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800442 }
443 return result;
444 }
445
446 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800447 * Gets an AccountManager instance associated with a Context.
448 * The {@link Context} will be used as long as the AccountManager is
449 * active, so make sure to use a {@link Context} whose lifetime is
450 * commensurate with any listeners registered to
451 * {@link #addOnAccountsUpdatedListener} or similar methods.
452 *
453 * <p>It is safe to call this method from the main thread.
454 *
455 * <p>No permission is required to call this method.
456 *
Fred Quintana756b7352009-10-21 13:43:10 -0700457 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800458 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700459 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700460 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700461 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700462 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
463 }
464
Fred Quintana756b7352009-10-21 13:43:10 -0700465 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800466 * Gets the saved password associated with the account. This is intended for authenticators and
467 * related code; applications should get an auth token instead.
Dan Egnor661f0132010-02-19 11:23:00 -0800468 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800469 * <p>
470 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800471 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800472 * <p>
473 * This method requires the caller to have a signature match with the authenticator that owns
474 * the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800475 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800476 * <p>
477 * <b>NOTE:</b> If targeting your app to work on API level
478 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before, AUTHENTICATE_ACCOUNTS
479 * permission is needed for those platforms. See docs for this function in API level
480 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700481 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700482 * @param account The account to query for a password. Must not be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800483 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700484 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700485 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700486 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700487 try {
488 return mService.getPassword(account);
489 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700490 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700491 }
492 }
493
Fred Quintana756b7352009-10-21 13:43:10 -0700494 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800495 * Gets the user data named by "key" associated with the account. This is intended for
496 * authenticators and related code to store arbitrary metadata along with accounts. The meaning
497 * of the keys and values is up to the authenticator for the account.
Dan Egnor661f0132010-02-19 11:23:00 -0800498 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800499 * <p>
500 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800501 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800502 * <p>
503 * This method requires the caller to have a signature match with the authenticator that owns
504 * the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800505 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800506 * <p>
507 * <b>NOTE:</b> If targeting your app to work on API level
508 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before, AUTHENTICATE_ACCOUNTS
509 * permission is needed for those platforms. See docs for this function in API level
510 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700511 *
Dan Egnor661f0132010-02-19 11:23:00 -0800512 * @param account The account to query for user data
513 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700514 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700516 if (account == null) throw new IllegalArgumentException("account is null");
517 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700518 try {
519 return mService.getUserData(account, key);
520 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700521 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700522 }
523 }
524
Fred Quintana756b7352009-10-21 13:43:10 -0700525 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800526 * Lists the currently registered authenticators.
527 *
528 * <p>It is safe to call this method from the main thread.
529 *
530 * <p>No permission is required to call this method.
531 *
532 * @return An array of {@link AuthenticatorDescription} for every
533 * authenticator known to the AccountManager service. Empty (never
534 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700535 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700536 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700537 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100538 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
539 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700540 throw e.rethrowFromSystemServer();
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100541 }
542 }
543
544 /**
545 * @hide
546 * Lists the currently registered authenticators for a given user id.
547 *
548 * <p>It is safe to call this method from the main thread.
549 *
550 * <p>The caller has to be in the same user or have the permission
551 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
552 *
553 * @return An array of {@link AuthenticatorDescription} for every
554 * authenticator known to the AccountManager service. Empty (never
555 * null) if no authenticators are known.
556 */
557 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
558 try {
559 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700560 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700561 throw e.rethrowFromSystemServer();
Fred Quintanaa698f422009-04-08 19:14:54 -0700562 }
563 }
564
Fred Quintana756b7352009-10-21 13:43:10 -0700565 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800566 * Lists all accounts visible to the caller regardless of type. Equivalent to
567 * getAccountsByType(null). These accounts may be visible because the user granted access to the
568 * account, or the AbstractAcccountAuthenticator managing the account did so or because the
569 * client shares a signature with the managing AbstractAccountAuthenticator.
Dan Egnor661f0132010-02-19 11:23:00 -0800570 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800571 * <p>
572 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800573 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800574 * @return An array of {@link Account}, one for each account. Empty (never null) if no accounts
575 * have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700576 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700577 @NonNull
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700578 public Account[] getAccounts() {
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000579 try {
580 return mService.getAccounts(null, mContext.getOpPackageName());
581 } catch (RemoteException e) {
582 throw e.rethrowFromSystemServer();
583 }
Fred Quintana60307342009-03-24 22:48:12 -0700584 }
585
Fred Quintana756b7352009-10-21 13:43:10 -0700586 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700587 * @hide
Dmitry Dementyev52745472016-12-02 10:27:45 -0800588 * Lists all accounts visible to caller regardless of type for a given user id. Equivalent to
589 * getAccountsByType(null).
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100590 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800591 * <p>
592 * It is safe to call this method from the main thread.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100593 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800594 * @return An array of {@link Account}, one for each account. Empty (never null) if no accounts
595 * have been added.
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100596 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700597 @NonNull
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100598 public Account[] getAccountsAsUser(int userId) {
599 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700600 return mService.getAccountsAsUser(null, userId, mContext.getOpPackageName());
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100601 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700602 throw e.rethrowFromSystemServer();
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100603 }
604 }
605
606 /**
607 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700608 * For use by internal activities. Returns the list of accounts that the calling package
609 * is authorized to use, particularly for shared accounts.
610 * @param packageName package name of the calling app.
611 * @param uid the uid of the calling app.
612 * @return the accounts that are available to this package and user.
613 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700614 @NonNull
Amith Yamasani27db4682013-03-30 17:07:47 -0700615 public Account[] getAccountsForPackage(String packageName, int uid) {
616 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700617 return mService.getAccountsForPackage(packageName, uid, mContext.getOpPackageName());
Amith Yamasani27db4682013-03-30 17:07:47 -0700618 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700619 throw re.rethrowFromSystemServer();
Amith Yamasani27db4682013-03-30 17:07:47 -0700620 }
621 }
622
623 /**
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700624 * Returns the accounts visible to the specified package in an environment where some apps are
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800625 * not authorized to view all accounts. This method can only be called by system apps and
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700626 * authenticators managing the type.
627 * Beginning API level {@link android.os.Build.VERSION_CODES#O} it also return accounts
Jeff Sharkey67f9d502017-08-05 13:49:13 -0600628 * which user can make visible to the application (see {@link #VISIBILITY_USER_MANAGED_VISIBLE}).
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800629 *
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700630 * @param type The type of accounts to return, null to retrieve all accounts
631 * @param packageName The package name of the app for which the accounts are to be returned
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800632 * @return An array of {@link Account}, one per matching account. Empty (never null) if no
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700633 * accounts of the specified type can be accessed by the package.
634 *
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700635 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700636 @NonNull
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700637 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
638 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700639 return mService.getAccountsByTypeForPackage(type, packageName,
640 mContext.getOpPackageName());
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700641 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700642 throw re.rethrowFromSystemServer();
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700643 }
644 }
645
646 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800647 * Lists all accounts of particular type visible to the caller. These accounts may be visible
648 * because the user granted access to the account, or the AbstractAcccountAuthenticator managing
649 * the account did so or because the client shares a signature with the managing
650 * AbstractAccountAuthenticator.
Dan Egnor661f0132010-02-19 11:23:00 -0800651 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800652 * <p>
653 * The account type is a string token corresponding to the authenticator and useful domain of
654 * the account. For example, there are types corresponding to Google and Facebook. The exact
655 * string token to use will be published somewhere associated with the authenticator in
656 * question.
Dan Egnor661f0132010-02-19 11:23:00 -0800657 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800658 * <p>
659 * It is safe to call this method from the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800660 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800661 * <p>
662 * Caller targeting API level {@link android.os.Build.VERSION_CODES#O} and above, will get list
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700663 * of accounts made visible to it by user
664 * (see {@link #newChooseAccountIntent(Account, List, String[], String,
665 * String, String[], Bundle)}) or AbstractAcccountAuthenticator
Jeff Sharkey67f9d502017-08-05 13:49:13 -0600666 * using {@link #setAccountVisibility}.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800667 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is not used.
668 *
669 * <p>
670 * Caller targeting API level below {@link android.os.Build.VERSION_CODES#O} that have not been
671 * granted the {@link android.Manifest.permission#GET_ACCOUNTS} permission, will only see those
672 * accounts managed by AbstractAccountAuthenticators whose signature matches the client.
673 *
674 * <p>
675 * <b>NOTE:</b> If targeting your app to work on API level
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800676 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before,
677 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is
Dmitry Dementyev52745472016-12-02 10:27:45 -0800678 * needed for those platforms, irrespective of uid or signature match. See docs for this
679 * function in API level {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Ian Pedowitz358e51f2016-03-15 17:08:27 +0000680 *
681 * @param type The type of accounts to return, null to retrieve all accounts
Dmitry Dementyev52745472016-12-02 10:27:45 -0800682 * @return An array of {@link Account}, one per matching account. Empty (never null) if no
683 * accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700684 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700685 @NonNull
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700686 public Account[] getAccountsByType(String type) {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700687 return getAccountsByTypeAsUser(type, mContext.getUser());
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800688 }
689
690 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700691 @NonNull
Mathew Inwoodad576cc2018-08-06 16:51:18 +0100692 @UnsupportedAppUsage
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800693 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700694 try {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700695 return mService.getAccountsAsUser(type, userHandle.getIdentifier(),
696 mContext.getOpPackageName());
Fred Quintana60307342009-03-24 22:48:12 -0700697 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700698 throw e.rethrowFromSystemServer();
Fred Quintana60307342009-03-24 22:48:12 -0700699 }
700 }
701
Fred Quintana756b7352009-10-21 13:43:10 -0700702 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700703 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
704 * for an account.
705 * <p>
706 * This is only meant to be used by system activities and is not in the SDK.
707 * @param account The account whose permissions are being modified
708 * @param authTokenType The type of token whose permissions are being modified
709 * @param uid The uid that identifies the app which is being granted or revoked permission.
710 * @param value true is permission is being granted, false for revoked
711 * @hide
712 */
713 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
714 try {
715 mService.updateAppPermission(account, authTokenType, uid, value);
716 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700717 throw e.rethrowFromSystemServer();
Fred Quintanad9640ec2012-05-23 12:37:00 -0700718 }
719 }
720
721 /**
722 * Get the user-friendly label associated with an authenticator's auth token.
723 * @param accountType the type of the authenticator. must not be null.
724 * @param authTokenType the token type. must not be null.
725 * @param callback callback to invoke when the result is available. may be null.
726 * @param handler the handler on which to invoke the callback, or null for the main thread
727 * @return a future containing the label string
728 * @hide
729 */
730 public AccountManagerFuture<String> getAuthTokenLabel(
731 final String accountType, final String authTokenType,
732 AccountManagerCallback<String> callback, Handler handler) {
733 if (accountType == null) throw new IllegalArgumentException("accountType is null");
734 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
735 return new Future2Task<String>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800736 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -0700737 public void doWork() throws RemoteException {
738 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
739 }
740
741 @Override
742 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
743 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
744 throw new AuthenticatorException("no result in response");
745 }
746 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
747 }
748 }.start();
749 }
750
751 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800752 * Finds out whether a particular account has all the specified features. Account features are
753 * authenticator-specific string tokens identifying boolean account properties. For example,
754 * features are used to tell whether Google accounts have a particular service (such as Google
755 * Calendar or Google Talk) enabled. The feature names and their meanings are published
756 * somewhere associated with the authenticator in question.
Dan Egnor661f0132010-02-19 11:23:00 -0800757 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800758 * <p>
759 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
760 * not be used on the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -0800761 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800762 * <p>
763 * If caller target API level is below {@link android.os.Build.VERSION_CODES#O}, it is
764 * required to hold the permission {@link android.Manifest.permission#GET_ACCOUNTS} or have a
765 * signature match with the AbstractAccountAuthenticator that manages the account.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800766 *
767 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800768 * @param features An array of the account features to check
Dmitry Dementyev52745472016-12-02 10:27:45 -0800769 * @param callback Callback to invoke when the request completes, null for no callback
770 * @param handler {@link Handler} identifying the callback thread, null for the main thread
771 * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the account
772 * exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800773 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800774 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800775 final String[] features,
776 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700777 if (account == null) throw new IllegalArgumentException("account is null");
778 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800779 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800780 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800781 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700782 mService.hasFeatures(mResponse, account, features, mContext.getOpPackageName());
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800783 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800784 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800785 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
786 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
787 throw new AuthenticatorException("no result in response");
788 }
789 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
790 }
791 }.start();
792 }
793
794 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800795 * Lists all accounts of a type which have certain features. The account type identifies the
796 * authenticator (see {@link #getAccountsByType}). Account features are authenticator-specific
797 * string tokens identifying boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700798 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800799 * <p>
800 * Unlike {@link #getAccountsByType}, this method calls the authenticator, which may contact the
801 * server or do other work to check account features, so the method returns an
802 * {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700803 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800804 * <p>
805 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
806 * not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700807 *
Dmitry Dementyev52745472016-12-02 10:27:45 -0800808 * <p>
809 * Caller targeting API level {@link android.os.Build.VERSION_CODES#O} and above, will get list
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700810 * of accounts made visible to it by user
811 * (see {@link #newChooseAccountIntent(Account, List, String[], String,
812 * String, String[], Bundle)}) or AbstractAcccountAuthenticator
Jeff Sharkey67f9d502017-08-05 13:49:13 -0600813 * using {@link #setAccountVisibility}.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800814 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is not used.
815 *
816 * <p>
817 * Caller targeting API level below {@link android.os.Build.VERSION_CODES#O} that have not been
818 * granted the {@link android.Manifest.permission#GET_ACCOUNTS} permission, will only see those
819 * accounts managed by AbstractAccountAuthenticators whose signature matches the client.
820 * <p>
821 * <b>NOTE:</b> If targeting your app to work on API level
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800822 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and before,
823 * {@link android.Manifest.permission#GET_ACCOUNTS} permission is
Dmitry Dementyev52745472016-12-02 10:27:45 -0800824 * needed for those platforms, irrespective of uid or signature match. See docs for this
825 * function in API level {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
826 *
Fred Quintana756b7352009-10-21 13:43:10 -0700827 *
Dan Egnor661f0132010-02-19 11:23:00 -0800828 * @param type The type of accounts to return, must not be null
Dmitry Dementyev52745472016-12-02 10:27:45 -0800829 * @param features An array of the account features to require, may be null or empty *
830 * @param callback Callback to invoke when the request completes, null for no callback
831 * @param handler {@link Handler} identifying the callback thread, null for the main thread
832 * @return An {@link AccountManagerFuture} which resolves to an array of {@link Account}, one
833 * per account of the specified type which matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800834 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700835 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
836 final String type, final String[] features,
837 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700838 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700839 return new Future2Task<Account[]>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -0800840 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700841 public void doWork() throws RemoteException {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700842 mService.getAccountsByFeatures(mResponse, type, features,
843 mContext.getOpPackageName());
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700844 }
Sandra Kwan0b84b452016-01-20 15:25:42 -0800845 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700846 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700847 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700848 throw new AuthenticatorException("no result in response");
849 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700850 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700851 Account[] descs = new Account[parcelables.length];
852 for (int i = 0; i < parcelables.length; i++) {
853 descs[i] = (Account) parcelables[i];
854 }
855 return descs;
856 }
857 }.start();
858 }
859
Fred Quintana756b7352009-10-21 13:43:10 -0700860 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700861 * Adds an account directly to the AccountManager. Normally used by sign-up
Dan Egnor661f0132010-02-19 11:23:00 -0800862 * wizards associated with authenticators, not directly by applications.
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700863 * <p>Calling this method does not update the last authenticated timestamp,
864 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
865 * {@link #notifyAccountAuthenticated(Account)} after getting success.
866 * However, if this method is called when it is triggered by addAccount() or
867 * addAccountAsUser() or similar functions, then there is no need to update
868 * timestamp manually as it is updated automatically by framework on
869 * successful completion of the mentioned functions.
Dan Egnor661f0132010-02-19 11:23:00 -0800870 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700871 * <p>This method requires the caller to have a signature match with the
872 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800873 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -0700874 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
875 * AUTHENTICATE_ACCOUNTS permission is needed for those platforms. See docs
876 * for this function in API level 22.
877 *
Dan Egnor661f0132010-02-19 11:23:00 -0800878 * @param account The {@link Account} to add
879 * @param password The password to associate with the account, null for none
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700880 * @param userdata String values to use for the account's userdata, null for
881 * none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700882 * @return True if the account was successfully added, false if the account
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700883 * already exists, the account is null, or another error occurs.
Dan Egnor661f0132010-02-19 11:23:00 -0800884 */
885 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700886 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800887 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700888 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800889 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -0700890 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -0800891 }
892 }
893
894 /**
Dmitry Dementyev85d8a342017-05-02 17:33:17 -0700895 * Adds an account directly to the AccountManager. Additionally it specifies Account visibility
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800896 * for given list of packages.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800897 * <p>
898 * Normally used by sign-up wizards associated with authenticators, not directly by
899 * applications.
900 * <p>
901 * Calling this method does not update the last authenticated timestamp, referred by
902 * {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700903 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800904 * <p>
905 * It is safe to call this method from the main thread.
906 * <p>
907 * This method requires the caller to have a signature match with the authenticator that owns
908 * the specified account.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700909 *
910 * @param account The {@link Account} to add
911 * @param password The password to associate with the account, null for none
Dmitry Dementyev52745472016-12-02 10:27:45 -0800912 * @param extras String values to use for the account's userdata, null for none
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800913 * @param visibility Map from packageName to visibility values which will be set before account
914 * is added. See {@link #getAccountVisibility} for possible values.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800915 *
916 * @return True if the account was successfully added, false if the account already exists, the
917 * account is null, or another error occurs.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800918 */
919 public boolean addAccountExplicitly(Account account, String password, Bundle extras,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800920 Map<String, Integer> visibility) {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800921 if (account == null)
922 throw new IllegalArgumentException("account is null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700923 try {
Dmitry Dementyev52745472016-12-02 10:27:45 -0800924 return mService.addAccountExplicitlyWithVisibility(account, password, extras,
925 visibility);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700926 } catch (RemoteException e) {
927 throw e.rethrowFromSystemServer();
928 }
929 }
930
931 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800932 * Returns package names and visibility which were explicitly set for given account.
Dmitry Dementyev2ae64092017-01-09 12:48:18 -0800933 * <p>
934 * This method requires the caller to have a signature match with the authenticator that owns
935 * the specified account.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700936 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700937 * @param account The account for which visibility data should be returned
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700938 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700939 * @return Map from package names to visibility for given account
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700940 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800941 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800942 try {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800943 if (account == null)
944 throw new IllegalArgumentException("account is null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800945 @SuppressWarnings("unchecked")
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800946 Map<String, Integer> result = (Map<String, Integer>) mService
947 .getPackagesAndVisibilityForAccount(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800948 return result;
949 } catch (RemoteException re) {
950 throw re.rethrowFromSystemServer();
951 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700952 }
953
954 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -0800955 * Gets all accounts of given type and their visibility for specific package. This method
956 * requires the caller to have a signature match with the authenticator that manages
957 * accountType. It is a helper method which combines calls to {@link #getAccountsByType} by
958 * authenticator and {@link #getAccountVisibility} for every returned account.
959 *
960 * <p>
961 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700962 * @param packageName Package name
963 * @param accountType {@link Account} type
Dmitry Dementyev52745472016-12-02 10:27:45 -0800964 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700965 * @return Map with visibility for all accounts of given type
966 * See {@link #getAccountVisibility} for possible values
Dmitry Dementyev52745472016-12-02 10:27:45 -0800967 */
968 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
969 String accountType) {
970 try {
971 @SuppressWarnings("unchecked")
972 Map<Account, Integer> result = (Map<Account, Integer>) mService
973 .getAccountsAndVisibilityForPackage(packageName, accountType);
974 return result;
975 } catch (RemoteException re) {
976 throw re.rethrowFromSystemServer();
977 }
978 }
979
980 /**
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700981 * Set visibility value of given account to certain package.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800982 * Package name must match installed application, or be equal to
983 * {@link #PACKAGE_NAME_KEY_LEGACY_VISIBLE} or {@link #PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE}.
Dmitry Dementyev52745472016-12-02 10:27:45 -0800984 * <p>
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800985 * Possible visibility values:
986 * <ul>
987 * <li>{@link #VISIBILITY_UNDEFINED}</li>
988 * <li>{@link #VISIBILITY_VISIBLE}</li>
989 * <li>{@link #VISIBILITY_USER_MANAGED_VISIBLE}</li>
990 * <li>{@link #VISIBILITY_NOT_VISIBLE}
991 * <li>{@link #VISIBILITY_USER_MANAGED_NOT_VISIBLE}</li>
992 * </ul>
Dmitry Dementyev52745472016-12-02 10:27:45 -0800993 * <p>
994 * This method requires the caller to have a signature match with the authenticator that owns
995 * the specified account.
996 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -0700997 * @param account {@link Account} to update visibility
998 * @param packageName Package name of the application to modify account visibility
999 * @param visibility New visibility value
Dmitry Dementyev52745472016-12-02 10:27:45 -08001000 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -07001001 * @return True, if visibility value was successfully updated.
Dmitry Dementyev52745472016-12-02 10:27:45 -08001002 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001003 public boolean setAccountVisibility(Account account, String packageName,
Dmitry Dementyev52745472016-12-02 10:27:45 -08001004 @AccountVisibility int visibility) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001005 if (account == null)
1006 throw new IllegalArgumentException("account is null");
Dmitry Dementyev52745472016-12-02 10:27:45 -08001007 try {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001008 return mService.setAccountVisibility(account, packageName, visibility);
Dmitry Dementyev52745472016-12-02 10:27:45 -08001009 } catch (RemoteException re) {
1010 throw re.rethrowFromSystemServer();
1011 }
1012 }
1013
1014 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001015 * Get visibility of certain account for given application. Possible returned values are:
Dmitry Dementyev52745472016-12-02 10:27:45 -08001016 * <ul>
1017 * <li>{@link #VISIBILITY_VISIBLE}</li>
1018 * <li>{@link #VISIBILITY_USER_MANAGED_VISIBLE}</li>
1019 * <li>{@link #VISIBILITY_NOT_VISIBLE}
1020 * <li>{@link #VISIBILITY_USER_MANAGED_NOT_VISIBLE}</li>
1021 * </ul>
1022 *
1023 * <p>
1024 * This method requires the caller to have a signature match with the authenticator that owns
1025 * the specified account.
1026 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -07001027 * @param account {@link Account} to get visibility
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001028 * @param packageName Package name of the application to get account visibility
Dmitry Dementyev52745472016-12-02 10:27:45 -08001029 *
Dmitry Dementyev0f8bba02017-03-20 10:57:01 -07001030 * @return int Visibility of given account.
Dmitry Dementyev52745472016-12-02 10:27:45 -08001031 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001032 public @AccountVisibility int getAccountVisibility(Account account, String packageName) {
1033 if (account == null)
1034 throw new IllegalArgumentException("account is null");
Dmitry Dementyev52745472016-12-02 10:27:45 -08001035 try {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001036 return mService.getAccountVisibility(account, packageName);
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001037 } catch (RemoteException re) {
1038 throw re.rethrowFromSystemServer();
1039 }
1040 }
1041
1042 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001043 * Notifies the system that the account has just been authenticated. This
1044 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001045 * should be called only when the user has entered correct credentials for
1046 * the account.
1047 * <p>
1048 * It is not safe to call this method from the main thread. As such, call it
1049 * from another thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001050 * <p>This method requires the caller to have a signature match with the
1051 * authenticator that owns the specified account.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001052 *
1053 * @param account The {@link Account} to be updated.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001054 * @return boolean {@code true} if the authentication of the account has been successfully
1055 * acknowledged. Otherwise {@code false}.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001056 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001057 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001058 if (account == null)
1059 throw new IllegalArgumentException("account is null");
1060 try {
1061 return mService.accountAuthenticated(account);
1062 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001063 throw e.rethrowFromSystemServer();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001064 }
1065 }
1066
1067 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001068 * Rename the specified {@link Account}. This is equivalent to removing
1069 * the existing account and adding a new renamed account with the old
1070 * account's user data.
1071 *
1072 * <p>It is safe to call this method from the main thread.
1073 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001074 * <p>This method requires the caller to have a signature match with the
1075 * authenticator that manages the specified account.
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001076 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001077 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1078 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1079 * is needed for those platforms. See docs for this function in API level 22.
1080 *
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001081 * @param account The {@link Account} to rename
1082 * @param newName String name to be associated with the account.
1083 * @param callback Callback to invoke when the request completes, null for
1084 * no callback
1085 * @param handler {@link Handler} identifying the callback thread, null for
1086 * the main thread
1087 * @return An {@link AccountManagerFuture} which resolves to the Account
1088 * after the name change. If successful the account's name will be the
1089 * specified new name.
1090 */
1091 public AccountManagerFuture<Account> renameAccount(
1092 final Account account,
Tor Norbye80b530a2015-04-23 16:36:09 -07001093 @Size(min = 1) final String newName,
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001094 AccountManagerCallback<Account> callback,
1095 Handler handler) {
1096 if (account == null) throw new IllegalArgumentException("account is null.");
1097 if (TextUtils.isEmpty(newName)) {
1098 throw new IllegalArgumentException("newName is empty or null.");
1099 }
1100 return new Future2Task<Account>(handler, callback) {
1101 @Override
1102 public void doWork() throws RemoteException {
1103 mService.renameAccount(mResponse, account, newName);
1104 }
1105 @Override
1106 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
1107 String name = bundle.getString(KEY_ACCOUNT_NAME);
1108 String type = bundle.getString(KEY_ACCOUNT_TYPE);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001109 String accessId = bundle.getString(KEY_ACCOUNT_ACCESS_ID);
1110 return new Account(name, type, accessId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001111 }
1112 }.start();
1113 }
1114
1115 /**
1116 * Gets the previous name associated with the account or {@code null}, if
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001117 * none. This is intended so that clients of
1118 * {@link OnAccountsUpdateListener} can determine if an
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001119 * authenticator has renamed an account.
1120 *
1121 * <p>It is safe to call this method from the main thread.
1122 *
1123 * @param account The account to query for a previous name.
1124 * @return The account's previous name, null if the account has never been
1125 * renamed.
1126 */
1127 public String getPreviousName(final Account account) {
1128 if (account == null) throw new IllegalArgumentException("account is null");
1129 try {
1130 return mService.getPreviousName(account);
1131 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001132 throw e.rethrowFromSystemServer();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001133 }
1134 }
1135
1136 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001137 * Removes an account from the AccountManager. Does nothing if the account
1138 * does not exist. Does not delete the account from the server.
1139 * The authenticator may have its own policies preventing account
1140 * deletion, in which case the account will not be deleted.
1141 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001142 * <p>This method requires the caller to have a signature match with the
1143 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001144 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001145 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1146 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1147 * this function in API level 22.
1148 *
Dan Egnor661f0132010-02-19 11:23:00 -08001149 * @param account The {@link Account} to remove
1150 * @param callback Callback to invoke when the request completes,
1151 * null for no callback
1152 * @param handler {@link Handler} identifying the callback thread,
1153 * null for the main thread
1154 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001155 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001156 * @deprecated use
1157 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
1158 * instead
Dan Egnor661f0132010-02-19 11:23:00 -08001159 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001160 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001161 public AccountManagerFuture<Boolean> removeAccount(final Account account,
1162 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001163 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001164 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001165 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001166 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001167 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -08001168 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001169 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001170 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1171 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1172 throw new AuthenticatorException("no result in response");
1173 }
1174 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1175 }
1176 }.start();
1177 }
1178
1179 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001180 * Removes an account from the AccountManager. Does nothing if the account
1181 * does not exist. Does not delete the account from the server.
1182 * The authenticator may have its own policies preventing account
1183 * deletion, in which case the account will not be deleted.
1184 *
1185 * <p>This method may be called from any thread, but the returned
1186 * {@link AccountManagerFuture} must not be used on the main thread.
1187 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001188 * <p>This method requires the caller to have a signature match with the
1189 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001190 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001191 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1192 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1193 * this function in API level 22.
1194 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001195 * @param account The {@link Account} to remove
1196 * @param activity The {@link Activity} context to use for launching a new
1197 * authenticator-defined sub-Activity to prompt the user to delete an
1198 * account; used only to call startActivity(); if null, the prompt
1199 * will not be launched directly, but the {@link Intent} may be
1200 * returned to the caller instead
1201 * @param callback Callback to invoke when the request completes,
1202 * null for no callback
1203 * @param handler {@link Handler} identifying the callback thread,
1204 * null for the main thread
1205 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1206 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
1207 * was removed or if active. If no activity was specified, the returned
1208 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
1209 * needed to launch the actual account removal process, if authenticator
1210 * needs the activity launch. If an error occurred,
1211 * {@link AccountManagerFuture#getResult()} throws:
1212 * <ul>
1213 * <li> {@link AuthenticatorException} if no authenticator was registered for
1214 * this account type or the authenticator failed to respond
1215 * <li> {@link OperationCanceledException} if the operation was canceled for
1216 * any reason, including the user canceling the creation process or
1217 * adding accounts (of this type) has been disabled by policy
1218 * </ul>
1219 */
1220 public AccountManagerFuture<Bundle> removeAccount(final Account account,
1221 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
1222 if (account == null) throw new IllegalArgumentException("account is null");
1223 return new AmsTask(activity, handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001224 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001225 public void doWork() throws RemoteException {
1226 mService.removeAccount(mResponse, account, activity != null);
1227 }
1228 }.start();
1229 }
1230
1231 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001232 * @see #removeAccount(Account, AccountManagerCallback, Handler)
1233 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001234 * @deprecated use
1235 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
1236 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001237 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001238 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001239 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
1240 AccountManagerCallback<Boolean> callback, Handler handler,
1241 final UserHandle userHandle) {
1242 if (account == null) throw new IllegalArgumentException("account is null");
1243 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1244 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001245 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001246 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001247 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001248 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001249 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001250 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1251 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1252 throw new AuthenticatorException("no result in response");
1253 }
1254 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1255 }
1256 }.start();
1257 }
1258
1259 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001260 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
1261 * @hide
1262 */
1263 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
1264 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
1265 final UserHandle userHandle) {
1266 if (account == null)
1267 throw new IllegalArgumentException("account is null");
1268 if (userHandle == null)
1269 throw new IllegalArgumentException("userHandle is null");
1270 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001271 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001272 public void doWork() throws RemoteException {
1273 mService.removeAccountAsUser(mResponse, account, activity != null,
1274 userHandle.getIdentifier());
1275 }
1276 }.start();
1277 }
1278
1279 /**
1280 * Removes an account directly. Normally used by authenticators, not
1281 * directly by applications. Does not delete the account from the server.
1282 * The authenticator may have its own policies preventing account deletion,
1283 * in which case the account will not be deleted.
1284 * <p>
1285 * It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001286 * <p>This method requires the caller to have a signature match with the
1287 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001288 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001289 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1290 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1291 * is needed for those platforms. See docs for this function in API level 22.
1292 *
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001293 * @param account The {@link Account} to delete.
1294 * @return True if the account was successfully deleted, false if the
1295 * account did not exist, the account is null, or another error
1296 * occurs.
1297 */
1298 public boolean removeAccountExplicitly(Account account) {
1299 if (account == null) throw new IllegalArgumentException("account is null");
1300 try {
1301 return mService.removeAccountExplicitly(account);
1302 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001303 throw e.rethrowFromSystemServer();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001304 }
1305 }
1306
1307 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001308 * Removes an auth token from the AccountManager's cache. Does nothing if
1309 * the auth token is not currently in the cache. Applications must call this
1310 * method when the auth token is found to have expired or otherwise become
1311 * invalid for authenticating requests. The AccountManager does not validate
1312 * or expire cached auth tokens otherwise.
1313 *
1314 * <p>It is safe to call this method from the main thread.
1315 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001316 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1317 * MANAGE_ACCOUNTS or USE_CREDENTIALS permission is needed for those
1318 * platforms. See docs for this function in API level 22.
1319 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001320 * @param accountType The account type of the auth token to invalidate, must not be null
1321 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -08001322 */
1323 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001324 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001325 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -07001326 if (authToken != null) {
1327 mService.invalidateAuthToken(accountType, authToken);
1328 }
Dan Egnor661f0132010-02-19 11:23:00 -08001329 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001330 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001331 }
1332 }
1333
1334 /**
1335 * Gets an auth token from the AccountManager's cache. If no auth
1336 * token is cached for this account, null will be returned -- a new
1337 * auth token will not be generated, and the server will not be contacted.
1338 * Intended for use by the authenticator, not directly by applications.
1339 *
1340 * <p>It is safe to call this method from the main thread.
1341 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001342 * <p>This method requires the caller to have a signature match with the
1343 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001344 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001345 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1346 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1347 * is needed for those platforms. See docs for this function in API level 22.
1348 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001349 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001350 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001351 * @return The cached auth token for this account and type, or null if
1352 * no auth token is cached or the account does not exist.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001353 * @see #getAuthToken
Dan Egnor661f0132010-02-19 11:23:00 -08001354 */
1355 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -07001356 if (account == null) throw new IllegalArgumentException("account is null");
1357 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001358 try {
1359 return mService.peekAuthToken(account, authTokenType);
1360 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001361 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001362 }
1363 }
1364
1365 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001366 * Sets or forgets a saved password. This modifies the local copy of the
1367 * password used to automatically authenticate the user; it does not change
1368 * the user's account password on the server. Intended for use by the
1369 * authenticator, not directly by applications.
1370 * <p>Calling this method does not update the last authenticated timestamp,
1371 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
1372 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dan Egnor661f0132010-02-19 11:23:00 -08001373 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001374 * <p>This method requires the caller to have a signature match with the
1375 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001376 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001377 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1378 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1379 * is needed for those platforms. See docs for this function in API level 22.
1380 *
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001381 * @param account The account whose password is to be set. Cannot be
1382 * {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001383 * @param password The password to set, null to clear the password
1384 */
1385 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -07001386 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001387 try {
1388 mService.setPassword(account, password);
1389 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001390 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001391 }
1392 }
1393
1394 /**
1395 * Forgets a saved password. This erases the local copy of the password;
1396 * it does not change the user's account password on the server.
1397 * Has the same effect as setPassword(account, null) but requires fewer
1398 * permissions, and may be used by applications or management interfaces
1399 * to "sign out" from an account.
1400 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001401 * <p>This method only successfully clear the account's password when the
1402 * caller has the same signature as the authenticator that owns the
1403 * specified account. Otherwise, this method will silently fail.
Dan Egnor661f0132010-02-19 11:23:00 -08001404 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001405 * <p>It is safe to call this method from the main thread.
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001406 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001407 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1408 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1409 * this function in API level 22.
1410 *
Dan Egnor661f0132010-02-19 11:23:00 -08001411 * @param account The account whose password to clear
1412 */
1413 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001414 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001415 try {
1416 mService.clearPassword(account);
1417 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001418 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001419 }
1420 }
1421
1422 /**
1423 * Sets one userdata key for an account. Intended by use for the
1424 * authenticator to stash state for itself, not directly by applications.
1425 * The meaning of the keys and values is up to the authenticator.
1426 *
1427 * <p>It is safe to call this method from the main thread.
1428 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001429 * <p>This method requires the caller to have a signature match with the
1430 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001431 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001432 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1433 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1434 * is needed for those platforms. See docs for this function in API level 22.
1435 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001436 * @param account Account whose user data is to be set. Must not be {@code null}.
1437 * @param key String user data key to set. Must not be null
1438 * @param value String value to set, {@code null} to clear this user data key
Dan Egnor661f0132010-02-19 11:23:00 -08001439 */
1440 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001441 if (account == null) throw new IllegalArgumentException("account is null");
1442 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001443 try {
1444 mService.setUserData(account, key, value);
1445 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001446 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001447 }
1448 }
1449
1450 /**
1451 * Adds an auth token to the AccountManager cache for an account.
1452 * If the account does not exist then this call has no effect.
1453 * Replaces any previous auth token for this account and auth token type.
1454 * Intended for use by the authenticator, not directly by applications.
1455 *
1456 * <p>It is safe to call this method from the main thread.
1457 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001458 * <p>This method requires the caller to have a signature match with the
1459 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001460 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001461 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1462 * AUTHENTICATE_ACCOUNTS permission and same UID as account's authenticator
1463 * is needed for those platforms. See docs for this function in API level 22.
1464 *
Dan Egnor661f0132010-02-19 11:23:00 -08001465 * @param account The account to set an auth token for
1466 * @param authTokenType The type of the auth token, see {#getAuthToken}
1467 * @param authToken The auth token to add to the cache
1468 */
1469 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001470 if (account == null) throw new IllegalArgumentException("account is null");
1471 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001472 try {
1473 mService.setAuthToken(account, authTokenType, authToken);
1474 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001475 throw e.rethrowFromSystemServer();
Dan Egnor661f0132010-02-19 11:23:00 -08001476 }
1477 }
1478
1479 /**
1480 * This convenience helper synchronously gets an auth token with
1481 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1482 *
1483 * <p>This method may block while a network request completes, and must
1484 * never be made from the main thread.
1485 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001486 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1487 * USE_CREDENTIALS permission is needed for those platforms. See docs for
1488 * this function in API level 22.
1489 *
Dan Egnor661f0132010-02-19 11:23:00 -08001490 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001491 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001492 * @param notifyAuthFailure If true, display a notification and return null
1493 * if authentication fails; if false, prompt and wait for the user to
1494 * re-enter correct credentials before returning
1495 * @return An auth token of the specified type for this account, or null
1496 * if authentication fails or none can be fetched.
1497 * @throws AuthenticatorException if the authenticator failed to respond
1498 * @throws OperationCanceledException if the request was canceled for any
1499 * reason, including the user canceling a credential request
1500 * @throws java.io.IOException if the authenticator experienced an I/O problem
1501 * creating a new auth token, usually because of network trouble
1502 */
1503 public String blockingGetAuthToken(Account account, String authTokenType,
1504 boolean notifyAuthFailure)
1505 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001506 if (account == null) throw new IllegalArgumentException("account is null");
1507 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001508 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1509 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001510 if (bundle == null) {
1511 // This should never happen, but it does, occasionally. If it does return null to
1512 // signify that we were not able to get the authtoken.
1513 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1514 // returned
1515 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1516 + account + ", authTokenType " + authTokenType);
1517 return null;
1518 }
Dan Egnor661f0132010-02-19 11:23:00 -08001519 return bundle.getString(KEY_AUTHTOKEN);
1520 }
1521
1522 /**
1523 * Gets an auth token of the specified type for a particular account,
1524 * prompting the user for credentials if necessary. This method is
1525 * intended for applications running in the foreground where it makes
1526 * sense to ask the user directly for a password.
1527 *
1528 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001529 * type, then it is returned. Otherwise, if a saved password is
1530 * available, it is sent to the server to generate a new auth token.
1531 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001532 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001533 * <p>Some authenticators have auth token <em>types</em>, whose value
1534 * is authenticator-dependent. Some services use different token types to
1535 * access different functionality -- for example, Google uses different auth
1536 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001537 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001538 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001539 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001540 * this function in API level 22.
1541 *
Dan Egnor661f0132010-02-19 11:23:00 -08001542 * <p>This method may be called from any thread, but the returned
1543 * {@link AccountManagerFuture} must not be used on the main thread.
1544 *
Dan Egnor661f0132010-02-19 11:23:00 -08001545 * @param account The account to fetch an auth token for
1546 * @param authTokenType The auth token type, an authenticator-dependent
1547 * string token, must not be null
1548 * @param options Authenticator-specific options for the request,
1549 * may be null or empty
1550 * @param activity The {@link Activity} context to use for launching a new
1551 * authenticator-defined sub-Activity to prompt the user for a password
1552 * if necessary; used only to call startActivity(); must not be null.
1553 * @param callback Callback to invoke when the request completes,
1554 * null for no callback
1555 * @param handler {@link Handler} identifying the callback thread,
1556 * null for the main thread
1557 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1558 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001559 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001560 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1561 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1562 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001563 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001564 *
1565 * (Other authenticator-specific values may be returned.) If an auth token
1566 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1567 * <ul>
1568 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1569 * <li> {@link OperationCanceledException} if the operation is canceled for
1570 * any reason, incluidng the user canceling a credential request
1571 * <li> {@link IOException} if the authenticator experienced an I/O problem
1572 * creating a new auth token, usually because of network trouble
1573 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001574 * If the account is no longer present on the device, the return value is
1575 * authenticator-dependent. The caller should verify the validity of the
1576 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001577 */
1578 public AccountManagerFuture<Bundle> getAuthToken(
1579 final Account account, final String authTokenType, final Bundle options,
1580 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001581 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001582 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001583 final Bundle optionsIn = new Bundle();
1584 if (options != null) {
1585 optionsIn.putAll(options);
1586 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001587 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001588 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001589 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001590 public void doWork() throws RemoteException {
1591 mService.getAuthToken(mResponse, account, authTokenType,
1592 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001593 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001594 }
1595 }.start();
1596 }
1597
1598 /**
1599 * Gets an auth token of the specified type for a particular account,
1600 * optionally raising a notification if the user must enter credentials.
1601 * This method is intended for background tasks and services where the
1602 * user should not be immediately interrupted with a password prompt.
1603 *
1604 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001605 * type, then it is returned. Otherwise, if a saved password is
1606 * available, it is sent to the server to generate a new auth token.
1607 * Otherwise, an {@link Intent} is returned which, when started, will
1608 * prompt the user for a password. If the notifyAuthFailure parameter is
1609 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001610 * alerting the user that they need to enter a password at some point.
1611 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001612 * <p>In that case, you may need to wait until the user responds, which
1613 * could take hours or days or forever. When the user does respond and
1614 * supply a new password, the account manager will broadcast the
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001615 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent and
1616 * notify {@link OnAccountsUpdateListener} which applications can
Dan Egnor8e4378b2010-08-02 18:22:09 -07001617 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001618 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001619 * <p>If notifyAuthFailure is not set, it is the application's
1620 * responsibility to launch the returned Intent at some point.
1621 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001622 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001623 * <p>Some authenticators have auth token <em>types</em>, whose value
1624 * is authenticator-dependent. Some services use different token types to
1625 * access different functionality -- for example, Google uses different auth
1626 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001627 *
1628 * <p>This method may be called from any thread, but the returned
1629 * {@link AccountManagerFuture} must not be used on the main thread.
1630 *
Dan Egnor661f0132010-02-19 11:23:00 -08001631 * @param account The account to fetch an auth token for
1632 * @param authTokenType The auth token type, an authenticator-dependent
1633 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001634 * @param notifyAuthFailure True to add a notification to prompt the
1635 * user for a password if necessary, false to leave that to the caller
1636 * @param callback Callback to invoke when the request completes,
1637 * null for no callback
1638 * @param handler {@link Handler} identifying the callback thread,
1639 * null for the main thread
1640 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1641 * at least the following fields on success:
1642 * <ul>
1643 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1644 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1645 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1646 * </ul>
1647 *
1648 * (Other authenticator-specific values may be returned.) If the user
1649 * must enter credentials, the returned Bundle contains only
1650 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1651 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001652 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001653 * <ul>
1654 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1655 * <li> {@link OperationCanceledException} if the operation is canceled for
1656 * any reason, incluidng the user canceling a credential request
1657 * <li> {@link IOException} if the authenticator experienced an I/O problem
1658 * creating a new auth token, usually because of network trouble
1659 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001660 * If the account is no longer present on the device, the return value is
1661 * authenticator-dependent. The caller should verify the validity of the
1662 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001663 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1664 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001665 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001666 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001667 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001668 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001669 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001670 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001671 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001672 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001673 }
1674
1675 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001676 * Gets an auth token of the specified type for a particular account,
1677 * optionally raising a notification if the user must enter credentials.
1678 * This method is intended for background tasks and services where the
1679 * user should not be immediately interrupted with a password prompt.
1680 *
1681 * <p>If a previously generated auth token is cached for this account and
1682 * type, then it is returned. Otherwise, if a saved password is
1683 * available, it is sent to the server to generate a new auth token.
1684 * Otherwise, an {@link Intent} is returned which, when started, will
1685 * prompt the user for a password. If the notifyAuthFailure parameter is
1686 * set, a status bar notification is also created with the same Intent,
1687 * alerting the user that they need to enter a password at some point.
1688 *
1689 * <p>In that case, you may need to wait until the user responds, which
1690 * could take hours or days or forever. When the user does respond and
1691 * supply a new password, the account manager will broadcast the
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001692 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent and
1693 * notify {@link OnAccountsUpdateListener} which applications can
Fred Quintanaad93a322011-09-08 13:21:01 -07001694 * use to try again.
1695 *
1696 * <p>If notifyAuthFailure is not set, it is the application's
1697 * responsibility to launch the returned Intent at some point.
1698 * Either way, the result from this call will not wait for user action.
1699 *
1700 * <p>Some authenticators have auth token <em>types</em>, whose value
1701 * is authenticator-dependent. Some services use different token types to
1702 * access different functionality -- for example, Google uses different auth
1703 * tokens to access Gmail and Google Calendar for the same account.
1704 *
1705 * <p>This method may be called from any thread, but the returned
1706 * {@link AccountManagerFuture} must not be used on the main thread.
1707 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001708 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
Sandra Kwan0b84b452016-01-20 15:25:42 -08001709 * USE_CREDENTIALS permission is needed for those platforms. See docs for
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001710 * this function in API level 22.
1711 *
Fred Quintanaad93a322011-09-08 13:21:01 -07001712 * @param account The account to fetch an auth token for
1713 * @param authTokenType The auth token type, an authenticator-dependent
1714 * string token, must not be null
1715 * @param options Authenticator-specific options for the request,
1716 * may be null or empty
1717 * @param notifyAuthFailure True to add a notification to prompt the
1718 * user for a password if necessary, false to leave that to the caller
1719 * @param callback Callback to invoke when the request completes,
1720 * null for no callback
1721 * @param handler {@link Handler} identifying the callback thread,
1722 * null for the main thread
1723 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1724 * at least the following fields on success:
1725 * <ul>
1726 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1727 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1728 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1729 * </ul>
1730 *
1731 * (Other authenticator-specific values may be returned.) If the user
1732 * must enter credentials, the returned Bundle contains only
1733 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1734 *
1735 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1736 * <ul>
1737 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1738 * <li> {@link OperationCanceledException} if the operation is canceled for
1739 * any reason, incluidng the user canceling a credential request
1740 * <li> {@link IOException} if the authenticator experienced an I/O problem
1741 * creating a new auth token, usually because of network trouble
1742 * </ul>
1743 * If the account is no longer present on the device, the return value is
1744 * authenticator-dependent. The caller should verify the validity of the
1745 * account before requesting an auth token.
1746 */
1747 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001748 final Account account, final String authTokenType, final Bundle options,
1749 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001750 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001751
Fred Quintanaad93a322011-09-08 13:21:01 -07001752 if (account == null) throw new IllegalArgumentException("account is null");
1753 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001754 final Bundle optionsIn = new Bundle();
1755 if (options != null) {
1756 optionsIn.putAll(options);
1757 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001758 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001759 return new AmsTask(null, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001760 @Override
Fred Quintanaad93a322011-09-08 13:21:01 -07001761 public void doWork() throws RemoteException {
1762 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001763 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001764 }
1765 }.start();
1766 }
1767
1768 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001769 * Asks the user to add an account of a specified type. The authenticator
1770 * for this account type processes this request with the appropriate user
1771 * interface. If the user does elect to create a new account, the account
1772 * name is returned.
1773 *
1774 * <p>This method may be called from any thread, but the returned
1775 * {@link AccountManagerFuture} must not be used on the main thread.
Sandra Kwan0b84b452016-01-20 15:25:42 -08001776 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001777 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1778 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
1779 * this function in API level 22.
Dan Egnor661f0132010-02-19 11:23:00 -08001780 *
Dan Egnor661f0132010-02-19 11:23:00 -08001781 * @param accountType The type of account to add; must not be null
1782 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1783 * this account will need to be able to generate, null for none
1784 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1785 * account must have, null for none
1786 * @param addAccountOptions Authenticator-specific options for the request,
1787 * may be null or empty
1788 * @param activity The {@link Activity} context to use for launching a new
1789 * authenticator-defined sub-Activity to prompt the user to create an
1790 * account; used only to call startActivity(); if null, the prompt
1791 * will not be launched directly, but the necessary {@link Intent}
1792 * will be returned to the caller instead
1793 * @param callback Callback to invoke when the request completes,
1794 * null for no callback
1795 * @param handler {@link Handler} identifying the callback thread,
1796 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001797 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001798 * these fields if activity was specified and an account was created:
1799 * <ul>
1800 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1801 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1802 * </ul>
1803 *
1804 * If no activity was specified, the returned Bundle contains only
1805 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001806 * actual account creation process. If an error occurred,
1807 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001808 * <ul>
1809 * <li> {@link AuthenticatorException} if no authenticator was registered for
1810 * this account type or the authenticator failed to respond
1811 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001812 * any reason, including the user canceling the creation process or adding accounts
1813 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001814 * <li> {@link IOException} if the authenticator experienced an I/O problem
1815 * creating a new account, usually because of network trouble
1816 * </ul>
1817 */
1818 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1819 final String authTokenType, final String[] requiredFeatures,
1820 final Bundle addAccountOptions,
1821 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001822 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001823 final Bundle optionsIn = new Bundle();
1824 if (addAccountOptions != null) {
1825 optionsIn.putAll(addAccountOptions);
1826 }
1827 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001828
Dan Egnor661f0132010-02-19 11:23:00 -08001829 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001830 @Override
Dan Egnor661f0132010-02-19 11:23:00 -08001831 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001832 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001833 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001834 }
1835 }.start();
1836 }
1837
1838 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001839 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1840 * @hide
1841 */
1842 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1843 final String authTokenType, final String[] requiredFeatures,
1844 final Bundle addAccountOptions, final Activity activity,
1845 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1846 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1847 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1848 final Bundle optionsIn = new Bundle();
1849 if (addAccountOptions != null) {
1850 optionsIn.putAll(addAccountOptions);
1851 }
1852 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1853
1854 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08001855 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001856 public void doWork() throws RemoteException {
1857 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1858 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1859 }
1860 }.start();
1861 }
1862
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001863
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001864 /**
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001865 * Adds shared accounts from a parent user to a secondary user. Adding the shared account
Amith Yamasani67df64b2012-12-14 12:09:36 -08001866 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1867 * are attempted to be copied to the target user from the primary via calls to the
1868 * authenticator.
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001869 * @param parentUser parent user
1870 * @param user target user
Amith Yamasani67df64b2012-12-14 12:09:36 -08001871 * @hide
1872 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001873 public void addSharedAccountsFromParentUser(UserHandle parentUser, UserHandle user) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001874 try {
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07001875 mService.addSharedAccountsFromParentUser(parentUser.getIdentifier(),
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08001876 user.getIdentifier(), mContext.getOpPackageName());
Amith Yamasani67df64b2012-12-14 12:09:36 -08001877 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001878 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001879 }
1880 }
1881
1882 /**
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001883 * Copies an account from one user to another user.
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001884 * @param account the account to copy
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001885 * @param fromUser the user to copy the account from
1886 * @param toUser the target user
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001887 * @param callback Callback to invoke when the request completes,
1888 * null for no callback
1889 * @param handler {@link Handler} identifying the callback thread,
1890 * null for the main thread
1891 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1892 * succeeded.
1893 * @hide
1894 */
1895 public AccountManagerFuture<Boolean> copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001896 final Account account, final UserHandle fromUser, final UserHandle toUser,
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001897 AccountManagerCallback<Boolean> callback, Handler handler) {
1898 if (account == null) throw new IllegalArgumentException("account is null");
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001899 if (toUser == null || fromUser == null) {
1900 throw new IllegalArgumentException("fromUser and toUser cannot be null");
1901 }
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001902
1903 return new Future2Task<Boolean>(handler, callback) {
1904 @Override
1905 public void doWork() throws RemoteException {
1906 mService.copyAccountToUser(
Xiaohui Chen75f68ce2015-08-14 09:28:07 -07001907 mResponse, account, fromUser.getIdentifier(), toUser.getIdentifier());
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001908 }
1909 @Override
1910 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1911 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1912 throw new AuthenticatorException("no result in response");
1913 }
1914 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1915 }
1916 }.start();
1917 }
1918
1919 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001920 * @hide
1921 * Removes the shared account.
1922 * @param account the account to remove
1923 * @param user the user to remove the account from
1924 * @return
1925 */
1926 public boolean removeSharedAccount(final Account account, UserHandle user) {
1927 try {
1928 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1929 return val;
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 /**
1936 * @hide
1937 * @param user
1938 * @return
1939 */
1940 public Account[] getSharedAccounts(UserHandle user) {
1941 try {
1942 return mService.getSharedAccountsAsUser(user.getIdentifier());
1943 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001944 throw re.rethrowFromSystemServer();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001945 }
1946 }
1947
1948 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001949 * Confirms that the user knows the password for an account to make extra
1950 * sure they are the owner of the account. The user-entered password can
1951 * be supplied directly, otherwise the authenticator for this account type
1952 * prompts the user with the appropriate interface. This method is
1953 * intended for applications which want extra assurance; for example, the
1954 * phone lock screen uses this to let the user unlock the phone with an
1955 * account password if they forget the lock pattern.
1956 *
1957 * <p>If the user-entered password matches a saved password for this
1958 * account, the request is considered valid; otherwise the authenticator
1959 * verifies the password (usually by contacting the server).
1960 *
1961 * <p>This method may be called from any thread, but the returned
1962 * {@link AccountManagerFuture} must not be used on the main thread.
1963 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07001964 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
1965 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
1966 * for this function in API level 22.
1967 *
Dan Egnor661f0132010-02-19 11:23:00 -08001968 * @param account The account to confirm password knowledge for
1969 * @param options Authenticator-specific options for the request;
1970 * if the {@link #KEY_PASSWORD} string field is present, the
1971 * authenticator may use it directly rather than prompting the user;
1972 * may be null or empty
1973 * @param activity The {@link Activity} context to use for launching a new
1974 * authenticator-defined sub-Activity to prompt the user to enter a
1975 * password; used only to call startActivity(); if null, the prompt
1976 * will not be launched directly, but the necessary {@link Intent}
1977 * will be returned to the caller instead
1978 * @param callback Callback to invoke when the request completes,
1979 * null for no callback
1980 * @param handler {@link Handler} identifying the callback thread,
1981 * null for the main thread
1982 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1983 * with these fields if activity or password was supplied and
1984 * the account was successfully verified:
1985 * <ul>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001986 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001987 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1988 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1989 * </ul>
1990 *
1991 * If no activity or password was specified, the returned Bundle contains
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001992 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1993 * password prompt.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001994 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001995 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001996 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001997 * credential was validated/created.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001998 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001999 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002000 * <ul>
2001 * <li> {@link AuthenticatorException} if the authenticator failed to respond
2002 * <li> {@link OperationCanceledException} if the operation was canceled for
2003 * any reason, including the user canceling the password prompt
2004 * <li> {@link IOException} if the authenticator experienced an I/O problem
2005 * verifying the password, usually because of network trouble
2006 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002007 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002008 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
2009 final Bundle options,
2010 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002011 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002012 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002013 return confirmCredentialsAsUser(account, options, activity, callback, handler,
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002014 mContext.getUser());
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002015 }
2016
2017 /**
2018 * @hide
2019 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
2020 * but for the specified user.
2021 */
Mathew Inwoodad576cc2018-08-06 16:51:18 +01002022 @UnsupportedAppUsage
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002023 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
2024 final Bundle options,
2025 final Activity activity,
2026 final AccountManagerCallback<Bundle> callback,
2027 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07002028 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002029 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07002030 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002031 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002032 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002033 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
2034 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07002035 }
Fred Quintana33269202009-04-20 16:05:10 -07002036 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002037 }
2038
Fred Quintana756b7352009-10-21 13:43:10 -07002039 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002040 * Asks the user to enter a new password for an account, updating the
2041 * saved credentials for the account. Normally this happens automatically
2042 * when the server rejects credentials during an auth token fetch, but this
2043 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07002044 *
Dan Egnor661f0132010-02-19 11:23:00 -08002045 * <p>This method may be called from any thread, but the returned
2046 * {@link AccountManagerFuture} must not be used on the main thread.
2047 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002048 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
2049 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs for
2050 * this function in API level 22.
2051 *
Dan Egnor661f0132010-02-19 11:23:00 -08002052 * @param account The account to update credentials for
2053 * @param authTokenType The credentials entered must allow an auth token
2054 * of this type to be created (but no actual auth token is returned);
2055 * may be null
2056 * @param options Authenticator-specific options for the request;
2057 * may be null or empty
2058 * @param activity The {@link Activity} context to use for launching a new
2059 * authenticator-defined sub-Activity to prompt the user to enter a
2060 * password; used only to call startActivity(); if null, the prompt
2061 * will not be launched directly, but the necessary {@link Intent}
2062 * will be returned to the caller instead
2063 * @param callback Callback to invoke when the request completes,
2064 * null for no callback
2065 * @param handler {@link Handler} identifying the callback thread,
2066 * null for the main thread
2067 * @return An {@link AccountManagerFuture} which resolves to a Bundle
2068 * with these fields if an activity was supplied and the account
2069 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07002070 * <ul>
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002071 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
Dan Egnor661f0132010-02-19 11:23:00 -08002072 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07002073 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002074 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002075 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08002076 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002077 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07002078 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002079 * <ul>
2080 * <li> {@link AuthenticatorException} if the authenticator failed to respond
2081 * <li> {@link OperationCanceledException} if the operation was canceled for
2082 * any reason, including the user canceling the password prompt
2083 * <li> {@link IOException} if the authenticator experienced an I/O problem
2084 * verifying the password, usually because of network trouble
2085 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002086 */
2087 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
2088 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07002089 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002090 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002091 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07002092 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07002093 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002094 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002095 public void doWork() throws RemoteException {
2096 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07002097 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07002098 }
Fred Quintana33269202009-04-20 16:05:10 -07002099 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002100 }
2101
Fred Quintana756b7352009-10-21 13:43:10 -07002102 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002103 * Offers the user an opportunity to change an authenticator's settings.
2104 * These properties are for the authenticator in general, not a particular
2105 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07002106 *
Dan Egnor661f0132010-02-19 11:23:00 -08002107 * <p>This method may be called from any thread, but the returned
2108 * {@link AccountManagerFuture} must not be used on the main thread.
2109 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002110 * <p>This method requires the caller to have the same signature as the
2111 * authenticator associated with the specified account type.
Dan Egnor661f0132010-02-19 11:23:00 -08002112 *
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002113 * <p><b>NOTE:</b> If targeting your app to work on API level 22 and before,
2114 * MANAGE_ACCOUNTS permission is needed for those platforms. See docs
2115 * for this function in API level 22.
2116 *
Dan Egnor661f0132010-02-19 11:23:00 -08002117 * @param accountType The account type associated with the authenticator
2118 * to adjust
2119 * @param activity The {@link Activity} context to use for launching a new
2120 * authenticator-defined sub-Activity to adjust authenticator settings;
2121 * used only to call startActivity(); if null, the settings dialog will
2122 * not be launched directly, but the necessary {@link Intent} will be
2123 * returned to the caller instead
2124 * @param callback Callback to invoke when the request completes,
2125 * null for no callback
2126 * @param handler {@link Handler} identifying the callback thread,
2127 * null for the main thread
2128 * @return An {@link AccountManagerFuture} which resolves to a Bundle
2129 * which is empty if properties were edited successfully, or
2130 * if no activity was specified, contains only {@link #KEY_INTENT}
2131 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07002132 * If an error occurred, {@link AccountManagerFuture#getResult()}
2133 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07002134 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002135 * <li> {@link AuthenticatorException} if no authenticator was registered for
2136 * this account type or the authenticator failed to respond
2137 * <li> {@link OperationCanceledException} if the operation was canceled for
2138 * any reason, including the user canceling the settings dialog
2139 * <li> {@link IOException} if the authenticator experienced an I/O problem
2140 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07002141 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002142 */
2143 public AccountManagerFuture<Bundle> editProperties(final String accountType,
2144 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07002145 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07002146 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07002147 return new AmsTask(activity, handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002148 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002149 public void doWork() throws RemoteException {
2150 mService.editProperties(mResponse, accountType, activity != null);
2151 }
Fred Quintana33269202009-04-20 16:05:10 -07002152 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07002153 }
2154
Amith Yamasani12747872015-12-07 14:19:49 -08002155 /**
2156 * @hide
2157 * Checks if the given account exists on any of the users on the device.
2158 * Only the system process can call this method.
2159 *
2160 * @param account The account to check for existence.
2161 * @return whether any user has this account
2162 */
2163 public boolean someUserHasAccount(@NonNull final Account account) {
2164 try {
2165 return mService.someUserHasAccount(account);
2166 } catch (RemoteException re) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002167 throw re.rethrowFromSystemServer();
Amith Yamasani12747872015-12-07 14:19:49 -08002168 }
2169 }
2170
Fred Quintanaa698f422009-04-08 19:14:54 -07002171 private void ensureNotOnMainThread() {
2172 final Looper looper = Looper.myLooper();
2173 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08002174 final IllegalStateException exception = new IllegalStateException(
2175 "calling this from your main thread can lead to deadlock");
2176 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
2177 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08002178 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
2179 throw exception;
2180 }
Fred Quintana60307342009-03-24 22:48:12 -07002181 }
2182 }
2183
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002184 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
2185 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07002186 handler = handler == null ? mMainHandler : handler;
2187 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002188 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002189 public void run() {
2190 callback.run(future);
2191 }
2192 });
2193 }
Fred Quintana60307342009-03-24 22:48:12 -07002194
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002195 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002196 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002197 final Account[] accountsCopy = new Account[accounts.length];
2198 // send a copy to make sure that one doesn't
2199 // change what another sees
2200 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
2201 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002202 handler.post(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002203 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002204 public void run() {
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002205 synchronized (mAccountsUpdatedListeners) {
2206 try {
2207 if (mAccountsUpdatedListeners.containsKey(listener)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002208 Set<String> types = mAccountsUpdatedListenersTypes.get(listener);
2209 if (types != null) {
2210 // filter by account type;
2211 ArrayList<Account> filtered = new ArrayList<>();
2212 for (Account account : accountsCopy) {
2213 if (types.contains(account.type)) {
2214 filtered.add(account);
2215 }
2216 }
2217 listener.onAccountsUpdated(
2218 filtered.toArray(new Account[filtered.size()]));
2219 } else {
2220 listener.onAccountsUpdated(accountsCopy);
2221 }
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002222 }
2223 } catch (SQLException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002224 // Better luck next time. If the problem was disk-full,
Hiroaki Kuriyama8d3e1592015-10-09 16:30:03 +02002225 // the STORAGE_OK intent will re-trigger the update.
2226 Log.e(TAG, "Can't update accounts", e);
2227 }
Costin Manolacheb6437242009-09-10 16:14:12 -07002228 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002229 }
2230 });
2231 }
2232
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002233 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Mathew Inwood55418ea2018-12-20 15:30:45 +00002234 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Fred Quintanaa698f422009-04-08 19:14:54 -07002235 final IAccountManagerResponse mResponse;
Mathew Inwood55418ea2018-12-20 15:30:45 +00002236 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Fred Quintanaa698f422009-04-08 19:14:54 -07002237 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002238 final AccountManagerCallback<Bundle> mCallback;
Mathew Inwood55418ea2018-12-20 15:30:45 +00002239 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Fred Quintanaa698f422009-04-08 19:14:54 -07002240 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002241 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002242 super(new Callable<Bundle>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002243 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002244 public Bundle call() throws Exception {
2245 throw new IllegalStateException("this should never be called");
2246 }
2247 });
2248
2249 mHandler = handler;
2250 mCallback = callback;
2251 mActivity = activity;
2252 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07002253 }
2254
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002255 public final AccountManagerFuture<Bundle> start() {
2256 try {
2257 doWork();
2258 } catch (RemoteException e) {
2259 setException(e);
2260 }
Fred Quintana33269202009-04-20 16:05:10 -07002261 return this;
Fred Quintana60307342009-03-24 22:48:12 -07002262 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002263
Sandra Kwan0b84b452016-01-20 15:25:42 -08002264 @Override
Fred Quintana96580e02010-03-04 13:42:42 -08002265 protected void set(Bundle bundle) {
2266 // TODO: somehow a null is being set as the result of the Future. Log this
2267 // case to help debug where this is occurring. When this bug is fixed this
2268 // condition statement should be removed.
2269 if (bundle == null) {
2270 Log.e(TAG, "the bundle must not be null", new Exception());
2271 }
2272 super.set(bundle);
2273 }
2274
Fred Quintanaa698f422009-04-08 19:14:54 -07002275 public abstract void doWork() throws RemoteException;
2276
2277 private Bundle internalGetResult(Long timeout, TimeUnit unit)
2278 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08002279 if (!isDone()) {
2280 ensureNotOnMainThread();
2281 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002282 try {
2283 if (timeout == null) {
2284 return get();
2285 } else {
2286 return get(timeout, unit);
2287 }
2288 } catch (CancellationException e) {
2289 throw new OperationCanceledException();
2290 } catch (TimeoutException e) {
2291 // fall through and cancel
2292 } catch (InterruptedException e) {
2293 // fall through and cancel
2294 } catch (ExecutionException e) {
2295 final Throwable cause = e.getCause();
2296 if (cause instanceof IOException) {
2297 throw (IOException) cause;
2298 } else if (cause instanceof UnsupportedOperationException) {
2299 throw new AuthenticatorException(cause);
2300 } else if (cause instanceof AuthenticatorException) {
2301 throw (AuthenticatorException) cause;
2302 } else if (cause instanceof RuntimeException) {
2303 throw (RuntimeException) cause;
2304 } else if (cause instanceof Error) {
2305 throw (Error) cause;
2306 } else {
2307 throw new IllegalStateException(cause);
2308 }
2309 } finally {
2310 cancel(true /* interrupt if running */);
2311 }
2312 throw new OperationCanceledException();
2313 }
2314
Sandra Kwan0b84b452016-01-20 15:25:42 -08002315 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002316 public Bundle getResult()
2317 throws OperationCanceledException, IOException, AuthenticatorException {
2318 return internalGetResult(null, null);
2319 }
2320
Sandra Kwan0b84b452016-01-20 15:25:42 -08002321 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002322 public Bundle getResult(long timeout, TimeUnit unit)
2323 throws OperationCanceledException, IOException, AuthenticatorException {
2324 return internalGetResult(timeout, unit);
2325 }
2326
Sandra Kwan0b84b452016-01-20 15:25:42 -08002327 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002328 protected void done() {
2329 if (mCallback != null) {
2330 postToHandler(mHandler, mCallback, this);
2331 }
2332 }
2333
2334 /** Handles the responses from the AccountManager */
2335 private class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002336 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002337 public void onResult(Bundle bundle) {
tiansimingf58793c2017-09-03 16:48:34 +08002338 if (bundle == null) {
2339 onError(ERROR_CODE_INVALID_RESPONSE, "null bundle returned");
2340 return;
2341 }
Brian Carlstrom46703b02011-04-06 15:41:29 -07002342 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07002343 if (intent != null && mActivity != null) {
2344 // since the user provided an Activity we will silently start intents
2345 // that we see
2346 mActivity.startActivity(intent);
2347 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002348 } else if (bundle.getBoolean("retry")) {
2349 try {
2350 doWork();
2351 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002352 throw e.rethrowFromSystemServer();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002353 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002354 } else {
2355 set(bundle);
2356 }
2357 }
2358
Sandra Kwan0b84b452016-01-20 15:25:42 -08002359 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002360 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002361 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2362 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2363 // the authenticator indicated that this request was canceled or we were
2364 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07002365 cancel(true /* mayInterruptIfRunning */);
2366 return;
2367 }
2368 setException(convertErrorToException(code, message));
2369 }
2370 }
2371
Fred Quintana60307342009-03-24 22:48:12 -07002372 }
2373
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002374 private abstract class BaseFutureTask<T> extends FutureTask<T> {
2375 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002376 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002377
2378 public BaseFutureTask(Handler handler) {
2379 super(new Callable<T>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002380 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002381 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07002382 throw new IllegalStateException("this should never be called");
2383 }
2384 });
Fred Quintanaa698f422009-04-08 19:14:54 -07002385 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002386 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07002387 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002388
2389 public abstract void doWork() throws RemoteException;
2390
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002391 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07002392
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002393 protected void postRunnableToHandler(Runnable runnable) {
2394 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
2395 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07002396 }
2397
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002398 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002399 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002400 doWork();
2401 } catch (RemoteException e) {
2402 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07002403 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002404 }
2405
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002406 protected class Response extends IAccountManagerResponse.Stub {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002407 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002408 public void onResult(Bundle bundle) {
2409 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002410 T result = bundleToResult(bundle);
2411 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002412 return;
2413 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002414 set(result);
2415 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002416 } catch (ClassCastException e) {
2417 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002418 } catch (AuthenticatorException e) {
2419 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07002420 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002421 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07002422 }
2423
Sandra Kwan0b84b452016-01-20 15:25:42 -08002424 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002425 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002426 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
2427 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
2428 // the authenticator indicated that this request was canceled or we were
2429 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07002430 cancel(true /* mayInterruptIfRunning */);
2431 return;
2432 }
2433 setException(convertErrorToException(code, message));
2434 }
2435 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002436 }
2437
2438 private abstract class Future2Task<T>
2439 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
2440 final AccountManagerCallback<T> mCallback;
2441 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
2442 super(handler);
2443 mCallback = callback;
2444 }
2445
Sandra Kwan0b84b452016-01-20 15:25:42 -08002446 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002447 protected void done() {
2448 if (mCallback != null) {
2449 postRunnableToHandler(new Runnable() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002450 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002451 public void run() {
2452 mCallback.run(Future2Task.this);
2453 }
2454 });
2455 }
2456 }
2457
2458 public Future2Task<T> start() {
2459 startTask();
2460 return this;
2461 }
2462
2463 private T internalGetResult(Long timeout, TimeUnit unit)
2464 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08002465 if (!isDone()) {
2466 ensureNotOnMainThread();
2467 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002468 try {
2469 if (timeout == null) {
2470 return get();
2471 } else {
2472 return get(timeout, unit);
2473 }
2474 } catch (InterruptedException e) {
2475 // fall through and cancel
2476 } catch (TimeoutException e) {
2477 // fall through and cancel
2478 } catch (CancellationException e) {
2479 // fall through and cancel
2480 } catch (ExecutionException e) {
2481 final Throwable cause = e.getCause();
2482 if (cause instanceof IOException) {
2483 throw (IOException) cause;
2484 } else if (cause instanceof UnsupportedOperationException) {
2485 throw new AuthenticatorException(cause);
2486 } else if (cause instanceof AuthenticatorException) {
2487 throw (AuthenticatorException) cause;
2488 } else if (cause instanceof RuntimeException) {
2489 throw (RuntimeException) cause;
2490 } else if (cause instanceof Error) {
2491 throw (Error) cause;
2492 } else {
2493 throw new IllegalStateException(cause);
2494 }
2495 } finally {
2496 cancel(true /* interrupt if running */);
2497 }
2498 throw new OperationCanceledException();
2499 }
2500
Sandra Kwan0b84b452016-01-20 15:25:42 -08002501 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002502 public T getResult()
2503 throws OperationCanceledException, IOException, AuthenticatorException {
2504 return internalGetResult(null, null);
2505 }
2506
Sandra Kwan0b84b452016-01-20 15:25:42 -08002507 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002508 public T getResult(long timeout, TimeUnit unit)
2509 throws OperationCanceledException, IOException, AuthenticatorException {
2510 return internalGetResult(timeout, unit);
2511 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002512
Fred Quintana60307342009-03-24 22:48:12 -07002513 }
2514
Fred Quintanaa698f422009-04-08 19:14:54 -07002515 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002516 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002517 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002518 }
Fred Quintana60307342009-03-24 22:48:12 -07002519
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002520 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002521 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002522 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002523
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002524 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002525 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002526 }
2527
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002528 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002529 return new IllegalArgumentException(message);
2530 }
2531
2532 return new AuthenticatorException(message);
2533 }
2534
sunjianf29d5492017-05-11 15:42:31 -07002535 private void getAccountByTypeAndFeatures(String accountType, String[] features,
2536 AccountManagerCallback<Bundle> callback, Handler handler) {
2537 (new AmsTask(null, handler, callback) {
2538 @Override
2539 public void doWork() throws RemoteException {
2540 mService.getAccountByTypeAndFeatures(mResponse, accountType, features,
2541 mContext.getOpPackageName());
2542 }
2543
2544 }).start();
2545 }
2546
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002547 private class GetAuthTokenByTypeAndFeaturesTask
2548 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002549 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2550 final String[] features, Activity activityForPrompting,
2551 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002552 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002553 super(activityForPrompting, handler, callback);
2554 if (accountType == null) throw new IllegalArgumentException("account type is null");
2555 mAccountType = accountType;
2556 mAuthTokenType = authTokenType;
2557 mFeatures = features;
2558 mAddAccountOptions = addAccountOptions;
2559 mLoginOptions = loginOptions;
2560 mMyCallback = this;
2561 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002562 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002563 final String mAccountType;
Mathew Inwood55418ea2018-12-20 15:30:45 +00002564 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Fred Quintana33269202009-04-20 16:05:10 -07002565 final String mAuthTokenType;
2566 final String[] mFeatures;
2567 final Bundle mAddAccountOptions;
Mathew Inwood55418ea2018-12-20 15:30:45 +00002568 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Fred Quintana33269202009-04-20 16:05:10 -07002569 final Bundle mLoginOptions;
Mathew Inwood55418ea2018-12-20 15:30:45 +00002570 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002571 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002572 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002573
Sandra Kwan0b84b452016-01-20 15:25:42 -08002574 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002575 public void doWork() throws RemoteException {
sunjianf29d5492017-05-11 15:42:31 -07002576 getAccountByTypeAndFeatures(mAccountType, mFeatures,
2577 new AccountManagerCallback<Bundle>() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002578 @Override
sunjianf29d5492017-05-11 15:42:31 -07002579 public void run(AccountManagerFuture<Bundle> future) {
2580 String accountName = null;
2581 String accountType = null;
Fred Quintana33269202009-04-20 16:05:10 -07002582 try {
sunjianf29d5492017-05-11 15:42:31 -07002583 Bundle result = future.getResult();
2584 accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2585 accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002586 } catch (OperationCanceledException e) {
2587 setException(e);
2588 return;
2589 } catch (IOException e) {
2590 setException(e);
2591 return;
2592 } catch (AuthenticatorException e) {
2593 setException(e);
2594 return;
Fred Quintana33269202009-04-20 16:05:10 -07002595 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002596
sunjianf29d5492017-05-11 15:42:31 -07002597 if (accountName == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002598 if (mActivity != null) {
2599 // no accounts, add one now. pretend that the user directly
2600 // made this request
2601 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2602 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2603 } else {
2604 // send result since we can't prompt to add an account
2605 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002606 result.putString(KEY_ACCOUNT_NAME, null);
2607 result.putString(KEY_ACCOUNT_TYPE, null);
2608 result.putString(KEY_AUTHTOKEN, null);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002609 result.putBinder(KEY_ACCOUNT_ACCESS_ID, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002610 try {
2611 mResponse.onResult(result);
2612 } catch (RemoteException e) {
2613 // this will never happen
2614 }
2615 // we are done
2616 }
sunjianf29d5492017-05-11 15:42:31 -07002617 } else {
2618 mNumAccounts = 1;
2619 Account account = new Account(accountName, accountType);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002620 // have a single account, return an authtoken for it
2621 if (mActivity == null) {
sunjianf29d5492017-05-11 15:42:31 -07002622 mFuture = getAuthToken(account, mAuthTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002623 false /* notifyAuthFailure */, mMyCallback, mHandler);
2624 } else {
sunjianf29d5492017-05-11 15:42:31 -07002625 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002626 mActivity, mMyCallback, mHandler);
2627 }
Fred Quintana33269202009-04-20 16:05:10 -07002628 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002629 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002630 }
2631
Sandra Kwan0b84b452016-01-20 15:25:42 -08002632 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002633 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002634 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002635 final Bundle result = future.getResult();
2636 if (mNumAccounts == 0) {
2637 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2638 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2639 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2640 setException(new AuthenticatorException("account not in result"));
2641 return;
2642 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07002643 final String accessId = result.getString(KEY_ACCOUNT_ACCESS_ID);
2644 final Account account = new Account(accountName, accountType, accessId);
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002645 mNumAccounts = 1;
2646 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2647 mMyCallback, mHandler);
2648 return;
2649 }
2650 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002651 } catch (OperationCanceledException e) {
2652 cancel(true /* mayInterruptIfRUnning */);
2653 } catch (IOException e) {
2654 setException(e);
2655 } catch (AuthenticatorException e) {
2656 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002657 }
2658 }
2659 }
2660
Fred Quintana756b7352009-10-21 13:43:10 -07002661 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -08002662 * This convenience helper combines the functionality of {@link #getAccountsByTypeAndFeatures},
2663 * {@link #getAuthToken}, and {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002664 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002665 * <p>
2666 * This method gets a list of the accounts matching specific type and feature set which are
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002667 * visible to the caller (see {@link #getAccountsByType} for details);
2668 * if there is exactly one already visible account, it is used; if there are some
Dmitry Dementyev52745472016-12-02 10:27:45 -08002669 * accounts for which user grant visibility, the user is prompted to pick one; if there are
2670 * none, the user is prompted to add one. Finally, an auth token is acquired for the chosen
2671 * account.
Dan Egnor661f0132010-02-19 11:23:00 -08002672 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002673 * <p>
2674 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
2675 * not be used on the main thread.
Dan Egnor661f0132010-02-19 11:23:00 -08002676 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002677 * <p>
2678 * <b>NOTE:</b> If targeting your app to work on API level 22 and before, MANAGE_ACCOUNTS
2679 * permission is needed for those platforms. See docs for this function in API level 22.
Simranjit Singh Kohli210bace2015-07-29 16:34:49 -07002680 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002681 * @param accountType The account type required (see {@link #getAccountsByType}), must not be
2682 * null
2683 * @param authTokenType The desired auth token type (see {@link #getAuthToken}), must not be
2684 * null
2685 * @param features Required features for the account (see
2686 * {@link #getAccountsByTypeAndFeatures}), may be null or empty
2687 * @param activity The {@link Activity} context to use for launching new sub-Activities to
2688 * prompt to add an account, select an account, and/or enter a password, as necessary;
2689 * used only to call startActivity(); should not be null
2690 * @param addAccountOptions Authenticator-specific options to use for adding new accounts; may
2691 * be null or empty
2692 * @param getAuthTokenOptions Authenticator-specific options to use for getting auth tokens; may
2693 * be null or empty
2694 * @param callback Callback to invoke when the request completes, null for no callback
2695 * @param handler {@link Handler} identifying the callback thread, null for the main thread
2696 * @return An {@link AccountManagerFuture} which resolves to a Bundle with at least the
2697 * following fields:
2698 * <ul>
2699 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account
2700 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account
2701 * <li>{@link #KEY_AUTHTOKEN} - the auth token you wanted
2702 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002703 *
Dmitry Dementyev52745472016-12-02 10:27:45 -08002704 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
2705 * <ul>
2706 * <li>{@link AuthenticatorException} if no authenticator was registered for this
2707 * account type or the authenticator failed to respond
2708 * <li>{@link OperationCanceledException} if the operation was canceled for any reason,
2709 * including the user canceling any operation
2710 * <li>{@link IOException} if the authenticator experienced an I/O problem updating
2711 * settings, usually because of network trouble
2712 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002713 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002714 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002715 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002716 final Activity activity, final Bundle addAccountOptions,
sunjianf29d5492017-05-11 15:42:31 -07002717 final Bundle getAuthTokenOptions, final AccountManagerCallback<Bundle> callback,
2718 final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002719 if (accountType == null) throw new IllegalArgumentException("account type is null");
2720 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002721 final GetAuthTokenByTypeAndFeaturesTask task =
2722 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002723 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002724 task.start();
2725 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002726 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002727
Fred Quintana1121bb52011-09-14 23:19:35 -07002728 /**
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002729 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
2730 * String, String[], Bundle)}.
2731 *
Fred Quintana1121bb52011-09-14 23:19:35 -07002732 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2733 * accounts.
2734 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002735 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002736 * <p>
2737 * On success the activity returns a Bundle with the account name and type specified using
2738 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002739 * Chosen account is marked as {@link #VISIBILITY_USER_MANAGED_VISIBLE} to the caller
Jeff Sharkey67f9d502017-08-05 13:49:13 -06002740 * (see {@link #setAccountVisibility}) and will be returned to it in consequent
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002741 * {@link #getAccountsByType}) calls.
Fred Quintana1121bb52011-09-14 23:19:35 -07002742 * <p>
2743 * The most common case is to call this with one account type, e.g.:
2744 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002745 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002746 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002747 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2748 * selected one, according to the caller's definition of selected.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002749 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
Fred Quintana1121bb52011-09-14 23:19:35 -07002750 * shown. If not specified then this field will not limit the displayed accounts.
2751 * @param allowableAccountTypes an optional string array of account types. These are used
2752 * 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 -07002753 * when adding an account. If not specified then this field will not limit the displayed
2754 * account types when adding an account.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002755 * @param alwaysPromptForAccount boolean that is ignored.
Fred Quintanad88324d2011-09-19 11:43:05 -07002756 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002757 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002758 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2759 * authTokenType parameter
2760 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2761 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002762 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002763 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002764 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002765 */
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002766 @Deprecated
2767 static public Intent newChooseAccountIntent(
2768 Account selectedAccount,
Baligh Uddinf2d248d2015-07-10 03:01:47 +00002769 ArrayList<Account> allowableAccounts,
Fred Quintana1121bb52011-09-14 23:19:35 -07002770 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002771 boolean alwaysPromptForAccount,
2772 String descriptionOverrideText,
2773 String addAccountAuthTokenType,
2774 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002775 Bundle addAccountOptions) {
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002776 return newChooseAccountIntent(
2777 selectedAccount,
2778 allowableAccounts,
2779 allowableAccountTypes,
2780 descriptionOverrideText,
2781 addAccountAuthTokenType,
2782 addAccountRequiredFeatures,
2783 addAccountOptions);
2784 }
2785
2786 /**
2787 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2788 * accounts.
2789 * The caller will then typically start the activity by calling
2790 * <code>startActivityForResult(intent, ...);</code>.
2791 * <p>
2792 * On success the activity returns a Bundle with the account name and type specified using
2793 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002794 * Chosen account is marked as {@link #VISIBILITY_USER_MANAGED_VISIBLE} to the caller
Jeff Sharkey67f9d502017-08-05 13:49:13 -06002795 * (see {@link #setAccountVisibility}) and will be returned to it in consequent
Dmitry Dementyev85d8a342017-05-02 17:33:17 -07002796 * {@link #getAccountsByType}) calls.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002797 * <p>
2798 * The most common case is to call this with one account type, e.g.:
2799 * <p>
2800 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null,
2801 * null);</pre>
2802 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2803 * selected one, according to the caller's definition of selected.
2804 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
2805 * shown. If not specified then this field will not limit the displayed accounts.
2806 * @param allowableAccountTypes an optional string array of account types. These are used
2807 * both to filter the shown accounts and to filter the list of account types that are shown
2808 * when adding an account. If not specified then this field will not limit the displayed
2809 * account types when adding an account.
2810 * @param descriptionOverrideText if non-null this string is used as the description in the
2811 * accounts chooser screen rather than the default
2812 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2813 * authTokenType parameter
2814 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2815 * requiredFeatures parameter
2816 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2817 * parameter
2818 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2819 */
2820 static public Intent newChooseAccountIntent(
2821 Account selectedAccount,
2822 List<Account> allowableAccounts,
2823 String[] allowableAccountTypes,
2824 String descriptionOverrideText,
2825 String addAccountAuthTokenType,
2826 String[] addAccountRequiredFeatures,
2827 Bundle addAccountOptions) {
Fred Quintana1121bb52011-09-14 23:19:35 -07002828 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002829 ComponentName componentName = ComponentName.unflattenFromString(
2830 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2831 intent.setClassName(componentName.getPackageName(),
2832 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002833 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
Craig Lafayette3c9c71d2015-07-14 10:48:46 -04002834 allowableAccounts == null ? null : new ArrayList<Account>(allowableAccounts));
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002835 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2836 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002837 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2838 addAccountOptions);
2839 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002840 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2841 descriptionOverrideText);
2842 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2843 addAccountAuthTokenType);
2844 intent.putExtra(
2845 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2846 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002847 return intent;
2848 }
2849
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002850 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002851 Maps.newHashMap();
2852
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002853 private final HashMap<OnAccountsUpdateListener, Set<String> > mAccountsUpdatedListenersTypes =
2854 Maps.newHashMap();
2855
Fred Quintanad9d2f112009-04-23 13:36:27 -07002856 /**
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002857 * BroadcastReceiver that listens for the ACTION_VISIBLE_ACCOUNTS_CHANGED intent
Fred Quintanad9d2f112009-04-23 13:36:27 -07002858 * so that it can read the updated list of accounts and send them to the listener
2859 * in mAccountsUpdatedListeners.
2860 */
2861 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
Sandra Kwan0b84b452016-01-20 15:25:42 -08002862 @Override
Fred Quintanad9d2f112009-04-23 13:36:27 -07002863 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002864 final Account[] accounts = getAccounts();
2865 // send the result to the listeners
2866 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002867 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002868 mAccountsUpdatedListeners.entrySet()) {
2869 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002870 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002871 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002872 }
2873 };
2874
2875 /**
Dmitry Dementyev52745472016-12-02 10:27:45 -08002876 * Adds an {@link OnAccountsUpdateListener} to this instance of the {@link AccountManager}. This
2877 * listener will be notified whenever user or AbstractAcccountAuthenticator made changes to
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002878 * accounts of any type related to the caller. This method is equivalent to
2879 * addOnAccountsUpdatedListener(listener, handler, updateImmediately, null)
Dan Egnor661f0132010-02-19 11:23:00 -08002880 *
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002881 * @see #addOnAccountsUpdatedListener(OnAccountsUpdateListener, Handler, boolean,
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002882 * String[])
2883 */
2884 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
2885 Handler handler, boolean updateImmediately) {
2886 addOnAccountsUpdatedListener(listener, handler,updateImmediately, null);
2887 }
2888
2889 /**
2890 * Adds an {@link OnAccountsUpdateListener} to this instance of the {@link AccountManager}. This
2891 * listener will be notified whenever user or AbstractAcccountAuthenticator made changes to
2892 * accounts of given types related to the caller -
2893 * either list of accounts returned by {@link #getAccounts()}
2894 * was changed, or new account was added for which user can grant access to the caller.
Dmitry Dementyev52745472016-12-02 10:27:45 -08002895 * <p>
2896 * As long as this listener is present, the AccountManager instance will not be
2897 * garbage-collected, and neither will the {@link Context} used to retrieve it, which may be a
2898 * large Activity instance. To avoid memory leaks, you must remove this listener before then.
2899 * Normally listeners are added in an Activity or Service's {@link Activity#onCreate} and
2900 * removed in {@link Activity#onDestroy}.
Dmitry Dementyev52745472016-12-02 10:27:45 -08002901 * <p>
2902 * It is safe to call this method from the main thread.
Ian Pedowitz845d14d2015-08-04 07:47:37 -07002903 *
Dan Egnor661f0132010-02-19 11:23:00 -08002904 * @param listener The listener to send notifications to
Dmitry Dementyev52745472016-12-02 10:27:45 -08002905 * @param handler {@link Handler} identifying the thread to use for notifications, null for the
2906 * main thread
2907 * @param updateImmediately If true, the listener will be invoked (on the handler thread) right
2908 * away with the current account list
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002909 * @param accountTypes If set, only changes to accounts of given types will be reported.
Fred Quintanad9d2f112009-04-23 13:36:27 -07002910 * @throws IllegalArgumentException if listener is null
2911 * @throws IllegalStateException if listener was already added
2912 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002913 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Dmitry Dementyev2ae64092017-01-09 12:48:18 -08002914 Handler handler, boolean updateImmediately, String[] accountTypes) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07002915 if (listener == null) {
2916 throw new IllegalArgumentException("the listener is null");
2917 }
2918 synchronized (mAccountsUpdatedListeners) {
2919 if (mAccountsUpdatedListeners.containsKey(listener)) {
2920 throw new IllegalStateException("this listener is already added");
2921 }
2922 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2923
2924 mAccountsUpdatedListeners.put(listener, handler);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002925 if (accountTypes != null) {
2926 mAccountsUpdatedListenersTypes.put(listener,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002927 new HashSet<String>(Arrays.asList(accountTypes)));
2928 } else {
2929 mAccountsUpdatedListenersTypes.put(listener, null);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002930 }
Dmitry Dementyev52745472016-12-02 10:27:45 -08002931
Fred Quintanad9d2f112009-04-23 13:36:27 -07002932 if (wasEmpty) {
2933 // Register a broadcast receiver to monitor account changes
2934 IntentFilter intentFilter = new IntentFilter();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002935 intentFilter.addAction(ACTION_VISIBLE_ACCOUNTS_CHANGED);
Costin Manolacheb6437242009-09-10 16:14:12 -07002936 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002937 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002938 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2939 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002940
2941 try {
2942 // Notify AccountManagedService about new receiver.
2943 // The receiver must be unregistered later exactly one time
2944 mService.registerAccountListener(accountTypes, mContext.getOpPackageName());
2945 } catch (RemoteException e) {
2946 throw e.rethrowFromSystemServer();
2947 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002948 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002949 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002950 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002951 }
2952 }
2953
2954 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002955 * Removes an {@link OnAccountsUpdateListener} previously registered with
2956 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2957 * receive notifications of account changes.
2958 *
2959 * <p>It is safe to call this method from the main thread.
2960 *
2961 * <p>No permission is required to call this method.
2962 *
2963 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002964 * @throws IllegalArgumentException if listener is null
2965 * @throws IllegalStateException if listener was not already added
2966 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002967 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002968 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002969 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002970 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002971 Log.e(TAG, "Listener was not previously added");
2972 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002973 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002974 Set<String> accountTypes = mAccountsUpdatedListenersTypes.get(listener);
2975 String[] accountsArray;
2976 if (accountTypes != null) {
2977 accountsArray = accountTypes.toArray(new String[accountTypes.size()]);
2978 } else {
2979 accountsArray = null;
2980 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002981 mAccountsUpdatedListeners.remove(listener);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002982 mAccountsUpdatedListenersTypes.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002983 if (mAccountsUpdatedListeners.isEmpty()) {
2984 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2985 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002986 try {
2987 mService.unregisterAccountListener(accountsArray, mContext.getOpPackageName());
2988 } catch (RemoteException e) {
2989 throw e.rethrowFromSystemServer();
2990 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002991 }
2992 }
Sandra Kwan78812282015-11-04 11:19:47 -08002993
2994 /**
2995 * Asks the user to authenticate with an account of a specified type. The
2996 * authenticator for this account type processes this request with the
2997 * appropriate user interface. If the user does elect to authenticate with a
2998 * new account, a bundle of session data for installing the account later is
2999 * returned with optional account password and account status token.
3000 * <p>
3001 * This method may be called from any thread, but the returned
3002 * {@link AccountManagerFuture} must not be used on the main thread.
3003 * <p>
3004 * <p>
3005 * <b>NOTE:</b> The account will not be installed to the device by calling
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003006 * this api alone. #finishSession should be called after this to install the
3007 * account on device.
Sandra Kwan78812282015-11-04 11:19:47 -08003008 *
3009 * @param accountType The type of account to add; must not be null
3010 * @param authTokenType The type of auth token (see {@link #getAuthToken})
3011 * this account will need to be able to generate, null for none
3012 * @param requiredFeatures The features (see {@link #hasFeatures}) this
3013 * account must have, null for none
3014 * @param options Authenticator-specific options for the request, may be
3015 * null or empty
3016 * @param activity The {@link Activity} context to use for launching a new
3017 * authenticator-defined sub-Activity to prompt the user to
3018 * create an account; used only to call startActivity(); if null,
3019 * the prompt will not be launched directly, but the necessary
3020 * {@link Intent} will be returned to the caller instead
3021 * @param callback Callback to invoke when the request completes, null for
3022 * no callback
3023 * @param handler {@link Handler} identifying the callback thread, null for
3024 * the main thread
3025 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
3026 * these fields if activity was specified and user was authenticated
3027 * with an account:
3028 * <ul>
3029 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
3030 * adding the the to the device later.
Sandra Kwan78812282015-11-04 11:19:47 -08003031 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3032 * status of the account
3033 * </ul>
3034 * If no activity was specified, the returned Bundle contains only
3035 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
3036 * actual account creation process. If authenticator doesn't support
3037 * this method, the returned Bundle contains only
3038 * {@link #KEY_ACCOUNT_SESSION_BUNDLE} with encrypted
3039 * {@code options} needed to add account later. If an error
3040 * occurred, {@link AccountManagerFuture#getResult()} throws:
3041 * <ul>
3042 * <li>{@link AuthenticatorException} if no authenticator was
3043 * registered for this account type or the authenticator failed to
3044 * respond
3045 * <li>{@link OperationCanceledException} if the operation was
3046 * canceled for any reason, including the user canceling the
3047 * creation process or adding accounts (of this type) has been
3048 * disabled by policy
3049 * <li>{@link IOException} if the authenticator experienced an I/O
3050 * problem creating a new account, usually because of network
3051 * trouble
3052 * </ul>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003053 * @see #finishSession
Sandra Kwan78812282015-11-04 11:19:47 -08003054 */
Sandra Kwane68c37e2015-11-12 17:11:49 -08003055 public AccountManagerFuture<Bundle> startAddAccountSession(
3056 final String accountType,
3057 final String authTokenType,
3058 final String[] requiredFeatures,
3059 final Bundle options,
3060 final Activity activity,
3061 AccountManagerCallback<Bundle> callback,
3062 Handler handler) {
Sandra Kwan78812282015-11-04 11:19:47 -08003063 if (accountType == null) throw new IllegalArgumentException("accountType is null");
3064 final Bundle optionsIn = new Bundle();
3065 if (options != null) {
3066 optionsIn.putAll(options);
3067 }
3068 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
3069
3070 return new AmsTask(activity, handler, callback) {
3071 @Override
3072 public void doWork() throws RemoteException {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003073 mService.startAddAccountSession(
3074 mResponse,
3075 accountType,
3076 authTokenType,
3077 requiredFeatures,
3078 activity != null,
3079 optionsIn);
3080 }
3081 }.start();
3082 }
3083
3084 /**
3085 * Asks the user to enter a new password for an account but not updating the
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003086 * saved credentials for the account until {@link #finishSession} is called.
Sandra Kwane68c37e2015-11-12 17:11:49 -08003087 * <p>
3088 * This method may be called from any thread, but the returned
3089 * {@link AccountManagerFuture} must not be used on the main thread.
3090 * <p>
3091 * <b>NOTE:</b> The saved credentials for the account alone will not be
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003092 * updated by calling this API alone. #finishSession should be called after
3093 * this to update local credentials
Sandra Kwane68c37e2015-11-12 17:11:49 -08003094 *
3095 * @param account The account to update credentials for
3096 * @param authTokenType The credentials entered must allow an auth token of
3097 * this type to be created (but no actual auth token is
3098 * returned); may be null
3099 * @param options Authenticator-specific options for the request; may be
3100 * null or empty
3101 * @param activity The {@link Activity} context to use for launching a new
3102 * authenticator-defined sub-Activity to prompt the user to enter
3103 * a password; used only to call startActivity(); if null, the
3104 * prompt will not be launched directly, but the necessary
3105 * {@link Intent} will be returned to the caller instead
3106 * @param callback Callback to invoke when the request completes, null for
3107 * no callback
3108 * @param handler {@link Handler} identifying the callback thread, null for
3109 * the main thread
3110 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
3111 * these fields if an activity was supplied and user was
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003112 * successfully re-authenticated to the account:
Sandra Kwane68c37e2015-11-12 17:11:49 -08003113 * <ul>
3114 * <li>{@link #KEY_ACCOUNT_SESSION_BUNDLE} - encrypted Bundle for
3115 * updating the local credentials on device later.
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003116 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3117 * status of the account
Sandra Kwane68c37e2015-11-12 17:11:49 -08003118 * </ul>
3119 * If no activity was specified, the returned Bundle contains
3120 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
3121 * password prompt. If an error occurred,
3122 * {@link AccountManagerFuture#getResult()} throws:
3123 * <ul>
3124 * <li>{@link AuthenticatorException} if the authenticator failed to
3125 * respond
3126 * <li>{@link OperationCanceledException} if the operation was
3127 * canceled for any reason, including the user canceling the
3128 * password prompt
3129 * <li>{@link IOException} if the authenticator experienced an I/O
3130 * problem verifying the password, usually because of network
3131 * trouble
3132 * </ul>
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003133 * @see #finishSession
Sandra Kwane68c37e2015-11-12 17:11:49 -08003134 */
3135 public AccountManagerFuture<Bundle> startUpdateCredentialsSession(
3136 final Account account,
3137 final String authTokenType,
3138 final Bundle options,
3139 final Activity activity,
3140 final AccountManagerCallback<Bundle> callback,
3141 final Handler handler) {
3142 if (account == null) {
3143 throw new IllegalArgumentException("account is null");
3144 }
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003145
3146 // Always include the calling package name. This just makes life easier
3147 // down stream.
3148 final Bundle optionsIn = new Bundle();
3149 if (options != null) {
3150 optionsIn.putAll(options);
3151 }
3152 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
3153
Sandra Kwane68c37e2015-11-12 17:11:49 -08003154 return new AmsTask(activity, handler, callback) {
3155 @Override
3156 public void doWork() throws RemoteException {
3157 mService.startUpdateCredentialsSession(
3158 mResponse,
3159 account,
3160 authTokenType,
3161 activity != null,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003162 optionsIn);
Sandra Kwan78812282015-11-04 11:19:47 -08003163 }
3164 }.start();
3165 }
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003166
3167 /**
3168 * Finishes the session started by {@link #startAddAccountSession} or
3169 * {@link #startUpdateCredentialsSession}. This will either add the account
3170 * to AccountManager or update the local credentials stored.
3171 * <p>
3172 * This method may be called from any thread, but the returned
3173 * {@link AccountManagerFuture} must not be used on the main thread.
3174 *
3175 * @param sessionBundle a {@link Bundle} created by {@link #startAddAccountSession} or
3176 * {@link #startUpdateCredentialsSession}
3177 * @param activity The {@link Activity} context to use for launching a new
3178 * authenticator-defined sub-Activity to prompt the user to
3179 * create an account or reauthenticate existing account; used
3180 * only to call startActivity(); if null, the prompt will not
3181 * be launched directly, but the necessary {@link Intent} will
3182 * be returned to the caller instead
3183 * @param callback Callback to invoke when the request completes, null for
3184 * no callback
3185 * @param handler {@link Handler} identifying the callback thread, null for
3186 * the main thread
3187 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
3188 * these fields if an activity was supplied and an account was added
3189 * to device or local credentials were updated::
3190 * <ul>
3191 * <li>{@link #KEY_ACCOUNT_NAME} - the name of the account created
3192 * <li>{@link #KEY_ACCOUNT_TYPE} - the type of the account
Hongming Jin8b442752016-06-26 10:36:21 -07003193 * <li>{@link #KEY_ACCOUNT_STATUS_TOKEN} - optional, token to check
3194 * status of the account
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003195 * </ul>
3196 * If no activity was specified and additional information is needed
3197 * from user, the returned Bundle may contains only
3198 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
3199 * actual account creation process. If an error occurred,
3200 * {@link AccountManagerFuture#getResult()} throws:
3201 * <ul>
3202 * <li>{@link AuthenticatorException} if no authenticator was
3203 * registered for this account type or the authenticator failed to
3204 * respond
3205 * <li>{@link OperationCanceledException} if the operation was
3206 * canceled for any reason, including the user canceling the
3207 * creation process or adding accounts (of this type) has been
3208 * disabled by policy
3209 * <li>{@link IOException} if the authenticator experienced an I/O
3210 * problem creating a new account, usually because of network
3211 * trouble
3212 * </ul>
3213 * @see #startAddAccountSession and #startUpdateCredentialsSession
3214 */
3215 public AccountManagerFuture<Bundle> finishSession(
3216 final Bundle sessionBundle,
3217 final Activity activity,
3218 AccountManagerCallback<Bundle> callback,
3219 Handler handler) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003220 return finishSessionAsUser(
3221 sessionBundle,
3222 activity,
Jeff Sharkeyad357d12018-02-02 13:25:31 -07003223 mContext.getUser(),
Sandra Kwan0b84b452016-01-20 15:25:42 -08003224 callback,
3225 handler);
3226 }
3227
3228 /**
3229 * @see #finishSession
3230 * @hide
3231 */
3232 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06003233 @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
Sandra Kwan0b84b452016-01-20 15:25:42 -08003234 public AccountManagerFuture<Bundle> finishSessionAsUser(
3235 final Bundle sessionBundle,
3236 final Activity activity,
3237 final UserHandle userHandle,
3238 AccountManagerCallback<Bundle> callback,
3239 Handler handler) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003240 if (sessionBundle == null) {
3241 throw new IllegalArgumentException("sessionBundle is null");
3242 }
3243
3244 /* Add information required by add account flow */
3245 final Bundle appInfo = new Bundle();
3246 appInfo.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
3247
3248 return new AmsTask(activity, handler, callback) {
3249 @Override
3250 public void doWork() throws RemoteException {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003251 mService.finishSessionAsUser(
3252 mResponse,
3253 sessionBundle,
3254 activity != null,
3255 appInfo,
3256 userHandle.getIdentifier());
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003257 }
3258 }.start();
3259 }
Sandra Kwan390c9d22016-01-12 14:13:37 -08003260
3261 /**
3262 * Checks whether {@link #updateCredentials} or {@link #startUpdateCredentialsSession} should be
3263 * called with respect to the specified account.
3264 * <p>
3265 * This method may be called from any thread, but the returned {@link AccountManagerFuture} must
3266 * not be used on the main thread.
3267 *
3268 * @param account The {@link Account} to be checked whether {@link #updateCredentials} or
3269 * {@link #startUpdateCredentialsSession} should be called
3270 * @param statusToken a String of token to check account staus
3271 * @param callback Callback to invoke when the request completes, null for no callback
3272 * @param handler {@link Handler} identifying the callback thread, null for the main thread
3273 * @return An {@link AccountManagerFuture} which resolves to a Boolean, true if the credentials
3274 * of the account should be updated.
Sandra Kwan390c9d22016-01-12 14:13:37 -08003275 */
Sandra Kwan390c9d22016-01-12 14:13:37 -08003276 public AccountManagerFuture<Boolean> isCredentialsUpdateSuggested(
3277 final Account account,
3278 final String statusToken,
3279 AccountManagerCallback<Boolean> callback,
3280 Handler handler) {
3281 if (account == null) {
3282 throw new IllegalArgumentException("account is null");
3283 }
3284
3285 if (TextUtils.isEmpty(statusToken)) {
3286 throw new IllegalArgumentException("status token is empty");
3287 }
3288
3289 return new Future2Task<Boolean>(handler, callback) {
Sandra Kwan0b84b452016-01-20 15:25:42 -08003290 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003291 public void doWork() throws RemoteException {
3292 mService.isCredentialsUpdateSuggested(
3293 mResponse,
3294 account,
3295 statusToken);
3296 }
Sandra Kwan0b84b452016-01-20 15:25:42 -08003297 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003298 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
3299 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
3300 throw new AuthenticatorException("no result in response");
3301 }
3302 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
3303 }
3304 }.start();
3305 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003306
3307 /**
3308 * Gets whether a given package under a user has access to an account.
3309 * Can be called only from the system UID.
3310 *
3311 * @param account The account for which to check.
3312 * @param packageName The package for which to check.
3313 * @param userHandle The user for which to check.
3314 * @return True if the package can access the account.
3315 *
3316 * @hide
3317 */
3318 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3319 @NonNull UserHandle userHandle) {
3320 try {
3321 return mService.hasAccountAccess(account, packageName, userHandle);
3322 } catch (RemoteException e) {
3323 throw e.rethrowFromSystemServer();
3324 }
3325 }
3326
3327 /**
3328 * Creates an intent to request access to a given account for a UID.
3329 * The returned intent should be stated for a result where {@link
3330 * Activity#RESULT_OK} result means access was granted whereas {@link
3331 * Activity#RESULT_CANCELED} result means access wasn't granted. Can
3332 * be called only from the system UID.
3333 *
3334 * @param account The account for which to request.
3335 * @param packageName The package name which to request.
3336 * @param userHandle The user for which to request.
3337 * @return The intent to request account access or null if the package
3338 * doesn't exist.
3339 *
3340 * @hide
3341 */
3342 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3343 @NonNull String packageName, @NonNull UserHandle userHandle) {
3344 try {
3345 return mService.createRequestAccountAccessIntentSenderAsUser(account, packageName,
3346 userHandle);
3347 } catch (RemoteException e) {
3348 throw e.rethrowFromSystemServer();
3349 }
3350 }
Fred Quintana60307342009-03-24 22:48:12 -07003351}