blob: 993b53d17d705c09a4b0a9e65a8d4cfedd4c5b7e [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;
46import java.util.Map;
Fred Quintanaa698f422009-04-08 19:14:54 -070047import java.util.concurrent.Callable;
48import java.util.concurrent.CancellationException;
49import java.util.concurrent.ExecutionException;
50import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070051import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080052import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070053
Tor Norbye80b530a2015-04-23 16:36:09 -070054import static android.Manifest.permission.GET_ACCOUNTS;
Tor Norbye80b530a2015-04-23 16:36:09 -070055
Fred Quintana60307342009-03-24 22:48:12 -070056/**
Dan Egnor661f0132010-02-19 11:23:00 -080057 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070058 * online accounts. The user enters credentials (username and password) once
59 * per account, granting applications access to online resources with
60 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070061 *
Dan Egnor661f0132010-02-19 11:23:00 -080062 * <p>Different online services have different ways of handling accounts and
63 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070064 * modules for different <em>account types</em>. Authenticators (which may be
65 * written by third parties) handle the actual details of validating account
66 * credentials and storing account information. For example, Google, Facebook,
67 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080068 *
69 * <p>Many servers support some notion of an <em>authentication token</em>,
70 * which can be used to authenticate a request to the server without sending
71 * the user's actual password. (Auth tokens are normally created with a
72 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070073 * can generate auth tokens for applications, so the application doesn't need to
74 * handle passwords directly. Auth tokens are normally reusable and cached by
75 * AccountManager, but must be refreshed periodically. It's the responsibility
76 * of applications to <em>invalidate</em> auth tokens when they stop working so
77 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080078 *
79 * <p>Applications accessing a server normally go through these steps:
80 *
81 * <ul>
82 * <li>Get an instance of AccountManager using {@link #get(Context)}.
83 *
84 * <li>List the available accounts using {@link #getAccountsByType} or
85 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
86 * be interested in accounts with one particular <em>type</em>, which
87 * identifies the authenticator. Account <em>features</em> are used to
88 * identify particular account subtypes and capabilities. Both the account
89 * type and features are authenticator-specific strings, and must be known by
90 * the application in coordination with its preferred authenticators.
91 *
92 * <li>Select one or more of the available accounts, possibly by asking the
93 * user for their preference. If no suitable accounts are available,
94 * {@link #addAccount} may be called to prompt the user to create an
95 * account of the appropriate type.
96 *
Dan Egnor8e4378b2010-08-02 18:22:09 -070097 * <li><b>Important:</b> If the application is using a previously remembered
98 * account selection, it must make sure the account is still in the list
99 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
100 * for an account no longer on the device results in an undefined failure.
101 *
Dan Egnor661f0132010-02-19 11:23:00 -0800102 * <li>Request an auth token for the selected account(s) using one of the
103 * {@link #getAuthToken} methods or related helpers. Refer to the description
104 * of each method for exact usage and error handling details.
105 *
106 * <li>Make the request using the auth token. The form of the auth token,
107 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700108 * service you are accessing. The application may use whatever network and
109 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800110 *
111 * <li><b>Important:</b> If the request fails with an authentication error,
112 * it could be that a cached auth token is stale and no longer honored by
113 * the server. The application must call {@link #invalidateAuthToken} to remove
114 * the token from the cache, otherwise requests will continue failing! After
115 * invalidating the auth token, immediately go back to the "Request an auth
116 * token" step above. If the process fails the second time, then it can be
117 * treated as a "genuine" authentication failure and the user notified or other
118 * appropriate actions taken.
119 * </ul>
120 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700121 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800122 * prompt for credentials, present options, or ask the user to add an account.
123 * The caller may choose whether to allow AccountManager to directly launch the
124 * necessary user interface and wait for the user, or to return an Intent which
125 * the caller may use to launch the interface, or (in some cases) to install a
126 * notification which the user can select at any time to launch the interface.
127 * To have AccountManager launch the interface directly, the caller must supply
128 * the current foreground {@link Activity} context.
129 *
130 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700131 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800132 * run asynchronously. If a callback is provided then
133 * {@link AccountManagerCallback#run} will be invoked on the Handler's
134 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700135 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
136 * on the {@link AccountManagerFuture} returned by the method (and also passed
137 * to the callback). This method waits for the operation to complete (if
138 * necessary) and either returns the result or throws an exception if an error
139 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800140 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700141 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800142 *
143 * <p>Requests which may block, including
144 * {@link AccountManagerFuture#getResult()}, must never be called on
145 * the application's main event thread. These operations throw
146 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700147 */
148public class AccountManager {
149 private static final String TAG = "AccountManager";
150
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700151 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
152 public static final int ERROR_CODE_NETWORK_ERROR = 3;
153 public static final int ERROR_CODE_CANCELED = 4;
154 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
155 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
156 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
157 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700158 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700159
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160 /** @hide */
161 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100162 /** @hide */
163 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800164
Dan Egnor661f0132010-02-19 11:23:00 -0800165 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700166 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800167 * from methods which return information about a particular account.
168 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700169 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800170
171 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700172 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800173 * from methods which return information about a particular account.
174 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700175 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800176
177 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700178 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800179 * from {@link #getAuthToken} and friends.
180 */
181 public static final String KEY_AUTHTOKEN = "authtoken";
182
183 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700184 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800185 * may require the caller to interact with the user. The Intent can
186 * be used to start the corresponding user interface activity.
187 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700188 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800189
190 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700191 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800192 * {@link #confirmCredentials}, rather than prompting the user with
193 * the standard password prompt.
194 */
195 public static final String KEY_PASSWORD = "password";
196
197 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700198
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700199 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
200 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800201 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700202 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
203 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800204 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
205 public static final String KEY_ERROR_CODE = "errorCode";
206 public static final String KEY_ERROR_MESSAGE = "errorMessage";
207 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700208
Costin Manolachea40c6302010-12-13 14:50:45 -0800209 /**
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800210 * Bundle key used to supply the last time the credentials of the account
211 * were authenticated successfully. Time is specified in milliseconds since
212 * epoch.
213 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700214 public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800215
216 /**
Costin Manolachea40c6302010-12-13 14:50:45 -0800217 * Authenticators using 'customTokens' option will also get the UID of the
218 * caller
219 */
220 public static final String KEY_CALLER_UID = "callerUid";
221 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800222
Costin Manolached6060452011-01-24 16:11:36 -0800223 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700224 * The Android package of the caller will be set in the options bundle by the
225 * {@link AccountManager} and will be passed to the AccountManagerService and
226 * to the AccountAuthenticators. The uid of the caller will be known by the
227 * AccountManagerService as well as the AccountAuthenticators so they will be able to
228 * verify that the package is consistent with the uid (a uid might be shared by many
229 * packages).
230 */
231 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
232
233 /**
Costin Manolached6060452011-01-24 16:11:36 -0800234 * Boolean, if set and 'customTokens' the authenticator is responsible for
235 * notifications.
236 * @hide
237 */
238 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
239
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700240 public static final String ACTION_AUTHENTICATOR_INTENT =
241 "android.accounts.AccountAuthenticator";
242 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800243 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700244 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
245
Fred Quintana60307342009-03-24 22:48:12 -0700246 private final Context mContext;
247 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700248 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800249
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700250 /**
251 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800252 * when accounts are added, accounts are removed, or an
253 * account's credentials (saved password, etc) are changed.
254 *
255 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700256 */
257 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
258 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700259
Fred Quintana33269202009-04-20 16:05:10 -0700260 /**
261 * @hide
262 */
Fred Quintana60307342009-03-24 22:48:12 -0700263 public AccountManager(Context context, IAccountManager service) {
264 mContext = context;
265 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700266 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700267 }
268
Fred Quintana0eabf022009-04-27 15:08:17 -0700269 /**
270 * @hide used for testing only
271 */
272 public AccountManager(Context context, IAccountManager service, Handler handler) {
273 mContext = context;
274 mService = service;
275 mMainHandler = handler;
276 }
277
Fred Quintana756b7352009-10-21 13:43:10 -0700278 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800279 * @hide for internal use only
280 */
281 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700282 if (result != null) {
283 if (result.containsKey(KEY_AUTHTOKEN)
284 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
285 final Bundle newResult = new Bundle(result);
286 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
287 return newResult;
288 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800289 }
290 return result;
291 }
292
293 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800294 * Gets an AccountManager instance associated with a Context.
295 * The {@link Context} will be used as long as the AccountManager is
296 * active, so make sure to use a {@link Context} whose lifetime is
297 * commensurate with any listeners registered to
298 * {@link #addOnAccountsUpdatedListener} or similar methods.
299 *
300 * <p>It is safe to call this method from the main thread.
301 *
302 * <p>No permission is required to call this method.
303 *
Fred Quintana756b7352009-10-21 13:43:10 -0700304 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800305 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700306 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700307 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700308 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700309 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
310 }
311
Fred Quintana756b7352009-10-21 13:43:10 -0700312 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800313 * Gets the saved password associated with the account.
314 * This is intended for authenticators and related code; applications
315 * should get an auth token instead.
316 *
317 * <p>It is safe to call this method from the main thread.
318 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700319 * <p>This method requires the caller to have a signature match with the
320 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800321 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700322 * @param account The account to query for a password. Must not be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800323 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700324 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700325 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700326 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700327 try {
328 return mService.getPassword(account);
329 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700330 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700331 throw new RuntimeException(e);
332 }
333 }
334
Fred Quintana756b7352009-10-21 13:43:10 -0700335 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800336 * Gets the user data named by "key" associated with the account.
337 * This is intended for authenticators and related code to store
338 * arbitrary metadata along with accounts. The meaning of the keys
339 * and values is up to the authenticator for the account.
340 *
341 * <p>It is safe to call this method from the main thread.
342 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700343 * <p>This method requires the caller to have a signature match with the
344 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800345 *
346 * @param account The account to query for user data
347 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700348 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700349 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700350 if (account == null) throw new IllegalArgumentException("account is null");
351 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700352 try {
353 return mService.getUserData(account, key);
354 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700355 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700356 throw new RuntimeException(e);
357 }
358 }
359
Fred Quintana756b7352009-10-21 13:43:10 -0700360 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800361 * Lists the currently registered authenticators.
362 *
363 * <p>It is safe to call this method from the main thread.
364 *
365 * <p>No permission is required to call this method.
366 *
367 * @return An array of {@link AuthenticatorDescription} for every
368 * authenticator known to the AccountManager service. Empty (never
369 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700370 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700371 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700372 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100373 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
374 } catch (RemoteException e) {
375 // will never happen
376 throw new RuntimeException(e);
377 }
378 }
379
380 /**
381 * @hide
382 * Lists the currently registered authenticators for a given user id.
383 *
384 * <p>It is safe to call this method from the main thread.
385 *
386 * <p>The caller has to be in the same user or have the permission
387 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
388 *
389 * @return An array of {@link AuthenticatorDescription} for every
390 * authenticator known to the AccountManager service. Empty (never
391 * null) if no authenticators are known.
392 */
393 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
394 try {
395 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700396 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700397 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700398 throw new RuntimeException(e);
399 }
400 }
401
Fred Quintana756b7352009-10-21 13:43:10 -0700402 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800403 * Lists all accounts of any type registered on the device.
404 * Equivalent to getAccountsByType(null).
405 *
406 * <p>It is safe to call this method from the main thread.
407 *
408 * <p>This method requires the caller to hold the permission
409 * {@link android.Manifest.permission#GET_ACCOUNTS}.
410 *
411 * @return An array of {@link Account}, one for each account. Empty
412 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700413 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700414 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700415 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700416 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700417 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700418 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700419 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700420 throw new RuntimeException(e);
421 }
422 }
423
Fred Quintana756b7352009-10-21 13:43:10 -0700424 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700425 * @hide
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100426 * Lists all accounts of any type registered on the device for a given
427 * user id. Equivalent to getAccountsByType(null).
428 *
429 * <p>It is safe to call this method from the main thread.
430 *
431 * <p>This method requires the caller to hold the permission
432 * {@link android.Manifest.permission#GET_ACCOUNTS}.
433 *
434 * @return An array of {@link Account}, one for each account. Empty
435 * (never null) if no accounts have been added.
436 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700437 @RequiresPermission(GET_ACCOUNTS)
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100438 public Account[] getAccountsAsUser(int userId) {
439 try {
440 return mService.getAccountsAsUser(null, userId);
441 } catch (RemoteException e) {
442 // won't ever happen
443 throw new RuntimeException(e);
444 }
445 }
446
447 /**
448 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700449 * For use by internal activities. Returns the list of accounts that the calling package
450 * is authorized to use, particularly for shared accounts.
451 * @param packageName package name of the calling app.
452 * @param uid the uid of the calling app.
453 * @return the accounts that are available to this package and user.
454 */
455 public Account[] getAccountsForPackage(String packageName, int uid) {
456 try {
457 return mService.getAccountsForPackage(packageName, uid);
458 } catch (RemoteException re) {
459 // possible security exception
460 throw new RuntimeException(re);
461 }
462 }
463
464 /**
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700465 * Returns the accounts visible to the specified package, in an environment where some apps
466 * are not authorized to view all accounts. This method can only be called by system apps.
467 * @param type The type of accounts to return, null to retrieve all accounts
468 * @param packageName The package name of the app for which the accounts are to be returned
469 * @return An array of {@link Account}, one per matching account. Empty
470 * (never null) if no accounts of the specified type have been added.
471 */
472 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
473 try {
474 return mService.getAccountsByTypeForPackage(type, packageName);
475 } catch (RemoteException re) {
476 // possible security exception
477 throw new RuntimeException(re);
478 }
479 }
480
481 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800482 * Lists all accounts of a particular type. The account type is a
483 * string token corresponding to the authenticator and useful domain
484 * of the account. For example, there are types corresponding to Google
485 * and Facebook. The exact string token to use will be published somewhere
486 * associated with the authenticator in question.
487 *
488 * <p>It is safe to call this method from the main thread.
489 *
490 * <p>This method requires the caller to hold the permission
491 * {@link android.Manifest.permission#GET_ACCOUNTS}.
492 *
493 * @param type The type of accounts to return, null to retrieve all accounts
494 * @return An array of {@link Account}, one per matching account. Empty
495 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700496 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700497 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700498 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800499 return getAccountsByTypeAsUser(type, Process.myUserHandle());
500 }
501
502 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
503 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700504 try {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800505 return mService.getAccountsAsUser(type, userHandle.getIdentifier());
Fred Quintana60307342009-03-24 22:48:12 -0700506 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700507 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700508 throw new RuntimeException(e);
509 }
510 }
511
Fred Quintana756b7352009-10-21 13:43:10 -0700512 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700513 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
514 * for an account.
515 * <p>
516 * This is only meant to be used by system activities and is not in the SDK.
517 * @param account The account whose permissions are being modified
518 * @param authTokenType The type of token whose permissions are being modified
519 * @param uid The uid that identifies the app which is being granted or revoked permission.
520 * @param value true is permission is being granted, false for revoked
521 * @hide
522 */
523 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
524 try {
525 mService.updateAppPermission(account, authTokenType, uid, value);
526 } catch (RemoteException e) {
527 // won't ever happen
528 throw new RuntimeException(e);
529 }
530 }
531
532 /**
533 * Get the user-friendly label associated with an authenticator's auth token.
534 * @param accountType the type of the authenticator. must not be null.
535 * @param authTokenType the token type. must not be null.
536 * @param callback callback to invoke when the result is available. may be null.
537 * @param handler the handler on which to invoke the callback, or null for the main thread
538 * @return a future containing the label string
539 * @hide
540 */
541 public AccountManagerFuture<String> getAuthTokenLabel(
542 final String accountType, final String authTokenType,
543 AccountManagerCallback<String> callback, Handler handler) {
544 if (accountType == null) throw new IllegalArgumentException("accountType is null");
545 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
546 return new Future2Task<String>(handler, callback) {
547 public void doWork() throws RemoteException {
548 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
549 }
550
551 @Override
552 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
553 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
554 throw new AuthenticatorException("no result in response");
555 }
556 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
557 }
558 }.start();
559 }
560
561 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800562 * Finds out whether a particular account has all the specified features.
563 * Account features are authenticator-specific string tokens identifying
564 * boolean account properties. For example, features are used to tell
565 * whether Google accounts have a particular service (such as Google
566 * Calendar or Google Talk) enabled. The feature names and their meanings
567 * are published somewhere associated with the authenticator in question.
568 *
569 * <p>This method may be called from any thread, but the returned
570 * {@link AccountManagerFuture} must not be used on the main thread.
571 *
572 * <p>This method requires the caller to hold the permission
573 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800574 *
575 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800576 * @param features An array of the account features to check
577 * @param callback Callback to invoke when the request completes,
578 * null for no callback
579 * @param handler {@link Handler} identifying the callback thread,
580 * null for the main thread
581 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
582 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800583 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700584 @RequiresPermission(GET_ACCOUNTS)
Fred Quintana3084a6f2010-01-14 18:02:03 -0800585 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800586 final String[] features,
587 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700588 if (account == null) throw new IllegalArgumentException("account is null");
589 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800590 return new Future2Task<Boolean>(handler, callback) {
591 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800592 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800593 }
594 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
595 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
596 throw new AuthenticatorException("no result in response");
597 }
598 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
599 }
600 }.start();
601 }
602
603 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800604 * Lists all accounts of a type which have certain features. The account
605 * type identifies the authenticator (see {@link #getAccountsByType}).
606 * Account features are authenticator-specific string tokens identifying
607 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700608 *
Dan Egnor661f0132010-02-19 11:23:00 -0800609 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
610 * which may contact the server or do other work to check account features,
611 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700612 *
Dan Egnor661f0132010-02-19 11:23:00 -0800613 * <p>This method may be called from any thread, but the returned
614 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700615 *
Dan Egnor661f0132010-02-19 11:23:00 -0800616 * <p>This method requires the caller to hold the permission
617 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700618 *
Dan Egnor661f0132010-02-19 11:23:00 -0800619 * @param type The type of accounts to return, must not be null
620 * @param features An array of the account features to require,
621 * may be null or empty
622 * @param callback Callback to invoke when the request completes,
623 * null for no callback
624 * @param handler {@link Handler} identifying the callback thread,
625 * null for the main thread
626 * @return An {@link AccountManagerFuture} which resolves to an array of
627 * {@link Account}, one per account of the specified type which
628 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800629 */
Tor Norbye80b530a2015-04-23 16:36:09 -0700630 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700631 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
632 final String type, final String[] features,
633 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700634 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700635 return new Future2Task<Account[]>(handler, callback) {
636 public void doWork() throws RemoteException {
637 mService.getAccountsByFeatures(mResponse, type, features);
638 }
639 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700640 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700641 throw new AuthenticatorException("no result in response");
642 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700643 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700644 Account[] descs = new Account[parcelables.length];
645 for (int i = 0; i < parcelables.length; i++) {
646 descs[i] = (Account) parcelables[i];
647 }
648 return descs;
649 }
650 }.start();
651 }
652
Fred Quintana756b7352009-10-21 13:43:10 -0700653 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800654 * Adds an account directly to the AccountManager. Normally used by sign-up
655 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700656 *
Dan Egnor661f0132010-02-19 11:23:00 -0800657 * <p>It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700658 * <p>This method requires the caller to have a signature match with the
659 * authenticator that owns the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800660 *
661 * @param account The {@link Account} to add
662 * @param password The password to associate with the account, null for none
663 * @param userdata String values to use for the account's userdata, null for none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700664 * @return True if the account was successfully added, false if the account
Dan Egnor661f0132010-02-19 11:23:00 -0800665 * already exists, the account is null, or another error occurs.
666 */
667 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700668 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800669 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700670 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800671 } catch (RemoteException e) {
672 // won't ever happen
673 throw new RuntimeException(e);
674 }
675 }
676
677 /**
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700678 * Notifies the system that the account has just been authenticated. This
679 * information may be used by other applications to verify the account. This
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800680 * should be called only when the user has entered correct credentials for
681 * the account.
682 * <p>
683 * It is not safe to call this method from the main thread. As such, call it
684 * from another thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700685 * <p>This method requires the caller to have a signature match with the
686 * authenticator that owns the specified account.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800687 *
688 * @param account The {@link Account} to be updated.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700689 * @return boolean {@code true} if the authentication of the account has been successfully
690 * acknowledged. Otherwise {@code false}.
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800691 */
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -0700692 public boolean notifyAccountAuthenticated(Account account) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800693 if (account == null)
694 throw new IllegalArgumentException("account is null");
695 try {
696 return mService.accountAuthenticated(account);
697 } catch (RemoteException e) {
698 throw new RuntimeException(e);
699 }
700 }
701
702 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700703 * Rename the specified {@link Account}. This is equivalent to removing
704 * the existing account and adding a new renamed account with the old
705 * account's user data.
706 *
707 * <p>It is safe to call this method from the main thread.
708 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700709 * <p>This method requires the caller to have a signature match with the
710 * authenticator that manages the specified account.
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700711 *
712 * @param account The {@link Account} to rename
713 * @param newName String name to be associated with the account.
714 * @param callback Callback to invoke when the request completes, null for
715 * no callback
716 * @param handler {@link Handler} identifying the callback thread, null for
717 * the main thread
718 * @return An {@link AccountManagerFuture} which resolves to the Account
719 * after the name change. If successful the account's name will be the
720 * specified new name.
721 */
722 public AccountManagerFuture<Account> renameAccount(
723 final Account account,
Tor Norbye80b530a2015-04-23 16:36:09 -0700724 @Size(min = 1) final String newName,
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700725 AccountManagerCallback<Account> callback,
726 Handler handler) {
727 if (account == null) throw new IllegalArgumentException("account is null.");
728 if (TextUtils.isEmpty(newName)) {
729 throw new IllegalArgumentException("newName is empty or null.");
730 }
731 return new Future2Task<Account>(handler, callback) {
732 @Override
733 public void doWork() throws RemoteException {
734 mService.renameAccount(mResponse, account, newName);
735 }
736 @Override
737 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
738 String name = bundle.getString(KEY_ACCOUNT_NAME);
739 String type = bundle.getString(KEY_ACCOUNT_TYPE);
740 return new Account(name, type);
741 }
742 }.start();
743 }
744
745 /**
746 * Gets the previous name associated with the account or {@code null}, if
747 * none. This is intended so that clients of {@link
748 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
749 * authenticator has renamed an account.
750 *
751 * <p>It is safe to call this method from the main thread.
752 *
753 * @param account The account to query for a previous name.
754 * @return The account's previous name, null if the account has never been
755 * renamed.
756 */
757 public String getPreviousName(final Account account) {
758 if (account == null) throw new IllegalArgumentException("account is null");
759 try {
760 return mService.getPreviousName(account);
761 } catch (RemoteException e) {
762 // will never happen
763 throw new RuntimeException(e);
764 }
765 }
766
767 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800768 * Removes an account from the AccountManager. Does nothing if the account
769 * does not exist. Does not delete the account from the server.
770 * The authenticator may have its own policies preventing account
771 * deletion, in which case the account will not be deleted.
772 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700773 * <p>This method requires the caller to have a signature match with the
774 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800775 *
776 * @param account The {@link Account} to remove
777 * @param callback Callback to invoke when the request completes,
778 * null for no callback
779 * @param handler {@link Handler} identifying the callback thread,
780 * null for the main thread
781 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100782 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800783 * @deprecated use
784 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
785 * instead
Dan Egnor661f0132010-02-19 11:23:00 -0800786 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800787 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800788 public AccountManagerFuture<Boolean> removeAccount(final Account account,
789 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700790 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800791 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700792 @Override
Dan Egnor661f0132010-02-19 11:23:00 -0800793 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800794 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -0800795 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700796 @Override
Dan Egnor661f0132010-02-19 11:23:00 -0800797 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
798 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
799 throw new AuthenticatorException("no result in response");
800 }
801 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
802 }
803 }.start();
804 }
805
806 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800807 * Removes an account from the AccountManager. Does nothing if the account
808 * does not exist. Does not delete the account from the server.
809 * The authenticator may have its own policies preventing account
810 * deletion, in which case the account will not be deleted.
811 *
812 * <p>This method may be called from any thread, but the returned
813 * {@link AccountManagerFuture} must not be used on the main thread.
814 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700815 * <p>This method requires the caller to have a signature match with the
816 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800817 *
818 * @param account The {@link Account} to remove
819 * @param activity The {@link Activity} context to use for launching a new
820 * authenticator-defined sub-Activity to prompt the user to delete an
821 * account; used only to call startActivity(); if null, the prompt
822 * will not be launched directly, but the {@link Intent} may be
823 * returned to the caller instead
824 * @param callback Callback to invoke when the request completes,
825 * null for no callback
826 * @param handler {@link Handler} identifying the callback thread,
827 * null for the main thread
828 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
829 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
830 * was removed or if active. If no activity was specified, the returned
831 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
832 * needed to launch the actual account removal process, if authenticator
833 * needs the activity launch. If an error occurred,
834 * {@link AccountManagerFuture#getResult()} throws:
835 * <ul>
836 * <li> {@link AuthenticatorException} if no authenticator was registered for
837 * this account type or the authenticator failed to respond
838 * <li> {@link OperationCanceledException} if the operation was canceled for
839 * any reason, including the user canceling the creation process or
840 * adding accounts (of this type) has been disabled by policy
841 * </ul>
842 */
843 public AccountManagerFuture<Bundle> removeAccount(final Account account,
844 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
845 if (account == null) throw new IllegalArgumentException("account is null");
846 return new AmsTask(activity, handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700847 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800848 public void doWork() throws RemoteException {
849 mService.removeAccount(mResponse, account, activity != null);
850 }
851 }.start();
852 }
853
854 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100855 * @see #removeAccount(Account, AccountManagerCallback, Handler)
856 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800857 * @deprecated use
858 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
859 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100860 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800861 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100862 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
863 AccountManagerCallback<Boolean> callback, Handler handler,
864 final UserHandle userHandle) {
865 if (account == null) throw new IllegalArgumentException("account is null");
866 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
867 return new Future2Task<Boolean>(handler, callback) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700868 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100869 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800870 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100871 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700872 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100873 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
874 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
875 throw new AuthenticatorException("no result in response");
876 }
877 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
878 }
879 }.start();
880 }
881
882 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800883 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
884 * @hide
885 */
886 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
887 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
888 final UserHandle userHandle) {
889 if (account == null)
890 throw new IllegalArgumentException("account is null");
891 if (userHandle == null)
892 throw new IllegalArgumentException("userHandle is null");
893 return new AmsTask(activity, handler, callback) {
894 public void doWork() throws RemoteException {
895 mService.removeAccountAsUser(mResponse, account, activity != null,
896 userHandle.getIdentifier());
897 }
898 }.start();
899 }
900
901 /**
902 * Removes an account directly. Normally used by authenticators, not
903 * directly by applications. Does not delete the account from the server.
904 * The authenticator may have its own policies preventing account deletion,
905 * in which case the account will not be deleted.
906 * <p>
907 * It is safe to call this method from the main thread.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700908 * <p>This method requires the caller to have a signature match with the
909 * authenticator that manages the specified account.
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800910 *
911 * @param account The {@link Account} to delete.
912 * @return True if the account was successfully deleted, false if the
913 * account did not exist, the account is null, or another error
914 * occurs.
915 */
916 public boolean removeAccountExplicitly(Account account) {
917 if (account == null) throw new IllegalArgumentException("account is null");
918 try {
919 return mService.removeAccountExplicitly(account);
920 } catch (RemoteException e) {
921 // won't ever happen
922 throw new RuntimeException(e);
923 }
924 }
925
926 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800927 * Removes an auth token from the AccountManager's cache. Does nothing if
928 * the auth token is not currently in the cache. Applications must call this
929 * method when the auth token is found to have expired or otherwise become
930 * invalid for authenticating requests. The AccountManager does not validate
931 * or expire cached auth tokens otherwise.
932 *
933 * <p>It is safe to call this method from the main thread.
934 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700935 * @param accountType The account type of the auth token to invalidate, must not be null
936 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800937 */
938 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700939 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800940 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700941 if (authToken != null) {
942 mService.invalidateAuthToken(accountType, authToken);
943 }
Dan Egnor661f0132010-02-19 11:23:00 -0800944 } catch (RemoteException e) {
945 // won't ever happen
946 throw new RuntimeException(e);
947 }
948 }
949
950 /**
951 * Gets an auth token from the AccountManager's cache. If no auth
952 * token is cached for this account, null will be returned -- a new
953 * auth token will not be generated, and the server will not be contacted.
954 * Intended for use by the authenticator, not directly by applications.
955 *
956 * <p>It is safe to call this method from the main thread.
957 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700958 * <p>This method requires the caller to have a signature match with the
959 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800960 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700961 * @param account The account for which an auth token is to be fetched. Cannot be {@code null}.
962 * @param authTokenType The type of auth token to fetch. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800963 * @return The cached auth token for this account and type, or null if
964 * no auth token is cached or the account does not exist.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700965 * @see #getAuthToken
Dan Egnor661f0132010-02-19 11:23:00 -0800966 */
967 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700968 if (account == null) throw new IllegalArgumentException("account is null");
969 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800970 try {
971 return mService.peekAuthToken(account, authTokenType);
972 } catch (RemoteException e) {
973 // won't ever happen
974 throw new RuntimeException(e);
975 }
976 }
977
978 /**
979 * Sets or forgets a saved password. This modifies the local copy of the
980 * password used to automatically authenticate the user; it does
981 * not change the user's account password on the server. Intended for use
982 * by the authenticator, not directly by applications.
983 *
984 * <p>It is safe to call this method from the main thread.
985 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700986 * <p>This method requires the caller to have a signature match with the
987 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -0800988 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700989 * @param account The account whose password is to be set. Cannot be {@code null}.
Dan Egnor661f0132010-02-19 11:23:00 -0800990 * @param password The password to set, null to clear the password
991 */
992 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700993 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800994 try {
995 mService.setPassword(account, password);
996 } catch (RemoteException e) {
997 // won't ever happen
998 throw new RuntimeException(e);
999 }
1000 }
1001
1002 /**
1003 * Forgets a saved password. This erases the local copy of the password;
1004 * it does not change the user's account password on the server.
1005 * Has the same effect as setPassword(account, null) but requires fewer
1006 * permissions, and may be used by applications or management interfaces
1007 * to "sign out" from an account.
1008 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001009 * <p>This method only successfully clear the account's password when the
1010 * caller has the same signature as the authenticator that owns the
1011 * specified account. Otherwise, this method will silently fail.
Dan Egnor661f0132010-02-19 11:23:00 -08001012 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001013 * <p>It is safe to call this method from the main thread.
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001014 *
Dan Egnor661f0132010-02-19 11:23:00 -08001015 * @param account The account whose password to clear
1016 */
1017 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -07001018 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001019 try {
1020 mService.clearPassword(account);
1021 } catch (RemoteException e) {
1022 // won't ever happen
1023 throw new RuntimeException(e);
1024 }
1025 }
1026
1027 /**
1028 * Sets one userdata key for an account. Intended by use for the
1029 * authenticator to stash state for itself, not directly by applications.
1030 * The meaning of the keys and values is up to the authenticator.
1031 *
1032 * <p>It is safe to call this method from the main thread.
1033 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001034 * <p>This method requires the caller to have a signature match with the
1035 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001036 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001037 * @param account Account whose user data is to be set. Must not be {@code null}.
1038 * @param key String user data key to set. Must not be null
1039 * @param value String value to set, {@code null} to clear this user data key
Dan Egnor661f0132010-02-19 11:23:00 -08001040 */
1041 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001042 if (account == null) throw new IllegalArgumentException("account is null");
1043 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001044 try {
1045 mService.setUserData(account, key, value);
1046 } catch (RemoteException e) {
1047 // won't ever happen
1048 throw new RuntimeException(e);
1049 }
1050 }
1051
1052 /**
1053 * Adds an auth token to the AccountManager cache for an account.
1054 * If the account does not exist then this call has no effect.
1055 * Replaces any previous auth token for this account and auth token type.
1056 * Intended for use by the authenticator, not directly by applications.
1057 *
1058 * <p>It is safe to call this method from the main thread.
1059 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001060 * <p>This method requires the caller to have a signature match with the
1061 * authenticator that manages the specified account.
Dan Egnor661f0132010-02-19 11:23:00 -08001062 *
1063 * @param account The account to set an auth token for
1064 * @param authTokenType The type of the auth token, see {#getAuthToken}
1065 * @param authToken The auth token to add to the cache
1066 */
1067 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001068 if (account == null) throw new IllegalArgumentException("account is null");
1069 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001070 try {
1071 mService.setAuthToken(account, authTokenType, authToken);
1072 } catch (RemoteException e) {
1073 // won't ever happen
1074 throw new RuntimeException(e);
1075 }
1076 }
1077
1078 /**
1079 * This convenience helper synchronously gets an auth token with
1080 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1081 *
1082 * <p>This method may block while a network request completes, and must
1083 * never be made from the main thread.
1084 *
Dan Egnor661f0132010-02-19 11:23:00 -08001085 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001086 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001087 * @param notifyAuthFailure If true, display a notification and return null
1088 * if authentication fails; if false, prompt and wait for the user to
1089 * re-enter correct credentials before returning
1090 * @return An auth token of the specified type for this account, or null
1091 * if authentication fails or none can be fetched.
1092 * @throws AuthenticatorException if the authenticator failed to respond
1093 * @throws OperationCanceledException if the request was canceled for any
1094 * reason, including the user canceling a credential request
1095 * @throws java.io.IOException if the authenticator experienced an I/O problem
1096 * creating a new auth token, usually because of network trouble
1097 */
1098 public String blockingGetAuthToken(Account account, String authTokenType,
1099 boolean notifyAuthFailure)
1100 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001101 if (account == null) throw new IllegalArgumentException("account is null");
1102 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001103 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1104 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001105 if (bundle == null) {
1106 // This should never happen, but it does, occasionally. If it does return null to
1107 // signify that we were not able to get the authtoken.
1108 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1109 // returned
1110 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1111 + account + ", authTokenType " + authTokenType);
1112 return null;
1113 }
Dan Egnor661f0132010-02-19 11:23:00 -08001114 return bundle.getString(KEY_AUTHTOKEN);
1115 }
1116
1117 /**
1118 * Gets an auth token of the specified type for a particular account,
1119 * prompting the user for credentials if necessary. This method is
1120 * intended for applications running in the foreground where it makes
1121 * sense to ask the user directly for a password.
1122 *
1123 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001124 * type, then it is returned. Otherwise, if a saved password is
1125 * available, it is sent to the server to generate a new auth token.
1126 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001127 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001128 * <p>Some authenticators have auth token <em>types</em>, whose value
1129 * is authenticator-dependent. Some services use different token types to
1130 * access different functionality -- for example, Google uses different auth
1131 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001132 *
1133 * <p>This method may be called from any thread, but the returned
1134 * {@link AccountManagerFuture} must not be used on the main thread.
1135 *
Dan Egnor661f0132010-02-19 11:23:00 -08001136 * @param account The account to fetch an auth token for
1137 * @param authTokenType The auth token type, an authenticator-dependent
1138 * string token, must not be null
1139 * @param options Authenticator-specific options for the request,
1140 * may be null or empty
1141 * @param activity The {@link Activity} context to use for launching a new
1142 * authenticator-defined sub-Activity to prompt the user for a password
1143 * if necessary; used only to call startActivity(); must not be null.
1144 * @param callback Callback to invoke when the request completes,
1145 * null for no callback
1146 * @param handler {@link Handler} identifying the callback thread,
1147 * null for the main thread
1148 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1149 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001150 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001151 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1152 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1153 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001154 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001155 *
1156 * (Other authenticator-specific values may be returned.) If an auth token
1157 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1158 * <ul>
1159 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1160 * <li> {@link OperationCanceledException} if the operation is canceled for
1161 * any reason, incluidng the user canceling a credential request
1162 * <li> {@link IOException} if the authenticator experienced an I/O problem
1163 * creating a new auth token, usually because of network trouble
1164 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001165 * If the account is no longer present on the device, the return value is
1166 * authenticator-dependent. The caller should verify the validity of the
1167 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001168 */
1169 public AccountManagerFuture<Bundle> getAuthToken(
1170 final Account account, final String authTokenType, final Bundle options,
1171 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001172 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001173 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001174 final Bundle optionsIn = new Bundle();
1175 if (options != null) {
1176 optionsIn.putAll(options);
1177 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001178 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001179 return new AmsTask(activity, handler, callback) {
1180 public void doWork() throws RemoteException {
1181 mService.getAuthToken(mResponse, account, authTokenType,
1182 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001183 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001184 }
1185 }.start();
1186 }
1187
1188 /**
1189 * Gets an auth token of the specified type for a particular account,
1190 * optionally raising a notification if the user must enter credentials.
1191 * This method is intended for background tasks and services where the
1192 * user should not be immediately interrupted with a password prompt.
1193 *
1194 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001195 * type, then it is returned. Otherwise, if a saved password is
1196 * available, it is sent to the server to generate a new auth token.
1197 * Otherwise, an {@link Intent} is returned which, when started, will
1198 * prompt the user for a password. If the notifyAuthFailure parameter is
1199 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001200 * alerting the user that they need to enter a password at some point.
1201 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001202 * <p>In that case, you may need to wait until the user responds, which
1203 * could take hours or days or forever. When the user does respond and
1204 * supply a new password, the account manager will broadcast the
1205 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1206 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001207 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001208 * <p>If notifyAuthFailure is not set, it is the application's
1209 * responsibility to launch the returned Intent at some point.
1210 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001211 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001212 * <p>Some authenticators have auth token <em>types</em>, whose value
1213 * is authenticator-dependent. Some services use different token types to
1214 * access different functionality -- for example, Google uses different auth
1215 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001216 *
1217 * <p>This method may be called from any thread, but the returned
1218 * {@link AccountManagerFuture} must not be used on the main thread.
1219 *
Dan Egnor661f0132010-02-19 11:23:00 -08001220 * @param account The account to fetch an auth token for
1221 * @param authTokenType The auth token type, an authenticator-dependent
1222 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001223 * @param notifyAuthFailure True to add a notification to prompt the
1224 * user for a password if necessary, false to leave that to the caller
1225 * @param callback Callback to invoke when the request completes,
1226 * null for no callback
1227 * @param handler {@link Handler} identifying the callback thread,
1228 * null for the main thread
1229 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1230 * at least the following fields on success:
1231 * <ul>
1232 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1233 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1234 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1235 * </ul>
1236 *
1237 * (Other authenticator-specific values may be returned.) If the user
1238 * must enter credentials, the returned Bundle contains only
1239 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1240 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001241 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001242 * <ul>
1243 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1244 * <li> {@link OperationCanceledException} if the operation is canceled for
1245 * any reason, incluidng the user canceling a credential request
1246 * <li> {@link IOException} if the authenticator experienced an I/O problem
1247 * creating a new auth token, usually because of network trouble
1248 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001249 * If the account is no longer present on the device, the return value is
1250 * authenticator-dependent. The caller should verify the validity of the
1251 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001252 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1253 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001254 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001255 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001256 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001257 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001258 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001259 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001260 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001261 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001262 }
1263
1264 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001265 * Gets an auth token of the specified type for a particular account,
1266 * optionally raising a notification if the user must enter credentials.
1267 * This method is intended for background tasks and services where the
1268 * user should not be immediately interrupted with a password prompt.
1269 *
1270 * <p>If a previously generated auth token is cached for this account and
1271 * type, then it is returned. Otherwise, if a saved password is
1272 * available, it is sent to the server to generate a new auth token.
1273 * Otherwise, an {@link Intent} is returned which, when started, will
1274 * prompt the user for a password. If the notifyAuthFailure parameter is
1275 * set, a status bar notification is also created with the same Intent,
1276 * alerting the user that they need to enter a password at some point.
1277 *
1278 * <p>In that case, you may need to wait until the user responds, which
1279 * could take hours or days or forever. When the user does respond and
1280 * supply a new password, the account manager will broadcast the
1281 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1282 * use to try again.
1283 *
1284 * <p>If notifyAuthFailure is not set, it is the application's
1285 * responsibility to launch the returned Intent at some point.
1286 * Either way, the result from this call will not wait for user action.
1287 *
1288 * <p>Some authenticators have auth token <em>types</em>, whose value
1289 * is authenticator-dependent. Some services use different token types to
1290 * access different functionality -- for example, Google uses different auth
1291 * tokens to access Gmail and Google Calendar for the same account.
1292 *
1293 * <p>This method may be called from any thread, but the returned
1294 * {@link AccountManagerFuture} must not be used on the main thread.
1295 *
Fred Quintanaad93a322011-09-08 13:21:01 -07001296 * @param account The account to fetch an auth token for
1297 * @param authTokenType The auth token type, an authenticator-dependent
1298 * string token, must not be null
1299 * @param options Authenticator-specific options for the request,
1300 * may be null or empty
1301 * @param notifyAuthFailure True to add a notification to prompt the
1302 * user for a password if necessary, false to leave that to the caller
1303 * @param callback Callback to invoke when the request completes,
1304 * null for no callback
1305 * @param handler {@link Handler} identifying the callback thread,
1306 * null for the main thread
1307 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1308 * at least the following fields on success:
1309 * <ul>
1310 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1311 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1312 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1313 * </ul>
1314 *
1315 * (Other authenticator-specific values may be returned.) If the user
1316 * must enter credentials, the returned Bundle contains only
1317 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1318 *
1319 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1320 * <ul>
1321 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1322 * <li> {@link OperationCanceledException} if the operation is canceled for
1323 * any reason, incluidng the user canceling a credential request
1324 * <li> {@link IOException} if the authenticator experienced an I/O problem
1325 * creating a new auth token, usually because of network trouble
1326 * </ul>
1327 * If the account is no longer present on the device, the return value is
1328 * authenticator-dependent. The caller should verify the validity of the
1329 * account before requesting an auth token.
1330 */
1331 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001332 final Account account, final String authTokenType, final Bundle options,
1333 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001334 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001335
Fred Quintanaad93a322011-09-08 13:21:01 -07001336 if (account == null) throw new IllegalArgumentException("account is null");
1337 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001338 final Bundle optionsIn = new Bundle();
1339 if (options != null) {
1340 optionsIn.putAll(options);
1341 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001342 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001343 return new AmsTask(null, handler, callback) {
1344 public void doWork() throws RemoteException {
1345 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001346 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001347 }
1348 }.start();
1349 }
1350
1351 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001352 * Asks the user to add an account of a specified type. The authenticator
1353 * for this account type processes this request with the appropriate user
1354 * interface. If the user does elect to create a new account, the account
1355 * name is returned.
1356 *
1357 * <p>This method may be called from any thread, but the returned
1358 * {@link AccountManagerFuture} must not be used on the main thread.
1359 *
Dan Egnor661f0132010-02-19 11:23:00 -08001360 * @param accountType The type of account to add; must not be null
1361 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1362 * this account will need to be able to generate, null for none
1363 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1364 * account must have, null for none
1365 * @param addAccountOptions Authenticator-specific options for the request,
1366 * may be null or empty
1367 * @param activity The {@link Activity} context to use for launching a new
1368 * authenticator-defined sub-Activity to prompt the user to create an
1369 * account; used only to call startActivity(); if null, the prompt
1370 * will not be launched directly, but the necessary {@link Intent}
1371 * will be returned to the caller instead
1372 * @param callback Callback to invoke when the request completes,
1373 * null for no callback
1374 * @param handler {@link Handler} identifying the callback thread,
1375 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001376 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001377 * these fields if activity was specified and an account was created:
1378 * <ul>
1379 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1380 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1381 * </ul>
1382 *
1383 * If no activity was specified, the returned Bundle contains only
1384 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001385 * actual account creation process. If an error occurred,
1386 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001387 * <ul>
1388 * <li> {@link AuthenticatorException} if no authenticator was registered for
1389 * this account type or the authenticator failed to respond
1390 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001391 * any reason, including the user canceling the creation process or adding accounts
1392 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001393 * <li> {@link IOException} if the authenticator experienced an I/O problem
1394 * creating a new account, usually because of network trouble
1395 * </ul>
1396 */
1397 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1398 final String authTokenType, final String[] requiredFeatures,
1399 final Bundle addAccountOptions,
1400 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001401 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001402 final Bundle optionsIn = new Bundle();
1403 if (addAccountOptions != null) {
1404 optionsIn.putAll(addAccountOptions);
1405 }
1406 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001407
Dan Egnor661f0132010-02-19 11:23:00 -08001408 return new AmsTask(activity, handler, callback) {
1409 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001410 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001411 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001412 }
1413 }.start();
1414 }
1415
1416 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001417 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1418 * @hide
1419 */
1420 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1421 final String authTokenType, final String[] requiredFeatures,
1422 final Bundle addAccountOptions, final Activity activity,
1423 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1424 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1425 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1426 final Bundle optionsIn = new Bundle();
1427 if (addAccountOptions != null) {
1428 optionsIn.putAll(addAccountOptions);
1429 }
1430 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1431
1432 return new AmsTask(activity, handler, callback) {
1433 public void doWork() throws RemoteException {
1434 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1435 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1436 }
1437 }.start();
1438 }
1439
1440 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001441 * Adds a shared account from the primary user to a secondary user. Adding the shared account
1442 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1443 * are attempted to be copied to the target user from the primary via calls to the
1444 * authenticator.
1445 * @param account the account to share
1446 * @param user the target user
1447 * @return
1448 * @hide
1449 */
1450 public boolean addSharedAccount(final Account account, UserHandle user) {
1451 try {
1452 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1453 return val;
1454 } catch (RemoteException re) {
1455 // won't ever happen
1456 throw new RuntimeException(re);
1457 }
1458 }
1459
1460 /**
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001461 * Copies an account from the primary user to another user.
1462 * @param account the account to copy
1463 * @param user the target user
1464 * @param callback Callback to invoke when the request completes,
1465 * null for no callback
1466 * @param handler {@link Handler} identifying the callback thread,
1467 * null for the main thread
1468 * @return An {@link AccountManagerFuture} which resolves to a Boolean indicated wether it
1469 * succeeded.
1470 * @hide
1471 */
1472 public AccountManagerFuture<Boolean> copyAccountToUser(
1473 final Account account, final UserHandle user,
1474 AccountManagerCallback<Boolean> callback, Handler handler) {
1475 if (account == null) throw new IllegalArgumentException("account is null");
1476 if (user == null) throw new IllegalArgumentException("user is null");
1477
1478 return new Future2Task<Boolean>(handler, callback) {
1479 @Override
1480 public void doWork() throws RemoteException {
1481 mService.copyAccountToUser(
1482 mResponse, account, UserHandle.USER_OWNER, user.getIdentifier());
1483 }
1484 @Override
1485 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
1486 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
1487 throw new AuthenticatorException("no result in response");
1488 }
1489 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
1490 }
1491 }.start();
1492 }
1493
1494 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001495 * @hide
1496 * Removes the shared account.
1497 * @param account the account to remove
1498 * @param user the user to remove the account from
1499 * @return
1500 */
1501 public boolean removeSharedAccount(final Account account, UserHandle user) {
1502 try {
1503 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1504 return val;
1505 } catch (RemoteException re) {
1506 // won't ever happen
1507 throw new RuntimeException(re);
1508 }
1509 }
1510
1511 /**
1512 * @hide
1513 * @param user
1514 * @return
1515 */
1516 public Account[] getSharedAccounts(UserHandle user) {
1517 try {
1518 return mService.getSharedAccountsAsUser(user.getIdentifier());
1519 } catch (RemoteException re) {
1520 // won't ever happen
1521 throw new RuntimeException(re);
1522 }
1523 }
1524
1525 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001526 * Confirms that the user knows the password for an account to make extra
1527 * sure they are the owner of the account. The user-entered password can
1528 * be supplied directly, otherwise the authenticator for this account type
1529 * prompts the user with the appropriate interface. This method is
1530 * intended for applications which want extra assurance; for example, the
1531 * phone lock screen uses this to let the user unlock the phone with an
1532 * account password if they forget the lock pattern.
1533 *
1534 * <p>If the user-entered password matches a saved password for this
1535 * account, the request is considered valid; otherwise the authenticator
1536 * verifies the password (usually by contacting the server).
1537 *
1538 * <p>This method may be called from any thread, but the returned
1539 * {@link AccountManagerFuture} must not be used on the main thread.
1540 *
Dan Egnor661f0132010-02-19 11:23:00 -08001541 * @param account The account to confirm password knowledge for
1542 * @param options Authenticator-specific options for the request;
1543 * if the {@link #KEY_PASSWORD} string field is present, the
1544 * authenticator may use it directly rather than prompting the user;
1545 * may be null or empty
1546 * @param activity The {@link Activity} context to use for launching a new
1547 * authenticator-defined sub-Activity to prompt the user to enter a
1548 * password; used only to call startActivity(); if null, the prompt
1549 * will not be launched directly, but the necessary {@link Intent}
1550 * will be returned to the caller instead
1551 * @param callback Callback to invoke when the request completes,
1552 * null for no callback
1553 * @param handler {@link Handler} identifying the callback thread,
1554 * null for the main thread
1555 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1556 * with these fields if activity or password was supplied and
1557 * the account was successfully verified:
1558 * <ul>
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001559 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account verified
Dan Egnor661f0132010-02-19 11:23:00 -08001560 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1561 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1562 * </ul>
1563 *
1564 * If no activity or password was specified, the returned Bundle contains
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001565 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
1566 * password prompt.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001567 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001568 * <p>Also the returning Bundle may contain {@link
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07001569 * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001570 * credential was validated/created.
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001571 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001572 * If an error occurred,{@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001573 * <ul>
1574 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1575 * <li> {@link OperationCanceledException} if the operation was canceled for
1576 * any reason, including the user canceling the password prompt
1577 * <li> {@link IOException} if the authenticator experienced an I/O problem
1578 * verifying the password, usually because of network trouble
1579 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001580 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001581 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1582 final Bundle options,
1583 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001584 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001585 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001586 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1587 Process.myUserHandle());
1588 }
1589
1590 /**
1591 * @hide
1592 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1593 * but for the specified user.
1594 */
1595 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1596 final Bundle options,
1597 final Activity activity,
1598 final AccountManagerCallback<Bundle> callback,
1599 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001600 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001601 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001602 return new AmsTask(activity, handler, callback) {
1603 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001604 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1605 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001606 }
Fred Quintana33269202009-04-20 16:05:10 -07001607 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001608 }
1609
Fred Quintana756b7352009-10-21 13:43:10 -07001610 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001611 * Asks the user to enter a new password for an account, updating the
1612 * saved credentials for the account. Normally this happens automatically
1613 * when the server rejects credentials during an auth token fetch, but this
1614 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001615 *
Dan Egnor661f0132010-02-19 11:23:00 -08001616 * <p>This method may be called from any thread, but the returned
1617 * {@link AccountManagerFuture} must not be used on the main thread.
1618 *
Dan Egnor661f0132010-02-19 11:23:00 -08001619 * @param account The account to update credentials for
1620 * @param authTokenType The credentials entered must allow an auth token
1621 * of this type to be created (but no actual auth token is returned);
1622 * may be null
1623 * @param options Authenticator-specific options for the request;
1624 * may be null or empty
1625 * @param activity The {@link Activity} context to use for launching a new
1626 * authenticator-defined sub-Activity to prompt the user to enter a
1627 * password; used only to call startActivity(); if null, the prompt
1628 * will not be launched directly, but the necessary {@link Intent}
1629 * will be returned to the caller instead
1630 * @param callback Callback to invoke when the request completes,
1631 * null for no callback
1632 * @param handler {@link Handler} identifying the callback thread,
1633 * null for the main thread
1634 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1635 * with these fields if an activity was supplied and the account
1636 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001637 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001638 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1639 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001640 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001641 *
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001642 * If no activity was specified, the returned Bundle contains
Dan Egnor661f0132010-02-19 11:23:00 -08001643 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001644 * password prompt. If an error occurred,
Dan Egnor8e4378b2010-08-02 18:22:09 -07001645 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001646 * <ul>
1647 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1648 * <li> {@link OperationCanceledException} if the operation was canceled for
1649 * any reason, including the user canceling the password prompt
1650 * <li> {@link IOException} if the authenticator experienced an I/O problem
1651 * verifying the password, usually because of network trouble
1652 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001653 */
1654 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1655 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001656 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001657 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001658 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001659 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001660 return new AmsTask(activity, handler, callback) {
1661 public void doWork() throws RemoteException {
1662 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001663 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001664 }
Fred Quintana33269202009-04-20 16:05:10 -07001665 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001666 }
1667
Fred Quintana756b7352009-10-21 13:43:10 -07001668 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001669 * Offers the user an opportunity to change an authenticator's settings.
1670 * These properties are for the authenticator in general, not a particular
1671 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001672 *
Dan Egnor661f0132010-02-19 11:23:00 -08001673 * <p>This method may be called from any thread, but the returned
1674 * {@link AccountManagerFuture} must not be used on the main thread.
1675 *
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001676 * <p>This method requires the caller to have the same signature as the
1677 * authenticator associated with the specified account type.
Dan Egnor661f0132010-02-19 11:23:00 -08001678 *
1679 * @param accountType The account type associated with the authenticator
1680 * to adjust
1681 * @param activity The {@link Activity} context to use for launching a new
1682 * authenticator-defined sub-Activity to adjust authenticator settings;
1683 * used only to call startActivity(); if null, the settings dialog will
1684 * not be launched directly, but the necessary {@link Intent} will be
1685 * returned to the caller instead
1686 * @param callback Callback to invoke when the request completes,
1687 * null for no callback
1688 * @param handler {@link Handler} identifying the callback thread,
1689 * null for the main thread
1690 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1691 * which is empty if properties were edited successfully, or
1692 * if no activity was specified, contains only {@link #KEY_INTENT}
1693 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001694 * If an error occurred, {@link AccountManagerFuture#getResult()}
1695 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001696 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001697 * <li> {@link AuthenticatorException} if no authenticator was registered for
1698 * this account type or the authenticator failed to respond
1699 * <li> {@link OperationCanceledException} if the operation was canceled for
1700 * any reason, including the user canceling the settings dialog
1701 * <li> {@link IOException} if the authenticator experienced an I/O problem
1702 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001703 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001704 */
1705 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1706 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001707 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001708 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001709 return new AmsTask(activity, handler, callback) {
1710 public void doWork() throws RemoteException {
1711 mService.editProperties(mResponse, accountType, activity != null);
1712 }
Fred Quintana33269202009-04-20 16:05:10 -07001713 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001714 }
1715
1716 private void ensureNotOnMainThread() {
1717 final Looper looper = Looper.myLooper();
1718 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001719 final IllegalStateException exception = new IllegalStateException(
1720 "calling this from your main thread can lead to deadlock");
1721 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1722 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001723 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1724 throw exception;
1725 }
Fred Quintana60307342009-03-24 22:48:12 -07001726 }
1727 }
1728
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001729 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1730 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001731 handler = handler == null ? mMainHandler : handler;
1732 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001733 public void run() {
1734 callback.run(future);
1735 }
1736 });
1737 }
Fred Quintana60307342009-03-24 22:48:12 -07001738
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001739 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001740 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001741 final Account[] accountsCopy = new Account[accounts.length];
1742 // send a copy to make sure that one doesn't
1743 // change what another sees
1744 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1745 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001746 handler.post(new Runnable() {
1747 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001748 try {
1749 listener.onAccountsUpdated(accountsCopy);
1750 } catch (SQLException e) {
1751 // Better luck next time. If the problem was disk-full,
1752 // the STORAGE_OK intent will re-trigger the update.
1753 Log.e(TAG, "Can't update accounts", e);
1754 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001755 }
1756 });
1757 }
1758
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001759 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001760 final IAccountManagerResponse mResponse;
1761 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001762 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001763 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001764 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001765 super(new Callable<Bundle>() {
1766 public Bundle call() throws Exception {
1767 throw new IllegalStateException("this should never be called");
1768 }
1769 });
1770
1771 mHandler = handler;
1772 mCallback = callback;
1773 mActivity = activity;
1774 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001775 }
1776
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001777 public final AccountManagerFuture<Bundle> start() {
1778 try {
1779 doWork();
1780 } catch (RemoteException e) {
1781 setException(e);
1782 }
Fred Quintana33269202009-04-20 16:05:10 -07001783 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001784 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001785
Fred Quintana96580e02010-03-04 13:42:42 -08001786 protected void set(Bundle bundle) {
1787 // TODO: somehow a null is being set as the result of the Future. Log this
1788 // case to help debug where this is occurring. When this bug is fixed this
1789 // condition statement should be removed.
1790 if (bundle == null) {
1791 Log.e(TAG, "the bundle must not be null", new Exception());
1792 }
1793 super.set(bundle);
1794 }
1795
Fred Quintanaa698f422009-04-08 19:14:54 -07001796 public abstract void doWork() throws RemoteException;
1797
1798 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1799 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001800 if (!isDone()) {
1801 ensureNotOnMainThread();
1802 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001803 try {
1804 if (timeout == null) {
1805 return get();
1806 } else {
1807 return get(timeout, unit);
1808 }
1809 } catch (CancellationException e) {
1810 throw new OperationCanceledException();
1811 } catch (TimeoutException e) {
1812 // fall through and cancel
1813 } catch (InterruptedException e) {
1814 // fall through and cancel
1815 } catch (ExecutionException e) {
1816 final Throwable cause = e.getCause();
1817 if (cause instanceof IOException) {
1818 throw (IOException) cause;
1819 } else if (cause instanceof UnsupportedOperationException) {
1820 throw new AuthenticatorException(cause);
1821 } else if (cause instanceof AuthenticatorException) {
1822 throw (AuthenticatorException) cause;
1823 } else if (cause instanceof RuntimeException) {
1824 throw (RuntimeException) cause;
1825 } else if (cause instanceof Error) {
1826 throw (Error) cause;
1827 } else {
1828 throw new IllegalStateException(cause);
1829 }
1830 } finally {
1831 cancel(true /* interrupt if running */);
1832 }
1833 throw new OperationCanceledException();
1834 }
1835
1836 public Bundle getResult()
1837 throws OperationCanceledException, IOException, AuthenticatorException {
1838 return internalGetResult(null, null);
1839 }
1840
1841 public Bundle getResult(long timeout, TimeUnit unit)
1842 throws OperationCanceledException, IOException, AuthenticatorException {
1843 return internalGetResult(timeout, unit);
1844 }
1845
1846 protected void done() {
1847 if (mCallback != null) {
1848 postToHandler(mHandler, mCallback, this);
1849 }
1850 }
1851
1852 /** Handles the responses from the AccountManager */
1853 private class Response extends IAccountManagerResponse.Stub {
1854 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07001855 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07001856 if (intent != null && mActivity != null) {
1857 // since the user provided an Activity we will silently start intents
1858 // that we see
1859 mActivity.startActivity(intent);
1860 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001861 } else if (bundle.getBoolean("retry")) {
1862 try {
1863 doWork();
1864 } catch (RemoteException e) {
1865 // this will only happen if the system process is dead, which means
1866 // we will be dying ourselves
1867 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001868 } else {
1869 set(bundle);
1870 }
1871 }
1872
1873 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001874 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1875 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1876 // the authenticator indicated that this request was canceled or we were
1877 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001878 cancel(true /* mayInterruptIfRunning */);
1879 return;
1880 }
1881 setException(convertErrorToException(code, message));
1882 }
1883 }
1884
Fred Quintana60307342009-03-24 22:48:12 -07001885 }
1886
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001887 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1888 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001889 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001890
1891 public BaseFutureTask(Handler handler) {
1892 super(new Callable<T>() {
1893 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001894 throw new IllegalStateException("this should never be called");
1895 }
1896 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001897 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001898 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001899 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001900
1901 public abstract void doWork() throws RemoteException;
1902
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001903 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001904
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001905 protected void postRunnableToHandler(Runnable runnable) {
1906 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1907 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001908 }
1909
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001910 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001911 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001912 doWork();
1913 } catch (RemoteException e) {
1914 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001915 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001916 }
1917
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001918 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001919 public void onResult(Bundle bundle) {
1920 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001921 T result = bundleToResult(bundle);
1922 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001923 return;
1924 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001925 set(result);
1926 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001927 } catch (ClassCastException e) {
1928 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001929 } catch (AuthenticatorException e) {
1930 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001931 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001932 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001933 }
1934
1935 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001936 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1937 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1938 // the authenticator indicated that this request was canceled or we were
1939 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001940 cancel(true /* mayInterruptIfRunning */);
1941 return;
1942 }
1943 setException(convertErrorToException(code, message));
1944 }
1945 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001946 }
1947
1948 private abstract class Future2Task<T>
1949 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1950 final AccountManagerCallback<T> mCallback;
1951 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1952 super(handler);
1953 mCallback = callback;
1954 }
1955
1956 protected void done() {
1957 if (mCallback != null) {
1958 postRunnableToHandler(new Runnable() {
1959 public void run() {
1960 mCallback.run(Future2Task.this);
1961 }
1962 });
1963 }
1964 }
1965
1966 public Future2Task<T> start() {
1967 startTask();
1968 return this;
1969 }
1970
1971 private T internalGetResult(Long timeout, TimeUnit unit)
1972 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001973 if (!isDone()) {
1974 ensureNotOnMainThread();
1975 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001976 try {
1977 if (timeout == null) {
1978 return get();
1979 } else {
1980 return get(timeout, unit);
1981 }
1982 } catch (InterruptedException e) {
1983 // fall through and cancel
1984 } catch (TimeoutException e) {
1985 // fall through and cancel
1986 } catch (CancellationException e) {
1987 // fall through and cancel
1988 } catch (ExecutionException e) {
1989 final Throwable cause = e.getCause();
1990 if (cause instanceof IOException) {
1991 throw (IOException) cause;
1992 } else if (cause instanceof UnsupportedOperationException) {
1993 throw new AuthenticatorException(cause);
1994 } else if (cause instanceof AuthenticatorException) {
1995 throw (AuthenticatorException) cause;
1996 } else if (cause instanceof RuntimeException) {
1997 throw (RuntimeException) cause;
1998 } else if (cause instanceof Error) {
1999 throw (Error) cause;
2000 } else {
2001 throw new IllegalStateException(cause);
2002 }
2003 } finally {
2004 cancel(true /* interrupt if running */);
2005 }
2006 throw new OperationCanceledException();
2007 }
2008
2009 public T getResult()
2010 throws OperationCanceledException, IOException, AuthenticatorException {
2011 return internalGetResult(null, null);
2012 }
2013
2014 public T getResult(long timeout, TimeUnit unit)
2015 throws OperationCanceledException, IOException, AuthenticatorException {
2016 return internalGetResult(timeout, unit);
2017 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002018
Fred Quintana60307342009-03-24 22:48:12 -07002019 }
2020
Fred Quintanaa698f422009-04-08 19:14:54 -07002021 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002022 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002023 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002024 }
Fred Quintana60307342009-03-24 22:48:12 -07002025
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002026 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07002027 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07002028 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002029
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002030 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07002031 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07002032 }
2033
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002034 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07002035 return new IllegalArgumentException(message);
2036 }
2037
2038 return new AuthenticatorException(message);
2039 }
2040
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002041 private class GetAuthTokenByTypeAndFeaturesTask
2042 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07002043 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
2044 final String[] features, Activity activityForPrompting,
2045 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002046 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002047 super(activityForPrompting, handler, callback);
2048 if (accountType == null) throw new IllegalArgumentException("account type is null");
2049 mAccountType = accountType;
2050 mAuthTokenType = authTokenType;
2051 mFeatures = features;
2052 mAddAccountOptions = addAccountOptions;
2053 mLoginOptions = loginOptions;
2054 mMyCallback = this;
2055 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002056 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002057 final String mAccountType;
2058 final String mAuthTokenType;
2059 final String[] mFeatures;
2060 final Bundle mAddAccountOptions;
2061 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002062 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002063 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002064
2065 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002066 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2067 new AccountManagerCallback<Account[]>() {
2068 public void run(AccountManagerFuture<Account[]> future) {
2069 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07002070 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002071 accounts = future.getResult();
2072 } catch (OperationCanceledException e) {
2073 setException(e);
2074 return;
2075 } catch (IOException e) {
2076 setException(e);
2077 return;
2078 } catch (AuthenticatorException e) {
2079 setException(e);
2080 return;
Fred Quintana33269202009-04-20 16:05:10 -07002081 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002082
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002083 mNumAccounts = accounts.length;
2084
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002085 if (accounts.length == 0) {
2086 if (mActivity != null) {
2087 // no accounts, add one now. pretend that the user directly
2088 // made this request
2089 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2090 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2091 } else {
2092 // send result since we can't prompt to add an account
2093 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002094 result.putString(KEY_ACCOUNT_NAME, null);
2095 result.putString(KEY_ACCOUNT_TYPE, null);
2096 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002097 try {
2098 mResponse.onResult(result);
2099 } catch (RemoteException e) {
2100 // this will never happen
2101 }
2102 // we are done
2103 }
2104 } else if (accounts.length == 1) {
2105 // have a single account, return an authtoken for it
2106 if (mActivity == null) {
2107 mFuture = getAuthToken(accounts[0], mAuthTokenType,
2108 false /* notifyAuthFailure */, mMyCallback, mHandler);
2109 } else {
2110 mFuture = getAuthToken(accounts[0],
2111 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002112 mActivity, mMyCallback, mHandler);
2113 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002114 } else {
2115 if (mActivity != null) {
2116 IAccountManagerResponse chooseResponse =
2117 new IAccountManagerResponse.Stub() {
2118 public void onResult(Bundle value) throws RemoteException {
2119 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002120 value.getString(KEY_ACCOUNT_NAME),
2121 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002122 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2123 mActivity, mMyCallback, mHandler);
2124 }
Fred Quintana33269202009-04-20 16:05:10 -07002125
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002126 public void onError(int errorCode, String errorMessage)
2127 throws RemoteException {
2128 mResponse.onError(errorCode, errorMessage);
2129 }
2130 };
2131 // have many accounts, launch the chooser
2132 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002133 ComponentName componentName = ComponentName.unflattenFromString(
2134 Resources.getSystem().getString(
2135 R.string.config_chooseAccountActivity));
2136 intent.setClassName(componentName.getPackageName(),
2137 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002138 intent.putExtra(KEY_ACCOUNTS, accounts);
2139 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002140 new AccountManagerResponse(chooseResponse));
2141 mActivity.startActivity(intent);
2142 // the result will arrive via the IAccountManagerResponse
2143 } else {
2144 // send result since we can't prompt to select an account
2145 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002146 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002147 try {
2148 mResponse.onResult(result);
2149 } catch (RemoteException e) {
2150 // this will never happen
2151 }
2152 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07002153 }
Fred Quintana33269202009-04-20 16:05:10 -07002154 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002155 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002156 }
2157
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002158 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002159 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002160 final Bundle result = future.getResult();
2161 if (mNumAccounts == 0) {
2162 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2163 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2164 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2165 setException(new AuthenticatorException("account not in result"));
2166 return;
2167 }
2168 final Account account = new Account(accountName, accountType);
2169 mNumAccounts = 1;
2170 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2171 mMyCallback, mHandler);
2172 return;
2173 }
2174 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002175 } catch (OperationCanceledException e) {
2176 cancel(true /* mayInterruptIfRUnning */);
2177 } catch (IOException e) {
2178 setException(e);
2179 } catch (AuthenticatorException e) {
2180 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002181 }
2182 }
2183 }
2184
Fred Quintana756b7352009-10-21 13:43:10 -07002185 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002186 * This convenience helper combines the functionality of
2187 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2188 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002189 *
Dan Egnor661f0132010-02-19 11:23:00 -08002190 * <p>This method gets a list of the accounts matching the
2191 * specified type and feature set; if there is exactly one, it is
2192 * used; if there are more than one, the user is prompted to pick one;
2193 * if there are none, the user is prompted to add one. Finally,
2194 * an auth token is acquired for the chosen account.
2195 *
2196 * <p>This method may be called from any thread, but the returned
2197 * {@link AccountManagerFuture} must not be used on the main thread.
2198 *
Dan Egnor661f0132010-02-19 11:23:00 -08002199 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08002200 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08002201 * @param authTokenType The desired auth token type
2202 * (see {@link #getAuthToken}), must not be null
2203 * @param features Required features for the account
2204 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2205 * @param activity The {@link Activity} context to use for launching new
2206 * sub-Activities to prompt to add an account, select an account,
2207 * and/or enter a password, as necessary; used only to call
2208 * startActivity(); should not be null
2209 * @param addAccountOptions Authenticator-specific options to use for
2210 * adding new accounts; may be null or empty
2211 * @param getAuthTokenOptions Authenticator-specific options to use for
2212 * getting auth tokens; may be null or empty
2213 * @param callback Callback to invoke when the request completes,
2214 * null for no callback
2215 * @param handler {@link Handler} identifying the callback thread,
2216 * null for the main thread
2217 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2218 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07002219 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002220 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2221 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2222 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07002223 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002224 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07002225 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002226 * <ul>
2227 * <li> {@link AuthenticatorException} if no authenticator was registered for
2228 * this account type or the authenticator failed to respond
2229 * <li> {@link OperationCanceledException} if the operation was canceled for
2230 * any reason, including the user canceling any operation
2231 * <li> {@link IOException} if the authenticator experienced an I/O problem
2232 * updating settings, usually because of network trouble
2233 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002234 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002235 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002236 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002237 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07002238 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002239 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002240 if (accountType == null) throw new IllegalArgumentException("account type is null");
2241 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002242 final GetAuthTokenByTypeAndFeaturesTask task =
2243 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002244 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002245 task.start();
2246 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002247 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002248
Fred Quintana1121bb52011-09-14 23:19:35 -07002249 /**
2250 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2251 * accounts.
2252 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002253 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002254 * <p>
2255 * On success the activity returns a Bundle with the account name and type specified using
2256 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2257 * <p>
2258 * The most common case is to call this with one account type, e.g.:
2259 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002260 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002261 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002262 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2263 * selected one, according to the caller's definition of selected.
2264 * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
2265 * shown. If not specified then this field will not limit the displayed accounts.
2266 * @param allowableAccountTypes an optional string array of account types. These are used
2267 * 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 -07002268 * when adding an account. If not specified then this field will not limit the displayed
2269 * account types when adding an account.
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002270 * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
2271 * it is only shown when there is more than one account from which to choose
Fred Quintanad88324d2011-09-19 11:43:05 -07002272 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002273 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002274 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2275 * authTokenType parameter
2276 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2277 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002278 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002279 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002280 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002281 */
2282 static public Intent newChooseAccountIntent(Account selectedAccount,
2283 ArrayList<Account> allowableAccounts,
2284 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002285 boolean alwaysPromptForAccount,
2286 String descriptionOverrideText,
2287 String addAccountAuthTokenType,
2288 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002289 Bundle addAccountOptions) {
2290 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002291 ComponentName componentName = ComponentName.unflattenFromString(
2292 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2293 intent.setClassName(componentName.getPackageName(),
2294 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002295 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
2296 allowableAccounts);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002297 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2298 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002299 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2300 addAccountOptions);
2301 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002302 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
2303 alwaysPromptForAccount);
2304 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2305 descriptionOverrideText);
2306 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2307 addAccountAuthTokenType);
2308 intent.putExtra(
2309 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2310 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002311 return intent;
2312 }
2313
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002314 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002315 Maps.newHashMap();
2316
Fred Quintanad9d2f112009-04-23 13:36:27 -07002317 /**
2318 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2319 * so that it can read the updated list of accounts and send them to the listener
2320 * in mAccountsUpdatedListeners.
2321 */
2322 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
2323 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002324 final Account[] accounts = getAccounts();
2325 // send the result to the listeners
2326 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002327 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002328 mAccountsUpdatedListeners.entrySet()) {
2329 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002330 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002331 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002332 }
2333 };
2334
2335 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002336 * Adds an {@link OnAccountsUpdateListener} to this instance of the
2337 * {@link AccountManager}. This listener will be notified whenever the
2338 * list of accounts on the device changes.
2339 *
2340 * <p>As long as this listener is present, the AccountManager instance
2341 * will not be garbage-collected, and neither will the {@link Context}
2342 * used to retrieve it, which may be a large Activity instance. To avoid
2343 * memory leaks, you must remove this listener before then. Normally
2344 * listeners are added in an Activity or Service's {@link Activity#onCreate}
2345 * and removed in {@link Activity#onDestroy}.
2346 *
2347 * <p>It is safe to call this method from the main thread.
2348 *
Nicolas Falliere9530e3a2012-06-18 17:21:06 -07002349 * <p>This method requires the caller to hold the permission
2350 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Dan Egnor661f0132010-02-19 11:23:00 -08002351 *
2352 * @param listener The listener to send notifications to
2353 * @param handler {@link Handler} identifying the thread to use
2354 * for notifications, null for the main thread
2355 * @param updateImmediately If true, the listener will be invoked
2356 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002357 * @throws IllegalArgumentException if listener is null
2358 * @throws IllegalStateException if listener was already added
2359 */
Tor Norbye80b530a2015-04-23 16:36:09 -07002360 @RequiresPermission(GET_ACCOUNTS)
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002361 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002362 Handler handler, boolean updateImmediately) {
2363 if (listener == null) {
2364 throw new IllegalArgumentException("the listener is null");
2365 }
2366 synchronized (mAccountsUpdatedListeners) {
2367 if (mAccountsUpdatedListeners.containsKey(listener)) {
2368 throw new IllegalStateException("this listener is already added");
2369 }
2370 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2371
2372 mAccountsUpdatedListeners.put(listener, handler);
2373
2374 if (wasEmpty) {
2375 // Register a broadcast receiver to monitor account changes
2376 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002377 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002378 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002379 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002380 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2381 }
2382 }
2383
2384 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002385 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002386 }
2387 }
2388
2389 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002390 * Removes an {@link OnAccountsUpdateListener} previously registered with
2391 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2392 * receive notifications of account changes.
2393 *
2394 * <p>It is safe to call this method from the main thread.
2395 *
2396 * <p>No permission is required to call this method.
2397 *
2398 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002399 * @throws IllegalArgumentException if listener is null
2400 * @throws IllegalStateException if listener was not already added
2401 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002402 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002403 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002404 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002405 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002406 Log.e(TAG, "Listener was not previously added");
2407 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002408 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002409 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002410 if (mAccountsUpdatedListeners.isEmpty()) {
2411 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2412 }
2413 }
2414 }
Fred Quintana60307342009-03-24 22:48:12 -07002415}