blob: 7a209296a08c0dcabf8a26d105901f7c56264f20 [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
Tor Norbye80b530a2015-04-23 16:36:09 -070019import android.annotation.RequiresPermission;
20import android.annotation.Size;
Fred Quintana60307342009-03-24 22:48:12 -070021import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080022import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070023import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070024import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080025import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070026import android.content.IntentFilter;
Amith Yamasani12b8e132013-03-14 10:48:07 -070027import android.content.res.Resources;
Costin Manolacheb6437242009-09-10 16:14:12 -070028import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080029import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070030import android.os.Bundle;
31import android.os.Handler;
32import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070033import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080034import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080035import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080036import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080037import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080038import android.util.Log;
39
40import com.android.internal.R;
41import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070042
Fred Quintanaa698f422009-04-08 19:14:54 -070043import java.io.IOException;
Fred Quintana1121bb52011-09-14 23:19:35 -070044import java.util.ArrayList;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080045import java.util.HashMap;
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -070046import java.util.List;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080047import java.util.Map;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import java.util.concurrent.Callable;
49import java.util.concurrent.CancellationException;
50import java.util.concurrent.ExecutionException;
51import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070052import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080053import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070054
Tor Norbye80b530a2015-04-23 16:36:09 -070055import static android.Manifest.permission.GET_ACCOUNTS;
Tor Norbye80b530a2015-04-23 16:36:09 -070056
Fred Quintana60307342009-03-24 22:48:12 -070057/**
Dan Egnor661f0132010-02-19 11:23:00 -080058 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070059 * online accounts. The user enters credentials (username and password) once
60 * per account, granting applications access to online resources with
61 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070062 *
Dan Egnor661f0132010-02-19 11:23:00 -080063 * <p>Different online services have different ways of handling accounts and
64 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070065 * modules for different <em>account types</em>. Authenticators (which may be
66 * written by third parties) handle the actual details of validating account
67 * credentials and storing account information. For example, Google, Facebook,
68 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080069 *
70 * <p>Many servers support some notion of an <em>authentication token</em>,
71 * which can be used to authenticate a request to the server without sending
72 * the user's actual password. (Auth tokens are normally created with a
73 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070074 * can generate auth tokens for applications, so the application doesn't need to
75 * handle passwords directly. Auth tokens are normally reusable and cached by
76 * AccountManager, but must be refreshed periodically. It's the responsibility
77 * of applications to <em>invalidate</em> auth tokens when they stop working so
78 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080079 *
80 * <p>Applications accessing a server normally go through these steps:
81 *
82 * <ul>
83 * <li>Get an instance of AccountManager using {@link #get(Context)}.
84 *
85 * <li>List the available accounts using {@link #getAccountsByType} or
86 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
87 * be interested in accounts with one particular <em>type</em>, which
88 * identifies the authenticator. Account <em>features</em> are used to
89 * identify particular account subtypes and capabilities. Both the account
90 * type and features are authenticator-specific strings, and must be known by
91 * the application in coordination with its preferred authenticators.
92 *
93 * <li>Select one or more of the available accounts, possibly by asking the
94 * user for their preference. If no suitable accounts are available,
95 * {@link #addAccount} may be called to prompt the user to create an
96 * account of the appropriate type.
97 *
Dan Egnor8e4378b2010-08-02 18:22:09 -070098 * <li><b>Important:</b> If the application is using a previously remembered
99 * account selection, it must make sure the account is still in the list
100 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
101 * for an account no longer on the device results in an undefined failure.
102 *
Dan Egnor661f0132010-02-19 11:23:00 -0800103 * <li>Request an auth token for the selected account(s) using one of the
104 * {@link #getAuthToken} methods or related helpers. Refer to the description
105 * of each method for exact usage and error handling details.
106 *
107 * <li>Make the request using the auth token. The form of the auth token,
108 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700109 * service you are accessing. The application may use whatever network and
110 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800111 *
112 * <li><b>Important:</b> If the request fails with an authentication error,
113 * it could be that a cached auth token is stale and no longer honored by
114 * the server. The application must call {@link #invalidateAuthToken} to remove
115 * the token from the cache, otherwise requests will continue failing! After
116 * invalidating the auth token, immediately go back to the "Request an auth
117 * token" step above. If the process fails the second time, then it can be
118 * treated as a "genuine" authentication failure and the user notified or other
119 * appropriate actions taken.
120 * </ul>
121 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700122 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800123 * prompt for credentials, present options, or ask the user to add an account.
124 * The caller may choose whether to allow AccountManager to directly launch the
125 * necessary user interface and wait for the user, or to return an Intent which
126 * the caller may use to launch the interface, or (in some cases) to install a
127 * notification which the user can select at any time to launch the interface.
128 * To have AccountManager launch the interface directly, the caller must supply
129 * the current foreground {@link Activity} context.
130 *
131 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700132 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800133 * run asynchronously. If a callback is provided then
134 * {@link AccountManagerCallback#run} will be invoked on the Handler's
135 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700136 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
137 * on the {@link AccountManagerFuture} returned by the method (and also passed
138 * to the callback). This method waits for the operation to complete (if
139 * necessary) and either returns the result or throws an exception if an error
140 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800141 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700142 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800143 *
144 * <p>Requests which may block, including
145 * {@link AccountManagerFuture#getResult()}, must never be called on
146 * the application's main event thread. These operations throw
147 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700148 */
149public class AccountManager {
150 private static final String TAG = "AccountManager";
151
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700152 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
153 public static final int ERROR_CODE_NETWORK_ERROR = 3;
154 public static final int ERROR_CODE_CANCELED = 4;
155 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
156 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
157 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
158 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700159 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700160
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800161 /** @hide */
162 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100163 /** @hide */
164 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800165
Dan Egnor661f0132010-02-19 11:23:00 -0800166 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700167 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800168 * from methods which return information about a particular account.
169 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700170 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800171
172 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700173 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800174 * from methods which return information about a particular account.
175 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700176 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800177
178 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700179 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800180 * from {@link #getAuthToken} and friends.
181 */
182 public static final String KEY_AUTHTOKEN = "authtoken";
183
184 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700185 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800186 * may require the caller to interact with the user. The Intent can
187 * be used to start the corresponding user interface activity.
188 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700189 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800190
191 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700192 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800193 * {@link #confirmCredentials}, rather than prompting the user with
194 * the standard password prompt.
195 */
196 public static final String KEY_PASSWORD = "password";
197
198 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700199
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700200 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
201 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800202 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700203 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
204 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800205 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
206 public static final String KEY_ERROR_CODE = "errorCode";
207 public static final String KEY_ERROR_MESSAGE = "errorMessage";
208 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700209
Costin Manolachea40c6302010-12-13 14:50:45 -0800210 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800211 * Bundle key used to supply the last time the credentials of the account
212 * were authenticated successfully. Time is specified in milliseconds since
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700213 * epoch. Associated time is updated on successful authentication of account
214 * on adding account, confirming credentials, or updating credentials.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800215 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700216 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800217
218 /**
Costin Manolachea40c6302010-12-13 14:50:45 -0800219 * Authenticators using 'customTokens' option will also get the UID of the
220 * caller
221 */
222 public static final String KEY_CALLER_UID = "callerUid";
223 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800224
Costin Manolached6060452011-01-24 16:11:36 -0800225 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700226 * The Android package of the caller will be set in the options bundle by the
227 * {@link AccountManager} and will be passed to the AccountManagerService and
228 * to the AccountAuthenticators. The uid of the caller will be known by the
229 * AccountManagerService as well as the AccountAuthenticators so they will be able to
230 * verify that the package is consistent with the uid (a uid might be shared by many
231 * packages).
232 */
233 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
234
235 /**
Costin Manolached6060452011-01-24 16:11:36 -0800236 * Boolean, if set and 'customTokens' the authenticator is responsible for
237 * notifications.
238 * @hide
239 */
240 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
241
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700242 public static final String ACTION_AUTHENTICATOR_INTENT =
243 "android.accounts.AccountAuthenticator";
244 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800245 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700246 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
247
Fred Quintana60307342009-03-24 22:48:12 -0700248 private final Context mContext;
249 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700250 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800251
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700252 /**
253 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800254 * when accounts are added, accounts are removed, or an
255 * account's credentials (saved password, etc) are changed.
256 *
257 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700258 */
259 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
260 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700261
Fred Quintana33269202009-04-20 16:05:10 -0700262 /**
263 * @hide
264 */
Fred Quintana60307342009-03-24 22:48:12 -0700265 public AccountManager(Context context, IAccountManager service) {
266 mContext = context;
267 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700268 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700269 }
270
Fred Quintana0eabf022009-04-27 15:08:17 -0700271 /**
272 * @hide used for testing only
273 */
274 public AccountManager(Context context, IAccountManager service, Handler handler) {
275 mContext = context;
276 mService = service;
277 mMainHandler = handler;
278 }
279
Fred Quintana756b7352009-10-21 13:43:10 -0700280 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800281 * @hide for internal use only
282 */
283 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700284 if (result != null) {
285 if (result.containsKey(KEY_AUTHTOKEN)
286 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
287 final Bundle newResult = new Bundle(result);
288 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
289 return newResult;
290 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800291 }
292 return result;
293 }
294
295 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800296 * Gets an AccountManager instance associated with a Context.
297 * The {@link Context} will be used as long as the AccountManager is
298 * active, so make sure to use a {@link Context} whose lifetime is
299 * commensurate with any listeners registered to
300 * {@link #addOnAccountsUpdatedListener} or similar methods.
301 *
302 * <p>It is safe to call this method from the main thread.
303 *
304 * <p>No permission is required to call this method.
305 *
Fred Quintana756b7352009-10-21 13:43:10 -0700306 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800307 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700308 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700309 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700310 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700311 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
312 }
313
Fred Quintana756b7352009-10-21 13:43:10 -0700314 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800315 * Gets the saved password associated with the account.
316 * This is intended for authenticators and related code; applications
317 * should get an auth token instead.
318 *
319 * <p>It is safe to call this method from the main thread.
320 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700321 * <p>This method requires the caller to have a signature match with the
322 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800323 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700324 * @param account The account to query for a password. Must not be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800325 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700326 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700327 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700328 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700329 try {
330 return mService.getPassword(account);
331 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700332 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700333 throw new RuntimeException(e);
334 }
335 }
336
Fred Quintana756b7352009-10-21 13:43:10 -0700337 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800338 * Gets the user data named by "key" associated with the account.
339 * This is intended for authenticators and related code to store
340 * arbitrary metadata along with accounts. The meaning of the keys
341 * and values is up to the authenticator for the account.
342 *
343 * <p>It is safe to call this method from the main thread.
344 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700345 * <p>This method requires the caller to have a signature match with the
346 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800347 *
348 * @param account The account to query for user data
349 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700350 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700351 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700352 if (account == null) throw new IllegalArgumentException("account is null");
353 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700354 try {
355 return mService.getUserData(account, key);
356 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700357 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700358 throw new RuntimeException(e);
359 }
360 }
361
Fred Quintana756b7352009-10-21 13:43:10 -0700362 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800363 * Lists the currently registered authenticators.
364 *
365 * <p>It is safe to call this method from the main thread.
366 *
367 * <p>No permission is required to call this method.
368 *
369 * @return An array of {@link AuthenticatorDescription} for every
370 * authenticator known to the AccountManager service. Empty (never
371 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700372 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700373 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700374 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100375 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
376 } catch (RemoteException e) {
377 // will never happen
378 throw new RuntimeException(e);
379 }
380 }
381
382 /**
383 * @hide
384 * Lists the currently registered authenticators for a given user id.
385 *
386 * <p>It is safe to call this method from the main thread.
387 *
388 * <p>The caller has to be in the same user or have the permission
389 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
390 *
391 * @return An array of {@link AuthenticatorDescription} for every
392 * authenticator known to the AccountManager service. Empty (never
393 * null) if no authenticators are known.
394 */
395 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
396 try {
397 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700398 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700399 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700400 throw new RuntimeException(e);
401 }
402 }
403
Fred Quintana756b7352009-10-21 13:43:10 -0700404 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800405 * Lists all accounts of any type registered on the device.
406 * Equivalent to getAccountsByType(null).
407 *
408 * <p>It is safe to call this method from the main thread.
409 *
410 * <p>This method requires the caller to hold the permission
411 * {@link android.Manifest.permission#GET_ACCOUNTS}.
412 *
413 * @return An array of {@link Account}, one for each account. Empty
414 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700415 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700416 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700417 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700418 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700419 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700420 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700421 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700422 throw new RuntimeException(e);
423 }
424 }
425
Fred Quintana756b7352009-10-21 13:43:10 -0700426 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700427 * @hide
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100428 * Lists all accounts of any type registered on the device for a given
429 * user id. Equivalent to getAccountsByType(null).
430 *
431 * <p>It is safe to call this method from the main thread.
432 *
433 * <p>This method requires the caller to hold the permission
434 * {@link android.Manifest.permission#GET_ACCOUNTS}.
435 *
436 * @return An array of {@link Account}, one for each account. Empty
437 * (never null) if no accounts have been added.
438 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700439 @RequiresPermission(GET_ACCOUNTS)
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100440 public Account[] getAccountsAsUser(int userId) {
441 try {
442 return mService.getAccountsAsUser(null, userId);
443 } catch (RemoteException e) {
444 // won't ever happen
445 throw new RuntimeException(e);
446 }
447 }
448
449 /**
450 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700451 * For use by internal activities. Returns the list of accounts that the calling package
452 * is authorized to use, particularly for shared accounts.
453 * @param packageName package name of the calling app.
454 * @param uid the uid of the calling app.
455 * @return the accounts that are available to this package and user.
456 */
457 public Account[] getAccountsForPackage(String packageName, int uid) {
458 try {
459 return mService.getAccountsForPackage(packageName, uid);
460 } catch (RemoteException re) {
461 // possible security exception
462 throw new RuntimeException(re);
463 }
464 }
465
466 /**
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700467 * Returns the accounts visible to the specified package, in an environment where some apps
468 * are not authorized to view all accounts. This method can only be called by system apps.
469 * @param type The type of accounts to return, null to retrieve all accounts
470 * @param packageName The package name of the app for which the accounts are to be returned
471 * @return An array of {@link Account}, one per matching account. Empty
472 * (never null) if no accounts of the specified type have been added.
473 */
474 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
475 try {
476 return mService.getAccountsByTypeForPackage(type, packageName);
477 } catch (RemoteException re) {
478 // possible security exception
479 throw new RuntimeException(re);
480 }
481 }
482
483 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800484 * Lists all accounts of a particular type. The account type is a
485 * string token corresponding to the authenticator and useful domain
486 * of the account. For example, there are types corresponding to Google
487 * and Facebook. The exact string token to use will be published somewhere
488 * associated with the authenticator in question.
489 *
490 * <p>It is safe to call this method from the main thread.
491 *
492 * <p>This method requires the caller to hold the permission
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700493 * {@link android.Manifest.permission#GET_ACCOUNTS} or share a uid with the
494 * authenticator that owns the account type.
Dan Egnor661f0132010-02-19 11:23:00 -0800495 *
496 * @param type The type of accounts to return, null to retrieve all accounts
497 * @return An array of {@link Account}, one per matching account. Empty
498 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700499 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700500 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700501 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800502 return getAccountsByTypeAsUser(type, Process.myUserHandle());
503 }
504
505 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
506 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700507 try {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800508 return mService.getAccountsAsUser(type, userHandle.getIdentifier());
Fred Quintana60307342009-03-24 22:48:12 -0700509 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700510 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700511 throw new RuntimeException(e);
512 }
513 }
514
Fred Quintana756b7352009-10-21 13:43:10 -0700515 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700516 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
517 * for an account.
518 * <p>
519 * This is only meant to be used by system activities and is not in the SDK.
520 * @param account The account whose permissions are being modified
521 * @param authTokenType The type of token whose permissions are being modified
522 * @param uid The uid that identifies the app which is being granted or revoked permission.
523 * @param value true is permission is being granted, false for revoked
524 * @hide
525 */
526 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
527 try {
528 mService.updateAppPermission(account, authTokenType, uid, value);
529 } catch (RemoteException e) {
530 // won't ever happen
531 throw new RuntimeException(e);
532 }
533 }
534
535 /**
536 * Get the user-friendly label associated with an authenticator's auth token.
537 * @param accountType the type of the authenticator. must not be null.
538 * @param authTokenType the token type. must not be null.
539 * @param callback callback to invoke when the result is available. may be null.
540 * @param handler the handler on which to invoke the callback, or null for the main thread
541 * @return a future containing the label string
542 * @hide
543 */
544 public AccountManagerFuture<String> getAuthTokenLabel(
545 final String accountType, final String authTokenType,
546 AccountManagerCallback<String> callback, Handler handler) {
547 if (accountType == null) throw new IllegalArgumentException("accountType is null");
548 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
549 return new Future2Task<String>(handler, callback) {
550 public void doWork() throws RemoteException {
551 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
552 }
553
554 @Override
555 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
556 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
557 throw new AuthenticatorException("no result in response");
558 }
559 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
560 }
561 }.start();
562 }
563
564 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800565 * Finds out whether a particular account has all the specified features.
566 * Account features are authenticator-specific string tokens identifying
567 * boolean account properties. For example, features are used to tell
568 * whether Google accounts have a particular service (such as Google
569 * Calendar or Google Talk) enabled. The feature names and their meanings
570 * are published somewhere associated with the authenticator in question.
571 *
572 * <p>This method may be called from any thread, but the returned
573 * {@link AccountManagerFuture} must not be used on the main thread.
574 *
575 * <p>This method requires the caller to hold the permission
576 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800577 *
578 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800579 * @param features An array of the account features to check
580 * @param callback Callback to invoke when the request completes,
581 * null for no callback
582 * @param handler {@link Handler} identifying the callback thread,
583 * null for the main thread
584 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
585 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800586 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700587 @RequiresPermission(GET_ACCOUNTS)
Fred Quintana3084a6f2010-01-14 18:02:03 -0800588 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800589 final String[] features,
590 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700591 if (account == null) throw new IllegalArgumentException("account is null");
592 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800593 return new Future2Task<Boolean>(handler, callback) {
594 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800595 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800596 }
597 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
598 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
599 throw new AuthenticatorException("no result in response");
600 }
601 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
602 }
603 }.start();
604 }
605
606 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800607 * Lists all accounts of a type which have certain features. The account
608 * type identifies the authenticator (see {@link #getAccountsByType}).
609 * Account features are authenticator-specific string tokens identifying
610 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700611 *
Dan Egnor661f0132010-02-19 11:23:00 -0800612 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
613 * which may contact the server or do other work to check account features,
614 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700615 *
Dan Egnor661f0132010-02-19 11:23:00 -0800616 * <p>This method may be called from any thread, but the returned
617 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700618 *
Dan Egnor661f0132010-02-19 11:23:00 -0800619 * <p>This method requires the caller to hold the permission
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700620 * {@link android.Manifest.permission#GET_ACCOUNTS} or share a uid with the
621 * authenticator that owns the account type.
Fred Quintana756b7352009-10-21 13:43:10 -0700622 *
Dan Egnor661f0132010-02-19 11:23:00 -0800623 * @param type The type of accounts to return, must not be null
624 * @param features An array of the account features to require,
625 * may be null or empty
626 * @param callback Callback to invoke when the request completes,
627 * null for no callback
628 * @param handler {@link Handler} identifying the callback thread,
629 * null for the main thread
630 * @return An {@link AccountManagerFuture} which resolves to an array of
631 * {@link Account}, one per account of the specified type which
632 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800633 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700634 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700635 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
636 final String type, final String[] features,
637 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700638 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700639 return new Future2Task<Account[]>(handler, callback) {
640 public void doWork() throws RemoteException {
641 mService.getAccountsByFeatures(mResponse, type, features);
642 }
643 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700644 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700645 throw new AuthenticatorException("no result in response");
646 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700647 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700648 Account[] descs = new Account[parcelables.length];
649 for (int i = 0; i < parcelables.length; i++) {
650 descs[i] = (Account) parcelables[i];
651 }
652 return descs;
653 }
654 }.start();
655 }
656
Fred Quintana756b7352009-10-21 13:43:10 -0700657 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700658 * Adds an account directly to the AccountManager. Normally used by sign-up
Dan Egnor661f0132010-02-19 11:23:00 -0800659 * wizards associated with authenticators, not directly by applications.
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700660 * <p>Calling this method does not update the last authenticated timestamp,
661 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
662 * {@link #notifyAccountAuthenticated(Account)} after getting success.
663 * However, if this method is called when it is triggered by addAccount() or
664 * addAccountAsUser() or similar functions, then there is no need to update
665 * timestamp manually as it is updated automatically by framework on
666 * successful completion of the mentioned functions.
Dan Egnor661f0132010-02-19 11:23:00 -0800667 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700668 * <p>This method requires the caller to have a signature match with the
669 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800670 *
671 * @param account The {@link Account} to add
672 * @param password The password to associate with the account, null for none
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700673 * @param userdata String values to use for the account's userdata, null for
674 * none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700675 * @return True if the account was successfully added, false if the account
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700676 * already exists, the account is null, or another error occurs.
Dan Egnor661f0132010-02-19 11:23:00 -0800677 */
678 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700679 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800680 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700681 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800682 } catch (RemoteException e) {
683 // won't ever happen
684 throw new RuntimeException(e);
685 }
686 }
687
688 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700689 * Notifies the system that the account has just been authenticated. This
690 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800691 * should be called only when the user has entered correct credentials for
692 * the account.
693 * <p>
694 * It is not safe to call this method from the main thread. As such, call it
695 * from another thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700696 * <p>This method requires the caller to have a signature match with the
697 * authenticator that owns the specified account.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800698 *
699 * @param account The {@link Account} to be updated.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700700 * @return boolean {@code true} if the authentication of the account has been successfully
701 * acknowledged. Otherwise {@code false}.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800702 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700703 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800704 if (account == null)
705 throw new IllegalArgumentException("account is null");
706 try {
707 return mService.accountAuthenticated(account);
708 } catch (RemoteException e) {
709 throw new RuntimeException(e);
710 }
711 }
712
713 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700714 * Rename the specified {@link Account}. This is equivalent to removing
715 * the existing account and adding a new renamed account with the old
716 * account's user data.
717 *
718 * <p>It is safe to call this method from the main thread.
719 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700720 * <p>This method requires the caller to have a signature match with the
721 * authenticator that manages the specified account.
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700722 *
723 * @param account The {@link Account} to rename
724 * @param newName String name to be associated with the account.
725 * @param callback Callback to invoke when the request completes, null for
726 * no callback
727 * @param handler {@link Handler} identifying the callback thread, null for
728 * the main thread
729 * @return An {@link AccountManagerFuture} which resolves to the Account
730 * after the name change. If successful the account's name will be the
731 * specified new name.
732 */
733 public AccountManagerFuture<Account> renameAccount(
734 final Account account,
Tor Norbye80b530a2015-04-23 16:36:09 -0700735 @Size(min = 1) final String newName,
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700736 AccountManagerCallback<Account> callback,
737 Handler handler) {
738 if (account == null) throw new IllegalArgumentException("account is null.");
739 if (TextUtils.isEmpty(newName)) {
740 throw new IllegalArgumentException("newName is empty or null.");
741 }
742 return new Future2Task<Account>(handler, callback) {
743 @Override
744 public void doWork() throws RemoteException {
745 mService.renameAccount(mResponse, account, newName);
746 }
747 @Override
748 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
749 String name = bundle.getString(KEY_ACCOUNT_NAME);
750 String type = bundle.getString(KEY_ACCOUNT_TYPE);
751 return new Account(name, type);
752 }
753 }.start();
754 }
755
756 /**
757 * Gets the previous name associated with the account or {@code null}, if
758 * none. This is intended so that clients of {@link
759 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
760 * authenticator has renamed an account.
761 *
762 * <p>It is safe to call this method from the main thread.
763 *
764 * @param account The account to query for a previous name.
765 * @return The account's previous name, null if the account has never been
766 * renamed.
767 */
768 public String getPreviousName(final Account account) {
769 if (account == null) throw new IllegalArgumentException("account is null");
770 try {
771 return mService.getPreviousName(account);
772 } catch (RemoteException e) {
773 // will never happen
774 throw new RuntimeException(e);
775 }
776 }
777
778 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800779 * Removes an account from the AccountManager. Does nothing if the account
780 * does not exist. Does not delete the account from the server.
781 * The authenticator may have its own policies preventing account
782 * deletion, in which case the account will not be deleted.
783 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700784 * <p>This method requires the caller to have a signature match with the
785 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800786 *
787 * @param account The {@link Account} to remove
788 * @param callback Callback to invoke when the request completes,
789 * null for no callback
790 * @param handler {@link Handler} identifying the callback thread,
791 * null for the main thread
792 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100793 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800794 * @deprecated use
795 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
796 * instead
Dan Egnor661f0132010-02-19 11:23:00 -0800797 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800798 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800799 public AccountManagerFuture<Boolean> removeAccount(final Account account,
800 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700801 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800802 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700803 @Override
Dan Egnor661f0132010-02-19 11:23:00 -0800804 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800805 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -0800806 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700807 @Override
Dan Egnor661f0132010-02-19 11:23:00 -0800808 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
809 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
810 throw new AuthenticatorException("no result in response");
811 }
812 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
813 }
814 }.start();
815 }
816
817 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800818 * Removes an account from the AccountManager. Does nothing if the account
819 * does not exist. Does not delete the account from the server.
820 * The authenticator may have its own policies preventing account
821 * deletion, in which case the account will not be deleted.
822 *
823 * <p>This method may be called from any thread, but the returned
824 * {@link AccountManagerFuture} must not be used on the main thread.
825 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700826 * <p>This method requires the caller to have a signature match with the
827 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800828 *
829 * @param account The {@link Account} to remove
830 * @param activity The {@link Activity} context to use for launching a new
831 * authenticator-defined sub-Activity to prompt the user to delete an
832 * account; used only to call startActivity(); if null, the prompt
833 * will not be launched directly, but the {@link Intent} may be
834 * returned to the caller instead
835 * @param callback Callback to invoke when the request completes,
836 * null for no callback
837 * @param handler {@link Handler} identifying the callback thread,
838 * null for the main thread
839 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
840 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
841 * was removed or if active. If no activity was specified, the returned
842 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
843 * needed to launch the actual account removal process, if authenticator
844 * needs the activity launch. If an error occurred,
845 * {@link AccountManagerFuture#getResult()} throws:
846 * <ul>
847 * <li> {@link AuthenticatorException} if no authenticator was registered for
848 * this account type or the authenticator failed to respond
849 * <li> {@link OperationCanceledException} if the operation was canceled for
850 * any reason, including the user canceling the creation process or
851 * adding accounts (of this type) has been disabled by policy
852 * </ul>
853 */
854 public AccountManagerFuture<Bundle> removeAccount(final Account account,
855 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
856 if (account == null) throw new IllegalArgumentException("account is null");
857 return new AmsTask(activity, handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700858 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800859 public void doWork() throws RemoteException {
860 mService.removeAccount(mResponse, account, activity != null);
861 }
862 }.start();
863 }
864
865 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100866 * @see #removeAccount(Account, AccountManagerCallback, Handler)
867 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800868 * @deprecated use
869 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
870 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100871 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800872 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100873 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
874 AccountManagerCallback<Boolean> callback, Handler handler,
875 final UserHandle userHandle) {
876 if (account == null) throw new IllegalArgumentException("account is null");
877 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
878 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700879 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100880 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800881 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100882 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700883 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100884 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
885 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
886 throw new AuthenticatorException("no result in response");
887 }
888 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
889 }
890 }.start();
891 }
892
893 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800894 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
895 * @hide
896 */
897 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
898 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
899 final UserHandle userHandle) {
900 if (account == null)
901 throw new IllegalArgumentException("account is null");
902 if (userHandle == null)
903 throw new IllegalArgumentException("userHandle is null");
904 return new AmsTask(activity, handler, callback) {
905 public void doWork() throws RemoteException {
906 mService.removeAccountAsUser(mResponse, account, activity != null,
907 userHandle.getIdentifier());
908 }
909 }.start();
910 }
911
912 /**
913 * Removes an account directly. Normally used by authenticators, not
914 * directly by applications. Does not delete the account from the server.
915 * The authenticator may have its own policies preventing account deletion,
916 * in which case the account will not be deleted.
917 * <p>
918 * It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700919 * <p>This method requires the caller to have a signature match with the
920 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800921 *
922 * @param account The {@link Account} to delete.
923 * @return True if the account was successfully deleted, false if the
924 * account did not exist, the account is null, or another error
925 * occurs.
926 */
927 public boolean removeAccountExplicitly(Account account) {
928 if (account == null) throw new IllegalArgumentException("account is null");
929 try {
930 return mService.removeAccountExplicitly(account);
931 } catch (RemoteException e) {
932 // won't ever happen
933 throw new RuntimeException(e);
934 }
935 }
936
937 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800938 * Removes an auth token from the AccountManager's cache. Does nothing if
939 * the auth token is not currently in the cache. Applications must call this
940 * method when the auth token is found to have expired or otherwise become
941 * invalid for authenticating requests. The AccountManager does not validate
942 * or expire cached auth tokens otherwise.
943 *
944 * <p>It is safe to call this method from the main thread.
945 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700946 * @param accountType The account type of the auth token to invalidate, must not be null
947 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800948 */
949 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700950 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800951 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700952 if (authToken != null) {
953 mService.invalidateAuthToken(accountType, authToken);
954 }
Dan Egnor661f0132010-02-19 11:23:00 -0800955 } catch (RemoteException e) {
956 // won't ever happen
957 throw new RuntimeException(e);
958 }
959 }
960
961 /**
962 * Gets an auth token from the AccountManager's cache. If no auth
963 * token is cached for this account, null will be returned -- a new
964 * auth token will not be generated, and the server will not be contacted.
965 * Intended for use by the authenticator, not directly by applications.
966 *
967 * <p>It is safe to call this method from the main thread.
968 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700969 * <p>This method requires the caller to have a signature match with the
970 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800971 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700972 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
973 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800974 * @return The cached auth token for this account and type, or null if
975 * no auth token is cached or the account does not exist.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700976 * @see #getAuthToken
Dan Egnor661f0132010-02-19 11:23:00 -0800977 */
978 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700979 if (account == null) throw new IllegalArgumentException("account is null");
980 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800981 try {
982 return mService.peekAuthToken(account, authTokenType);
983 } catch (RemoteException e) {
984 // won't ever happen
985 throw new RuntimeException(e);
986 }
987 }
988
989 /**
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -0700990 * Sets or forgets a saved password. This modifies the local copy of the
991 * password used to automatically authenticate the user; it does not change
992 * the user's account password on the server. Intended for use by the
993 * authenticator, not directly by applications.
994 * <p>Calling this method does not update the last authenticated timestamp,
995 * referred by {@link #KEY_LAST_AUTHENTICATED_TIME}. To update it, call
996 * {@link #notifyAccountAuthenticated(Account)} after getting success.
Dan Egnor661f0132010-02-19 11:23:00 -0800997 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700998 * <p>This method requires the caller to have a signature match with the
999 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001000 *
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07001001 * @param account The account whose password is to be set. Cannot be
1002 * {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -08001003 * @param password The password to set, null to clear the password
1004 */
1005 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -07001006 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001007 try {
1008 mService.setPassword(account, password);
1009 } catch (RemoteException e) {
1010 // won't ever happen
1011 throw new RuntimeException(e);
1012 }
1013 }
1014
1015 /**
1016 * Forgets a saved password. This erases the local copy of the password;
1017 * it does not change the user's account password on the server.
1018 * Has the same effect as setPassword(account, null) but requires fewer
1019 * permissions, and may be used by applications or management interfaces
1020 * to "sign out" from an account.
1021 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001022 * <p>This method only successfully clear the account's password when the
1023 * caller has the same signature as the authenticator that owns the
1024 * specified account. Otherwise, this method will silently fail.
Dan Egnor661f0132010-02-19 11:23:00 -08001025 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001026 * <p>It is safe to call this method from the main thread.
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001027 *
Dan Egnor661f0132010-02-19 11:23:00 -08001028 * @param account The account whose password to clear
1029 */
1030 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001031 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001032 try {
1033 mService.clearPassword(account);
1034 } catch (RemoteException e) {
1035 // won't ever happen
1036 throw new RuntimeException(e);
1037 }
1038 }
1039
1040 /**
1041 * Sets one userdata key for an account. Intended by use for the
1042 * authenticator to stash state for itself, not directly by applications.
1043 * The meaning of the keys and values is up to the authenticator.
1044 *
1045 * <p>It is safe to call this method from the main thread.
1046 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001047 * <p>This method requires the caller to have a signature match with the
1048 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001049 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001050 * @param account Account whose user data is to be set. Must not be {@code null}.
1051 * @param key String user data key to set. Must not be null
1052 * @param value String value to set, {@code null} to clear this user data key
Dan Egnor661f0132010-02-19 11:23:00 -08001053 */
1054 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001055 if (account == null) throw new IllegalArgumentException("account is null");
1056 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001057 try {
1058 mService.setUserData(account, key, value);
1059 } catch (RemoteException e) {
1060 // won't ever happen
1061 throw new RuntimeException(e);
1062 }
1063 }
1064
1065 /**
1066 * Adds an auth token to the AccountManager cache for an account.
1067 * If the account does not exist then this call has no effect.
1068 * Replaces any previous auth token for this account and auth token type.
1069 * Intended for use by the authenticator, not directly by applications.
1070 *
1071 * <p>It is safe to call this method from the main thread.
1072 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001073 * <p>This method requires the caller to have a signature match with the
1074 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001075 *
1076 * @param account The account to set an auth token for
1077 * @param authTokenType The type of the auth token, see {#getAuthToken}
1078 * @param authToken The auth token to add to the cache
1079 */
1080 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001081 if (account == null) throw new IllegalArgumentException("account is null");
1082 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001083 try {
1084 mService.setAuthToken(account, authTokenType, authToken);
1085 } catch (RemoteException e) {
1086 // won't ever happen
1087 throw new RuntimeException(e);
1088 }
1089 }
1090
1091 /**
1092 * This convenience helper synchronously gets an auth token with
1093 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1094 *
1095 * <p>This method may block while a network request completes, and must
1096 * never be made from the main thread.
1097 *
Dan Egnor661f0132010-02-19 11:23:00 -08001098 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001099 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001100 * @param notifyAuthFailure If true, display a notification and return null
1101 * if authentication fails; if false, prompt and wait for the user to
1102 * re-enter correct credentials before returning
1103 * @return An auth token of the specified type for this account, or null
1104 * if authentication fails or none can be fetched.
1105 * @throws AuthenticatorException if the authenticator failed to respond
1106 * @throws OperationCanceledException if the request was canceled for any
1107 * reason, including the user canceling a credential request
1108 * @throws java.io.IOException if the authenticator experienced an I/O problem
1109 * creating a new auth token, usually because of network trouble
1110 */
1111 public String blockingGetAuthToken(Account account, String authTokenType,
1112 boolean notifyAuthFailure)
1113 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001114 if (account == null) throw new IllegalArgumentException("account is null");
1115 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001116 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1117 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001118 if (bundle == null) {
1119 // This should never happen, but it does, occasionally. If it does return null to
1120 // signify that we were not able to get the authtoken.
1121 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1122 // returned
1123 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1124 + account + ", authTokenType " + authTokenType);
1125 return null;
1126 }
Dan Egnor661f0132010-02-19 11:23:00 -08001127 return bundle.getString(KEY_AUTHTOKEN);
1128 }
1129
1130 /**
1131 * Gets an auth token of the specified type for a particular account,
1132 * prompting the user for credentials if necessary. This method is
1133 * intended for applications running in the foreground where it makes
1134 * sense to ask the user directly for a password.
1135 *
1136 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001137 * type, then it is returned. Otherwise, if a saved password is
1138 * available, it is sent to the server to generate a new auth token.
1139 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001140 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001141 * <p>Some authenticators have auth token <em>types</em>, whose value
1142 * is authenticator-dependent. Some services use different token types to
1143 * access different functionality -- for example, Google uses different auth
1144 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001145 *
1146 * <p>This method may be called from any thread, but the returned
1147 * {@link AccountManagerFuture} must not be used on the main thread.
1148 *
Dan Egnor661f0132010-02-19 11:23:00 -08001149 * @param account The account to fetch an auth token for
1150 * @param authTokenType The auth token type, an authenticator-dependent
1151 * string token, must not be null
1152 * @param options Authenticator-specific options for the request,
1153 * may be null or empty
1154 * @param activity The {@link Activity} context to use for launching a new
1155 * authenticator-defined sub-Activity to prompt the user for a password
1156 * if necessary; used only to call startActivity(); must not be null.
1157 * @param callback Callback to invoke when the request completes,
1158 * null for no callback
1159 * @param handler {@link Handler} identifying the callback thread,
1160 * null for the main thread
1161 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1162 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001163 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001164 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1165 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1166 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001167 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001168 *
1169 * (Other authenticator-specific values may be returned.) If an auth token
1170 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1171 * <ul>
1172 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1173 * <li> {@link OperationCanceledException} if the operation is canceled for
1174 * any reason, incluidng the user canceling a credential request
1175 * <li> {@link IOException} if the authenticator experienced an I/O problem
1176 * creating a new auth token, usually because of network trouble
1177 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001178 * If the account is no longer present on the device, the return value is
1179 * authenticator-dependent. The caller should verify the validity of the
1180 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001181 */
1182 public AccountManagerFuture<Bundle> getAuthToken(
1183 final Account account, final String authTokenType, final Bundle options,
1184 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001185 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001186 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001187 final Bundle optionsIn = new Bundle();
1188 if (options != null) {
1189 optionsIn.putAll(options);
1190 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001191 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001192 return new AmsTask(activity, handler, callback) {
1193 public void doWork() throws RemoteException {
1194 mService.getAuthToken(mResponse, account, authTokenType,
1195 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001196 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001197 }
1198 }.start();
1199 }
1200
1201 /**
1202 * Gets an auth token of the specified type for a particular account,
1203 * optionally raising a notification if the user must enter credentials.
1204 * This method is intended for background tasks and services where the
1205 * user should not be immediately interrupted with a password prompt.
1206 *
1207 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001208 * type, then it is returned. Otherwise, if a saved password is
1209 * available, it is sent to the server to generate a new auth token.
1210 * Otherwise, an {@link Intent} is returned which, when started, will
1211 * prompt the user for a password. If the notifyAuthFailure parameter is
1212 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001213 * alerting the user that they need to enter a password at some point.
1214 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001215 * <p>In that case, you may need to wait until the user responds, which
1216 * could take hours or days or forever. When the user does respond and
1217 * supply a new password, the account manager will broadcast the
1218 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1219 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001220 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001221 * <p>If notifyAuthFailure is not set, it is the application's
1222 * responsibility to launch the returned Intent at some point.
1223 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001224 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001225 * <p>Some authenticators have auth token <em>types</em>, whose value
1226 * is authenticator-dependent. Some services use different token types to
1227 * access different functionality -- for example, Google uses different auth
1228 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001229 *
1230 * <p>This method may be called from any thread, but the returned
1231 * {@link AccountManagerFuture} must not be used on the main thread.
1232 *
Dan Egnor661f0132010-02-19 11:23:00 -08001233 * @param account The account to fetch an auth token for
1234 * @param authTokenType The auth token type, an authenticator-dependent
1235 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001236 * @param notifyAuthFailure True to add a notification to prompt the
1237 * user for a password if necessary, false to leave that to the caller
1238 * @param callback Callback to invoke when the request completes,
1239 * null for no callback
1240 * @param handler {@link Handler} identifying the callback thread,
1241 * null for the main thread
1242 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1243 * at least the following fields on success:
1244 * <ul>
1245 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1246 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1247 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1248 * </ul>
1249 *
1250 * (Other authenticator-specific values may be returned.) If the user
1251 * must enter credentials, the returned Bundle contains only
1252 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1253 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001254 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001255 * <ul>
1256 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1257 * <li> {@link OperationCanceledException} if the operation is canceled for
1258 * any reason, incluidng the user canceling a credential request
1259 * <li> {@link IOException} if the authenticator experienced an I/O problem
1260 * creating a new auth token, usually because of network trouble
1261 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001262 * If the account is no longer present on the device, the return value is
1263 * authenticator-dependent. The caller should verify the validity of the
1264 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001265 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1266 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001267 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001268 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001269 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001270 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001271 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001272 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001273 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001274 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001275 }
1276
1277 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001278 * Gets an auth token of the specified type for a particular account,
1279 * optionally raising a notification if the user must enter credentials.
1280 * This method is intended for background tasks and services where the
1281 * user should not be immediately interrupted with a password prompt.
1282 *
1283 * <p>If a previously generated auth token is cached for this account and
1284 * type, then it is returned. Otherwise, if a saved password is
1285 * available, it is sent to the server to generate a new auth token.
1286 * Otherwise, an {@link Intent} is returned which, when started, will
1287 * prompt the user for a password. If the notifyAuthFailure parameter is
1288 * set, a status bar notification is also created with the same Intent,
1289 * alerting the user that they need to enter a password at some point.
1290 *
1291 * <p>In that case, you may need to wait until the user responds, which
1292 * could take hours or days or forever. When the user does respond and
1293 * supply a new password, the account manager will broadcast the
1294 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1295 * use to try again.
1296 *
1297 * <p>If notifyAuthFailure is not set, it is the application's
1298 * responsibility to launch the returned Intent at some point.
1299 * Either way, the result from this call will not wait for user action.
1300 *
1301 * <p>Some authenticators have auth token <em>types</em>, whose value
1302 * is authenticator-dependent. Some services use different token types to
1303 * access different functionality -- for example, Google uses different auth
1304 * tokens to access Gmail and Google Calendar for the same account.
1305 *
1306 * <p>This method may be called from any thread, but the returned
1307 * {@link AccountManagerFuture} must not be used on the main thread.
1308 *
Fred Quintanaad93a322011-09-08 13:21:01 -07001309 * @param account The account to fetch an auth token for
1310 * @param authTokenType The auth token type, an authenticator-dependent
1311 * string token, must not be null
1312 * @param options Authenticator-specific options for the request,
1313 * may be null or empty
1314 * @param notifyAuthFailure True to add a notification to prompt the
1315 * user for a password if necessary, false to leave that to the caller
1316 * @param callback Callback to invoke when the request completes,
1317 * null for no callback
1318 * @param handler {@link Handler} identifying the callback thread,
1319 * null for the main thread
1320 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1321 * at least the following fields on success:
1322 * <ul>
1323 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1324 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1325 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1326 * </ul>
1327 *
1328 * (Other authenticator-specific values may be returned.) If the user
1329 * must enter credentials, the returned Bundle contains only
1330 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1331 *
1332 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1333 * <ul>
1334 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1335 * <li> {@link OperationCanceledException} if the operation is canceled for
1336 * any reason, incluidng the user canceling a credential request
1337 * <li> {@link IOException} if the authenticator experienced an I/O problem
1338 * creating a new auth token, usually because of network trouble
1339 * </ul>
1340 * If the account is no longer present on the device, the return value is
1341 * authenticator-dependent. The caller should verify the validity of the
1342 * account before requesting an auth token.
1343 */
1344 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001345 final Account account, final String authTokenType, final Bundle options,
1346 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001347 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001348
Fred Quintanaad93a322011-09-08 13:21:01 -07001349 if (account == null) throw new IllegalArgumentException("account is null");
1350 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001351 final Bundle optionsIn = new Bundle();
1352 if (options != null) {
1353 optionsIn.putAll(options);
1354 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001355 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001356 return new AmsTask(null, handler, callback) {
1357 public void doWork() throws RemoteException {
1358 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001359 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001360 }
1361 }.start();
1362 }
1363
1364 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001365 * Asks the user to add an account of a specified type. The authenticator
1366 * for this account type processes this request with the appropriate user
1367 * interface. If the user does elect to create a new account, the account
1368 * name is returned.
1369 *
1370 * <p>This method may be called from any thread, but the returned
1371 * {@link AccountManagerFuture} must not be used on the main thread.
1372 *
Dan Egnor661f0132010-02-19 11:23:00 -08001373 * @param accountType The type of account to add; must not be null
1374 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1375 * this account will need to be able to generate, null for none
1376 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1377 * account must have, null for none
1378 * @param addAccountOptions Authenticator-specific options for the request,
1379 * may be null or empty
1380 * @param activity The {@link Activity} context to use for launching a new
1381 * authenticator-defined sub-Activity to prompt the user to create an
1382 * account; used only to call startActivity(); if null, the prompt
1383 * will not be launched directly, but the necessary {@link Intent}
1384 * will be returned to the caller instead
1385 * @param callback Callback to invoke when the request completes,
1386 * null for no callback
1387 * @param handler {@link Handler} identifying the callback thread,
1388 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001389 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001390 * these fields if activity was specified and an account was created:
1391 * <ul>
1392 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1393 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1394 * </ul>
1395 *
1396 * If no activity was specified, the returned Bundle contains only
1397 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001398 * actual account creation process. If an error occurred,
1399 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001400 * <ul>
1401 * <li> {@link AuthenticatorException} if no authenticator was registered for
1402 * this account type or the authenticator failed to respond
1403 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001404 * any reason, including the user canceling the creation process or adding accounts
1405 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001406 * <li> {@link IOException} if the authenticator experienced an I/O problem
1407 * creating a new account, usually because of network trouble
1408 * </ul>
1409 */
1410 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1411 final String authTokenType, final String[] requiredFeatures,
1412 final Bundle addAccountOptions,
1413 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001414 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001415 final Bundle optionsIn = new Bundle();
1416 if (addAccountOptions != null) {
1417 optionsIn.putAll(addAccountOptions);
1418 }
1419 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001420
Dan Egnor661f0132010-02-19 11:23:00 -08001421 return new AmsTask(activity, handler, callback) {
1422 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001423 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001424 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001425 }
1426 }.start();
1427 }
1428
1429 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001430 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1431 * @hide
1432 */
1433 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1434 final String authTokenType, final String[] requiredFeatures,
1435 final Bundle addAccountOptions, final Activity activity,
1436 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1437 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1438 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1439 final Bundle optionsIn = new Bundle();
1440 if (addAccountOptions != null) {
1441 optionsIn.putAll(addAccountOptions);
1442 }
1443 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1444
1445 return new AmsTask(activity, handler, callback) {
1446 public void doWork() throws RemoteException {
1447 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1448 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1449 }
1450 }.start();
1451 }
1452
1453 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001454 * Adds a shared account from the primary user to a secondary user. Adding the shared account
1455 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1456 * are attempted to be copied to the target user from the primary via calls to the
1457 * authenticator.
1458 * @param account the account to share
1459 * @param user the target user
1460 * @return
1461 * @hide
1462 */
1463 public boolean addSharedAccount(final Account account, UserHandle user) {
1464 try {
1465 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1466 return val;
1467 } catch (RemoteException re) {
1468 // won't ever happen
1469 throw new RuntimeException(re);
1470 }
1471 }
1472
1473 /**
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001474 * Copies an account from the primary user to another user.
1475 * @param account the account to copy
1476 * @param user the target user
1477 * @param callback Callback to invoke when the request completes,
1478 * null for no callback
1479 * @param handler {@link Handler} identifying the callback thread,
1480 * null for the main thread
1481 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1482 * succeeded.
1483 * @hide
1484 */
1485 public AccountManagerFuture<Boolean> copyAccountToUser(
1486 final Account account, final UserHandle user,
1487 AccountManagerCallback<Boolean> callback, Handler handler) {
1488 if (account == null) throw new IllegalArgumentException("account is null");
1489 if (user == null) throw new IllegalArgumentException("user is null");
1490
1491 return new Future2Task<Boolean>(handler, callback) {
1492 @Override
1493 public void doWork() throws RemoteException {
1494 mService.copyAccountToUser(
1495 mResponse, account, UserHandle.USER_OWNER, user.getIdentifier());
1496 }
1497 @Override
1498 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1499 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1500 throw new AuthenticatorException("no result in response");
1501 }
1502 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1503 }
1504 }.start();
1505 }
1506
1507 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001508 * @hide
1509 * Removes the shared account.
1510 * @param account the account to remove
1511 * @param user the user to remove the account from
1512 * @return
1513 */
1514 public boolean removeSharedAccount(final Account account, UserHandle user) {
1515 try {
1516 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1517 return val;
1518 } catch (RemoteException re) {
1519 // won't ever happen
1520 throw new RuntimeException(re);
1521 }
1522 }
1523
1524 /**
1525 * @hide
1526 * @param user
1527 * @return
1528 */
1529 public Account[] getSharedAccounts(UserHandle user) {
1530 try {
1531 return mService.getSharedAccountsAsUser(user.getIdentifier());
1532 } catch (RemoteException re) {
1533 // won't ever happen
1534 throw new RuntimeException(re);
1535 }
1536 }
1537
1538 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001539 * Confirms that the user knows the password for an account to make extra
1540 * sure they are the owner of the account. The user-entered password can
1541 * be supplied directly, otherwise the authenticator for this account type
1542 * prompts the user with the appropriate interface. This method is
1543 * intended for applications which want extra assurance; for example, the
1544 * phone lock screen uses this to let the user unlock the phone with an
1545 * account password if they forget the lock pattern.
1546 *
1547 * <p>If the user-entered password matches a saved password for this
1548 * account, the request is considered valid; otherwise the authenticator
1549 * verifies the password (usually by contacting the server).
1550 *
1551 * <p>This method may be called from any thread, but the returned
1552 * {@link AccountManagerFuture} must not be used on the main thread.
1553 *
Dan Egnor661f0132010-02-19 11:23:00 -08001554 * @param account The account to confirm password knowledge for
1555 * @param options Authenticator-specific options for the request;
1556 * if the {@link #KEY_PASSWORD} string field is present, the
1557 * authenticator may use it directly rather than prompting the user;
1558 * may be null or empty
1559 * @param activity The {@link Activity} context to use for launching a new
1560 * authenticator-defined sub-Activity to prompt the user to enter a
1561 * password; used only to call startActivity(); if null, the prompt
1562 * will not be launched directly, but the necessary {@link Intent}
1563 * will be returned to the caller instead
1564 * @param callback Callback to invoke when the request completes,
1565 * null for no callback
1566 * @param handler {@link Handler} identifying the callback thread,
1567 * null for the main thread
1568 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1569 * with these fields if activity or password was supplied and
1570 * the account was successfully verified:
1571 * <ul>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001572 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001573 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1574 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1575 * </ul>
1576 *
1577 * If no activity or password was specified, the returned Bundle contains
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001578 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1579 * password prompt.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001580 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001581 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001582 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001583 * credential was validated/created.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001584 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001585 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001586 * <ul>
1587 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1588 * <li> {@link OperationCanceledException} if the operation was canceled for
1589 * any reason, including the user canceling the password prompt
1590 * <li> {@link IOException} if the authenticator experienced an I/O problem
1591 * verifying the password, usually because of network trouble
1592 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001593 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001594 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1595 final Bundle options,
1596 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001597 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001598 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001599 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1600 Process.myUserHandle());
1601 }
1602
1603 /**
1604 * @hide
1605 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1606 * but for the specified user.
1607 */
1608 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1609 final Bundle options,
1610 final Activity activity,
1611 final AccountManagerCallback<Bundle> callback,
1612 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001613 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001614 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001615 return new AmsTask(activity, handler, callback) {
1616 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001617 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1618 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001619 }
Fred Quintana33269202009-04-20 16:05:10 -07001620 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001621 }
1622
Fred Quintana756b7352009-10-21 13:43:10 -07001623 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001624 * Asks the user to enter a new password for an account, updating the
1625 * saved credentials for the account. Normally this happens automatically
1626 * when the server rejects credentials during an auth token fetch, but this
1627 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001628 *
Dan Egnor661f0132010-02-19 11:23:00 -08001629 * <p>This method may be called from any thread, but the returned
1630 * {@link AccountManagerFuture} must not be used on the main thread.
1631 *
Dan Egnor661f0132010-02-19 11:23:00 -08001632 * @param account The account to update credentials for
1633 * @param authTokenType The credentials entered must allow an auth token
1634 * of this type to be created (but no actual auth token is returned);
1635 * may be null
1636 * @param options Authenticator-specific options for the request;
1637 * may be null or empty
1638 * @param activity The {@link Activity} context to use for launching a new
1639 * authenticator-defined sub-Activity to prompt the user to enter a
1640 * password; used only to call startActivity(); if null, the prompt
1641 * will not be launched directly, but the necessary {@link Intent}
1642 * will be returned to the caller instead
1643 * @param callback Callback to invoke when the request completes,
1644 * null for no callback
1645 * @param handler {@link Handler} identifying the callback thread,
1646 * null for the main thread
1647 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1648 * with these fields if an activity was supplied and the account
1649 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001650 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001651 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1652 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001653 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001654 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001655 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08001656 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001657 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07001658 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001659 * <ul>
1660 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1661 * <li> {@link OperationCanceledException} if the operation was canceled for
1662 * any reason, including the user canceling the password prompt
1663 * <li> {@link IOException} if the authenticator experienced an I/O problem
1664 * verifying the password, usually because of network trouble
1665 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001666 */
1667 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1668 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001669 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001670 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001671 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001672 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001673 return new AmsTask(activity, handler, callback) {
1674 public void doWork() throws RemoteException {
1675 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001676 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001677 }
Fred Quintana33269202009-04-20 16:05:10 -07001678 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 }
1680
Fred Quintana756b7352009-10-21 13:43:10 -07001681 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001682 * Offers the user an opportunity to change an authenticator's settings.
1683 * These properties are for the authenticator in general, not a particular
1684 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001685 *
Dan Egnor661f0132010-02-19 11:23:00 -08001686 * <p>This method may be called from any thread, but the returned
1687 * {@link AccountManagerFuture} must not be used on the main thread.
1688 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001689 * <p>This method requires the caller to have the same signature as the
1690 * authenticator associated with the specified account type.
Dan Egnor661f0132010-02-19 11:23:00 -08001691 *
1692 * @param accountType The account type associated with the authenticator
1693 * to adjust
1694 * @param activity The {@link Activity} context to use for launching a new
1695 * authenticator-defined sub-Activity to adjust authenticator settings;
1696 * used only to call startActivity(); if null, the settings dialog will
1697 * not be launched directly, but the necessary {@link Intent} will be
1698 * returned to the caller instead
1699 * @param callback Callback to invoke when the request completes,
1700 * null for no callback
1701 * @param handler {@link Handler} identifying the callback thread,
1702 * null for the main thread
1703 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1704 * which is empty if properties were edited successfully, or
1705 * if no activity was specified, contains only {@link #KEY_INTENT}
1706 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001707 * If an error occurred, {@link AccountManagerFuture#getResult()}
1708 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001709 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001710 * <li> {@link AuthenticatorException} if no authenticator was registered for
1711 * this account type or the authenticator failed to respond
1712 * <li> {@link OperationCanceledException} if the operation was canceled for
1713 * any reason, including the user canceling the settings dialog
1714 * <li> {@link IOException} if the authenticator experienced an I/O problem
1715 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001716 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001717 */
1718 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1719 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001720 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001721 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001722 return new AmsTask(activity, handler, callback) {
1723 public void doWork() throws RemoteException {
1724 mService.editProperties(mResponse, accountType, activity != null);
1725 }
Fred Quintana33269202009-04-20 16:05:10 -07001726 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001727 }
1728
1729 private void ensureNotOnMainThread() {
1730 final Looper looper = Looper.myLooper();
1731 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001732 final IllegalStateException exception = new IllegalStateException(
1733 "calling this from your main thread can lead to deadlock");
1734 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1735 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001736 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1737 throw exception;
1738 }
Fred Quintana60307342009-03-24 22:48:12 -07001739 }
1740 }
1741
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001742 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1743 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001744 handler = handler == null ? mMainHandler : handler;
1745 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001746 public void run() {
1747 callback.run(future);
1748 }
1749 });
1750 }
Fred Quintana60307342009-03-24 22:48:12 -07001751
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001752 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001753 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001754 final Account[] accountsCopy = new Account[accounts.length];
1755 // send a copy to make sure that one doesn't
1756 // change what another sees
1757 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1758 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001759 handler.post(new Runnable() {
1760 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001761 try {
1762 listener.onAccountsUpdated(accountsCopy);
1763 } catch (SQLException e) {
1764 // Better luck next time. If the problem was disk-full,
1765 // the STORAGE_OK intent will re-trigger the update.
1766 Log.e(TAG, "Can't update accounts", e);
1767 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001768 }
1769 });
1770 }
1771
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001772 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001773 final IAccountManagerResponse mResponse;
1774 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001775 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001776 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001777 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001778 super(new Callable<Bundle>() {
1779 public Bundle call() throws Exception {
1780 throw new IllegalStateException("this should never be called");
1781 }
1782 });
1783
1784 mHandler = handler;
1785 mCallback = callback;
1786 mActivity = activity;
1787 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001788 }
1789
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001790 public final AccountManagerFuture<Bundle> start() {
1791 try {
1792 doWork();
1793 } catch (RemoteException e) {
1794 setException(e);
1795 }
Fred Quintana33269202009-04-20 16:05:10 -07001796 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001797 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001798
Fred Quintana96580e02010-03-04 13:42:42 -08001799 protected void set(Bundle bundle) {
1800 // TODO: somehow a null is being set as the result of the Future. Log this
1801 // case to help debug where this is occurring. When this bug is fixed this
1802 // condition statement should be removed.
1803 if (bundle == null) {
1804 Log.e(TAG, "the bundle must not be null", new Exception());
1805 }
1806 super.set(bundle);
1807 }
1808
Fred Quintanaa698f422009-04-08 19:14:54 -07001809 public abstract void doWork() throws RemoteException;
1810
1811 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1812 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001813 if (!isDone()) {
1814 ensureNotOnMainThread();
1815 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001816 try {
1817 if (timeout == null) {
1818 return get();
1819 } else {
1820 return get(timeout, unit);
1821 }
1822 } catch (CancellationException e) {
1823 throw new OperationCanceledException();
1824 } catch (TimeoutException e) {
1825 // fall through and cancel
1826 } catch (InterruptedException e) {
1827 // fall through and cancel
1828 } catch (ExecutionException e) {
1829 final Throwable cause = e.getCause();
1830 if (cause instanceof IOException) {
1831 throw (IOException) cause;
1832 } else if (cause instanceof UnsupportedOperationException) {
1833 throw new AuthenticatorException(cause);
1834 } else if (cause instanceof AuthenticatorException) {
1835 throw (AuthenticatorException) cause;
1836 } else if (cause instanceof RuntimeException) {
1837 throw (RuntimeException) cause;
1838 } else if (cause instanceof Error) {
1839 throw (Error) cause;
1840 } else {
1841 throw new IllegalStateException(cause);
1842 }
1843 } finally {
1844 cancel(true /* interrupt if running */);
1845 }
1846 throw new OperationCanceledException();
1847 }
1848
1849 public Bundle getResult()
1850 throws OperationCanceledException, IOException, AuthenticatorException {
1851 return internalGetResult(null, null);
1852 }
1853
1854 public Bundle getResult(long timeout, TimeUnit unit)
1855 throws OperationCanceledException, IOException, AuthenticatorException {
1856 return internalGetResult(timeout, unit);
1857 }
1858
1859 protected void done() {
1860 if (mCallback != null) {
1861 postToHandler(mHandler, mCallback, this);
1862 }
1863 }
1864
1865 /** Handles the responses from the AccountManager */
1866 private class Response extends IAccountManagerResponse.Stub {
1867 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07001868 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07001869 if (intent != null && mActivity != null) {
1870 // since the user provided an Activity we will silently start intents
1871 // that we see
1872 mActivity.startActivity(intent);
1873 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001874 } else if (bundle.getBoolean("retry")) {
1875 try {
1876 doWork();
1877 } catch (RemoteException e) {
1878 // this will only happen if the system process is dead, which means
1879 // we will be dying ourselves
1880 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001881 } else {
1882 set(bundle);
1883 }
1884 }
1885
1886 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001887 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1888 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1889 // the authenticator indicated that this request was canceled or we were
1890 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001891 cancel(true /* mayInterruptIfRunning */);
1892 return;
1893 }
1894 setException(convertErrorToException(code, message));
1895 }
1896 }
1897
Fred Quintana60307342009-03-24 22:48:12 -07001898 }
1899
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001900 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1901 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001902 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001903
1904 public BaseFutureTask(Handler handler) {
1905 super(new Callable<T>() {
1906 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001907 throw new IllegalStateException("this should never be called");
1908 }
1909 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001910 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001911 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001912 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001913
1914 public abstract void doWork() throws RemoteException;
1915
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001916 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001917
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001918 protected void postRunnableToHandler(Runnable runnable) {
1919 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1920 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001921 }
1922
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001923 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001924 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001925 doWork();
1926 } catch (RemoteException e) {
1927 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001928 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001929 }
1930
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001931 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001932 public void onResult(Bundle bundle) {
1933 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001934 T result = bundleToResult(bundle);
1935 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001936 return;
1937 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001938 set(result);
1939 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001940 } catch (ClassCastException e) {
1941 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001942 } catch (AuthenticatorException e) {
1943 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001944 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001945 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001946 }
1947
1948 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001949 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1950 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1951 // the authenticator indicated that this request was canceled or we were
1952 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001953 cancel(true /* mayInterruptIfRunning */);
1954 return;
1955 }
1956 setException(convertErrorToException(code, message));
1957 }
1958 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001959 }
1960
1961 private abstract class Future2Task<T>
1962 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1963 final AccountManagerCallback<T> mCallback;
1964 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1965 super(handler);
1966 mCallback = callback;
1967 }
1968
1969 protected void done() {
1970 if (mCallback != null) {
1971 postRunnableToHandler(new Runnable() {
1972 public void run() {
1973 mCallback.run(Future2Task.this);
1974 }
1975 });
1976 }
1977 }
1978
1979 public Future2Task<T> start() {
1980 startTask();
1981 return this;
1982 }
1983
1984 private T internalGetResult(Long timeout, TimeUnit unit)
1985 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001986 if (!isDone()) {
1987 ensureNotOnMainThread();
1988 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001989 try {
1990 if (timeout == null) {
1991 return get();
1992 } else {
1993 return get(timeout, unit);
1994 }
1995 } catch (InterruptedException e) {
1996 // fall through and cancel
1997 } catch (TimeoutException e) {
1998 // fall through and cancel
1999 } catch (CancellationException e) {
2000 // fall through and cancel
2001 } catch (ExecutionException e) {
2002 final Throwable cause = e.getCause();
2003 if (cause instanceof IOException) {
2004 throw (IOException) cause;
2005 } else if (cause instanceof UnsupportedOperationException) {
2006 throw new AuthenticatorException(cause);
2007 } else if (cause instanceof AuthenticatorException) {
2008 throw (AuthenticatorException) cause;
2009 } else if (cause instanceof RuntimeException) {
2010 throw (RuntimeException) cause;
2011 } else if (cause instanceof Error) {
2012 throw (Error) cause;
2013 } else {
2014 throw new IllegalStateException(cause);
2015 }
2016 } finally {
2017 cancel(true /* interrupt if running */);
2018 }
2019 throw new OperationCanceledException();
2020 }
2021
2022 public T getResult()
2023 throws OperationCanceledException, IOException, AuthenticatorException {
2024 return internalGetResult(null, null);
2025 }
2026
2027 public T getResult(long timeout, TimeUnit unit)
2028 throws OperationCanceledException, IOException, AuthenticatorException {
2029 return internalGetResult(timeout, unit);
2030 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002031
Fred Quintana60307342009-03-24 22:48:12 -07002032 }
2033
Fred Quintanaa698f422009-04-08 19:14:54 -07002034 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002035 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002036 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002037 }
Fred Quintana60307342009-03-24 22:48:12 -07002038
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002039 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002040 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002041 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002042
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002043 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002044 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002045 }
2046
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002047 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002048 return new IllegalArgumentException(message);
2049 }
2050
2051 return new AuthenticatorException(message);
2052 }
2053
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002054 private class GetAuthTokenByTypeAndFeaturesTask
2055 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002056 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2057 final String[] features, Activity activityForPrompting,
2058 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002059 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002060 super(activityForPrompting, handler, callback);
2061 if (accountType == null) throw new IllegalArgumentException("account type is null");
2062 mAccountType = accountType;
2063 mAuthTokenType = authTokenType;
2064 mFeatures = features;
2065 mAddAccountOptions = addAccountOptions;
2066 mLoginOptions = loginOptions;
2067 mMyCallback = this;
2068 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002069 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002070 final String mAccountType;
2071 final String mAuthTokenType;
2072 final String[] mFeatures;
2073 final Bundle mAddAccountOptions;
2074 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002075 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002076 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002077
2078 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002079 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2080 new AccountManagerCallback<Account[]>() {
2081 public void run(AccountManagerFuture<Account[]> future) {
2082 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07002083 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002084 accounts = future.getResult();
2085 } catch (OperationCanceledException e) {
2086 setException(e);
2087 return;
2088 } catch (IOException e) {
2089 setException(e);
2090 return;
2091 } catch (AuthenticatorException e) {
2092 setException(e);
2093 return;
Fred Quintana33269202009-04-20 16:05:10 -07002094 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002095
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002096 mNumAccounts = accounts.length;
2097
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002098 if (accounts.length == 0) {
2099 if (mActivity != null) {
2100 // no accounts, add one now. pretend that the user directly
2101 // made this request
2102 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2103 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2104 } else {
2105 // send result since we can't prompt to add an account
2106 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002107 result.putString(KEY_ACCOUNT_NAME, null);
2108 result.putString(KEY_ACCOUNT_TYPE, null);
2109 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002110 try {
2111 mResponse.onResult(result);
2112 } catch (RemoteException e) {
2113 // this will never happen
2114 }
2115 // we are done
2116 }
2117 } else if (accounts.length == 1) {
2118 // have a single account, return an authtoken for it
2119 if (mActivity == null) {
2120 mFuture = getAuthToken(accounts[0], mAuthTokenType,
2121 false /* notifyAuthFailure */, mMyCallback, mHandler);
2122 } else {
2123 mFuture = getAuthToken(accounts[0],
2124 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002125 mActivity, mMyCallback, mHandler);
2126 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002127 } else {
2128 if (mActivity != null) {
2129 IAccountManagerResponse chooseResponse =
2130 new IAccountManagerResponse.Stub() {
2131 public void onResult(Bundle value) throws RemoteException {
2132 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002133 value.getString(KEY_ACCOUNT_NAME),
2134 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002135 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2136 mActivity, mMyCallback, mHandler);
2137 }
Fred Quintana33269202009-04-20 16:05:10 -07002138
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002139 public void onError(int errorCode, String errorMessage)
2140 throws RemoteException {
2141 mResponse.onError(errorCode, errorMessage);
2142 }
2143 };
2144 // have many accounts, launch the chooser
2145 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002146 ComponentName componentName = ComponentName.unflattenFromString(
2147 Resources.getSystem().getString(
2148 R.string.config_chooseAccountActivity));
2149 intent.setClassName(componentName.getPackageName(),
2150 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002151 intent.putExtra(KEY_ACCOUNTS, accounts);
2152 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002153 new AccountManagerResponse(chooseResponse));
2154 mActivity.startActivity(intent);
2155 // the result will arrive via the IAccountManagerResponse
2156 } else {
2157 // send result since we can't prompt to select an account
2158 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002159 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002160 try {
2161 mResponse.onResult(result);
2162 } catch (RemoteException e) {
2163 // this will never happen
2164 }
2165 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07002166 }
Fred Quintana33269202009-04-20 16:05:10 -07002167 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002168 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002169 }
2170
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002171 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002172 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002173 final Bundle result = future.getResult();
2174 if (mNumAccounts == 0) {
2175 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2176 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2177 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2178 setException(new AuthenticatorException("account not in result"));
2179 return;
2180 }
2181 final Account account = new Account(accountName, accountType);
2182 mNumAccounts = 1;
2183 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2184 mMyCallback, mHandler);
2185 return;
2186 }
2187 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002188 } catch (OperationCanceledException e) {
2189 cancel(true /* mayInterruptIfRUnning */);
2190 } catch (IOException e) {
2191 setException(e);
2192 } catch (AuthenticatorException e) {
2193 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002194 }
2195 }
2196 }
2197
Fred Quintana756b7352009-10-21 13:43:10 -07002198 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002199 * This convenience helper combines the functionality of
2200 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2201 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002202 *
Dan Egnor661f0132010-02-19 11:23:00 -08002203 * <p>This method gets a list of the accounts matching the
2204 * specified type and feature set; if there is exactly one, it is
2205 * used; if there are more than one, the user is prompted to pick one;
2206 * if there are none, the user is prompted to add one. Finally,
2207 * an auth token is acquired for the chosen account.
2208 *
2209 * <p>This method may be called from any thread, but the returned
2210 * {@link AccountManagerFuture} must not be used on the main thread.
2211 *
Dan Egnor661f0132010-02-19 11:23:00 -08002212 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08002213 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08002214 * @param authTokenType The desired auth token type
2215 * (see {@link #getAuthToken}), must not be null
2216 * @param features Required features for the account
2217 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2218 * @param activity The {@link Activity} context to use for launching new
2219 * sub-Activities to prompt to add an account, select an account,
2220 * and/or enter a password, as necessary; used only to call
2221 * startActivity(); should not be null
2222 * @param addAccountOptions Authenticator-specific options to use for
2223 * adding new accounts; may be null or empty
2224 * @param getAuthTokenOptions Authenticator-specific options to use for
2225 * getting auth tokens; may be null or empty
2226 * @param callback Callback to invoke when the request completes,
2227 * null for no callback
2228 * @param handler {@link Handler} identifying the callback thread,
2229 * null for the main thread
2230 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2231 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07002232 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002233 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2234 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2235 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07002236 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002237 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07002238 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002239 * <ul>
2240 * <li> {@link AuthenticatorException} if no authenticator was registered for
2241 * this account type or the authenticator failed to respond
2242 * <li> {@link OperationCanceledException} if the operation was canceled for
2243 * any reason, including the user canceling any operation
2244 * <li> {@link IOException} if the authenticator experienced an I/O problem
2245 * updating settings, usually because of network trouble
2246 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002247 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002248 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002249 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002250 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07002251 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002252 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002253 if (accountType == null) throw new IllegalArgumentException("account type is null");
2254 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002255 final GetAuthTokenByTypeAndFeaturesTask task =
2256 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002257 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002258 task.start();
2259 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002260 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002261
Fred Quintana1121bb52011-09-14 23:19:35 -07002262 /**
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002263 * Deprecated in favor of {@link #newChooseAccountIntent(Account, List, String[], String,
2264 * String, String[], Bundle)}.
2265 *
Fred Quintana1121bb52011-09-14 23:19:35 -07002266 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2267 * accounts.
2268 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002269 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002270 * <p>
2271 * On success the activity returns a Bundle with the account name and type specified using
2272 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2273 * <p>
2274 * The most common case is to call this with one account type, e.g.:
2275 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002276 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002277 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002278 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2279 * selected one, according to the caller's definition of selected.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002280 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
Fred Quintana1121bb52011-09-14 23:19:35 -07002281 * shown. If not specified then this field will not limit the displayed accounts.
2282 * @param allowableAccountTypes an optional string array of account types. These are used
2283 * 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 -07002284 * when adding an account. If not specified then this field will not limit the displayed
2285 * account types when adding an account.
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002286 * @param alwaysPromptForAccount boolean that is ignored.
Fred Quintanad88324d2011-09-19 11:43:05 -07002287 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002288 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002289 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2290 * authTokenType parameter
2291 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2292 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002293 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002294 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002295 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002296 */
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002297 @Deprecated
2298 static public Intent newChooseAccountIntent(
2299 Account selectedAccount,
Baligh Uddinf2d248d2015-07-10 03:01:47 +00002300 ArrayList<Account> allowableAccounts,
Fred Quintana1121bb52011-09-14 23:19:35 -07002301 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002302 boolean alwaysPromptForAccount,
2303 String descriptionOverrideText,
2304 String addAccountAuthTokenType,
2305 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002306 Bundle addAccountOptions) {
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002307 return newChooseAccountIntent(
2308 selectedAccount,
2309 allowableAccounts,
2310 allowableAccountTypes,
2311 descriptionOverrideText,
2312 addAccountAuthTokenType,
2313 addAccountRequiredFeatures,
2314 addAccountOptions);
2315 }
2316
2317 /**
2318 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2319 * accounts.
2320 * The caller will then typically start the activity by calling
2321 * <code>startActivityForResult(intent, ...);</code>.
2322 * <p>
2323 * On success the activity returns a Bundle with the account name and type specified using
2324 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2325 * <p>
2326 * The most common case is to call this with one account type, e.g.:
2327 * <p>
2328 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, null, null, null,
2329 * null);</pre>
2330 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2331 * selected one, according to the caller's definition of selected.
2332 * @param allowableAccounts an optional {@link List} of accounts that are allowed to be
2333 * shown. If not specified then this field will not limit the displayed accounts.
2334 * @param allowableAccountTypes an optional string array of account types. These are used
2335 * both to filter the shown accounts and to filter the list of account types that are shown
2336 * when adding an account. If not specified then this field will not limit the displayed
2337 * account types when adding an account.
2338 * @param descriptionOverrideText if non-null this string is used as the description in the
2339 * accounts chooser screen rather than the default
2340 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2341 * authTokenType parameter
2342 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2343 * requiredFeatures parameter
2344 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
2345 * parameter
2346 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
2347 */
2348 static public Intent newChooseAccountIntent(
2349 Account selectedAccount,
2350 List<Account> allowableAccounts,
2351 String[] allowableAccountTypes,
2352 String descriptionOverrideText,
2353 String addAccountAuthTokenType,
2354 String[] addAccountRequiredFeatures,
2355 Bundle addAccountOptions) {
Fred Quintana1121bb52011-09-14 23:19:35 -07002356 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002357 ComponentName componentName = ComponentName.unflattenFromString(
2358 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2359 intent.setClassName(componentName.getPackageName(),
2360 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002361 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
Carlos Valdiviaa3db8ac2015-07-10 13:04:43 -07002362 new ArrayList<Account>(allowableAccounts));
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002363 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2364 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002365 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2366 addAccountOptions);
2367 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002368 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2369 descriptionOverrideText);
2370 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2371 addAccountAuthTokenType);
2372 intent.putExtra(
2373 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2374 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002375 return intent;
2376 }
2377
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002378 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002379 Maps.newHashMap();
2380
Fred Quintanad9d2f112009-04-23 13:36:27 -07002381 /**
2382 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2383 * so that it can read the updated list of accounts and send them to the listener
2384 * in mAccountsUpdatedListeners.
2385 */
2386 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
2387 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002388 final Account[] accounts = getAccounts();
2389 // send the result to the listeners
2390 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002391 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002392 mAccountsUpdatedListeners.entrySet()) {
2393 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002394 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002395 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002396 }
2397 };
2398
2399 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002400 * Adds an {@link OnAccountsUpdateListener} to this instance of the
2401 * {@link AccountManager}. This listener will be notified whenever the
2402 * list of accounts on the device changes.
2403 *
2404 * <p>As long as this listener is present, the AccountManager instance
2405 * will not be garbage-collected, and neither will the {@link Context}
2406 * used to retrieve it, which may be a large Activity instance. To avoid
2407 * memory leaks, you must remove this listener before then. Normally
2408 * listeners are added in an Activity or Service's {@link Activity#onCreate}
2409 * and removed in {@link Activity#onDestroy}.
2410 *
2411 * <p>It is safe to call this method from the main thread.
2412 *
Nicolas Falliere9530e3a2012-06-18 17:21:06 -07002413 * <p>This method requires the caller to hold the permission
2414 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Dan Egnor661f0132010-02-19 11:23:00 -08002415 *
2416 * @param listener The listener to send notifications to
2417 * @param handler {@link Handler} identifying the thread to use
2418 * for notifications, null for the main thread
2419 * @param updateImmediately If true, the listener will be invoked
2420 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002421 * @throws IllegalArgumentException if listener is null
2422 * @throws IllegalStateException if listener was already added
2423 */
Tor Norbye80b530a2015-04-23 16:36:09 -07002424 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002425 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002426 Handler handler, boolean updateImmediately) {
2427 if (listener == null) {
2428 throw new IllegalArgumentException("the listener is null");
2429 }
2430 synchronized (mAccountsUpdatedListeners) {
2431 if (mAccountsUpdatedListeners.containsKey(listener)) {
2432 throw new IllegalStateException("this listener is already added");
2433 }
2434 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2435
2436 mAccountsUpdatedListeners.put(listener, handler);
2437
2438 if (wasEmpty) {
2439 // Register a broadcast receiver to monitor account changes
2440 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002441 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002442 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002443 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002444 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2445 }
2446 }
2447
2448 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002449 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002450 }
2451 }
2452
2453 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002454 * Removes an {@link OnAccountsUpdateListener} previously registered with
2455 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2456 * receive notifications of account changes.
2457 *
2458 * <p>It is safe to call this method from the main thread.
2459 *
2460 * <p>No permission is required to call this method.
2461 *
2462 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002463 * @throws IllegalArgumentException if listener is null
2464 * @throws IllegalStateException if listener was not already added
2465 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002466 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002467 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002468 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002469 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002470 Log.e(TAG, "Listener was not previously added");
2471 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002472 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002473 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002474 if (mAccountsUpdatedListeners.isEmpty()) {
2475 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2476 }
2477 }
2478 }
Fred Quintana60307342009-03-24 22:48:12 -07002479}