blob: 64c2fd0e3e114ce2ea10c4ddab438e6427e0fbfb [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
Fred Quintana60307342009-03-24 22:48:12 -070019import android.app.Activity;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080020import android.content.BroadcastReceiver;
Amith Yamasani12b8e132013-03-14 10:48:07 -070021import android.content.ComponentName;
Fred Quintana60307342009-03-24 22:48:12 -070022import android.content.Context;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080023import android.content.Intent;
Fred Quintanad9d2f112009-04-23 13:36:27 -070024import android.content.IntentFilter;
Amith Yamasani12b8e132013-03-14 10:48:07 -070025import android.content.res.Resources;
Costin Manolacheb6437242009-09-10 16:14:12 -070026import android.database.SQLException;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080027import android.os.Build;
Fred Quintanaa698f422009-04-08 19:14:54 -070028import android.os.Bundle;
29import android.os.Handler;
30import android.os.Looper;
Fred Quintana33269202009-04-20 16:05:10 -070031import android.os.Parcelable;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080032import android.os.Process;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080033import android.os.RemoteException;
Amith Yamasani2c7bc262012-11-05 16:46:02 -080034import android.os.UserHandle;
Fred Quintanaf0fd8432010-03-08 12:48:05 -080035import android.text.TextUtils;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080036import android.util.Log;
37
38import com.android.internal.R;
39import com.google.android.collect.Maps;
Fred Quintana60307342009-03-24 22:48:12 -070040
Fred Quintanaa698f422009-04-08 19:14:54 -070041import java.io.IOException;
Fred Quintana1121bb52011-09-14 23:19:35 -070042import java.util.ArrayList;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080043import java.util.HashMap;
44import java.util.Map;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import java.util.concurrent.Callable;
46import java.util.concurrent.CancellationException;
47import java.util.concurrent.ExecutionException;
48import java.util.concurrent.FutureTask;
Fred Quintanaa698f422009-04-08 19:14:54 -070049import java.util.concurrent.TimeUnit;
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -080050import java.util.concurrent.TimeoutException;
Fred Quintana60307342009-03-24 22:48:12 -070051
52/**
Dan Egnor661f0132010-02-19 11:23:00 -080053 * This class provides access to a centralized registry of the user's
Dan Egnor8e4378b2010-08-02 18:22:09 -070054 * online accounts. The user enters credentials (username and password) once
55 * per account, granting applications access to online resources with
56 * "one-click" approval.
Fred Quintana60307342009-03-24 22:48:12 -070057 *
Dan Egnor661f0132010-02-19 11:23:00 -080058 * <p>Different online services have different ways of handling accounts and
59 * authentication, so the account manager uses pluggable <em>authenticator</em>
Dan Egnor8e4378b2010-08-02 18:22:09 -070060 * modules for different <em>account types</em>. Authenticators (which may be
61 * written by third parties) handle the actual details of validating account
62 * credentials and storing account information. For example, Google, Facebook,
63 * and Microsoft Exchange each have their own authenticator.
Dan Egnor661f0132010-02-19 11:23:00 -080064 *
65 * <p>Many servers support some notion of an <em>authentication token</em>,
66 * which can be used to authenticate a request to the server without sending
67 * the user's actual password. (Auth tokens are normally created with a
68 * separate request which does include the user's credentials.) AccountManager
Dan Egnor8e4378b2010-08-02 18:22:09 -070069 * can generate auth tokens for applications, so the application doesn't need to
70 * handle passwords directly. Auth tokens are normally reusable and cached by
71 * AccountManager, but must be refreshed periodically. It's the responsibility
72 * of applications to <em>invalidate</em> auth tokens when they stop working so
73 * the AccountManager knows it needs to regenerate them.
Dan Egnor661f0132010-02-19 11:23:00 -080074 *
75 * <p>Applications accessing a server normally go through these steps:
76 *
77 * <ul>
78 * <li>Get an instance of AccountManager using {@link #get(Context)}.
79 *
80 * <li>List the available accounts using {@link #getAccountsByType} or
81 * {@link #getAccountsByTypeAndFeatures}. Normally applications will only
82 * be interested in accounts with one particular <em>type</em>, which
83 * identifies the authenticator. Account <em>features</em> are used to
84 * identify particular account subtypes and capabilities. Both the account
85 * type and features are authenticator-specific strings, and must be known by
86 * the application in coordination with its preferred authenticators.
87 *
88 * <li>Select one or more of the available accounts, possibly by asking the
89 * user for their preference. If no suitable accounts are available,
90 * {@link #addAccount} may be called to prompt the user to create an
91 * account of the appropriate type.
92 *
Dan Egnor8e4378b2010-08-02 18:22:09 -070093 * <li><b>Important:</b> If the application is using a previously remembered
94 * account selection, it must make sure the account is still in the list
95 * of accounts returned by {@link #getAccountsByType}. Requesting an auth token
96 * for an account no longer on the device results in an undefined failure.
97 *
Dan Egnor661f0132010-02-19 11:23:00 -080098 * <li>Request an auth token for the selected account(s) using one of the
99 * {@link #getAuthToken} methods or related helpers. Refer to the description
100 * of each method for exact usage and error handling details.
101 *
102 * <li>Make the request using the auth token. The form of the auth token,
103 * the format of the request, and the protocol used are all specific to the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700104 * service you are accessing. The application may use whatever network and
105 * protocol libraries are useful.
Dan Egnor661f0132010-02-19 11:23:00 -0800106 *
107 * <li><b>Important:</b> If the request fails with an authentication error,
108 * it could be that a cached auth token is stale and no longer honored by
109 * the server. The application must call {@link #invalidateAuthToken} to remove
110 * the token from the cache, otherwise requests will continue failing! After
111 * invalidating the auth token, immediately go back to the "Request an auth
112 * token" step above. If the process fails the second time, then it can be
113 * treated as a "genuine" authentication failure and the user notified or other
114 * appropriate actions taken.
115 * </ul>
116 *
Dan Egnor8e4378b2010-08-02 18:22:09 -0700117 * <p>Some AccountManager methods may need to interact with the user to
Dan Egnor661f0132010-02-19 11:23:00 -0800118 * prompt for credentials, present options, or ask the user to add an account.
119 * The caller may choose whether to allow AccountManager to directly launch the
120 * necessary user interface and wait for the user, or to return an Intent which
121 * the caller may use to launch the interface, or (in some cases) to install a
122 * notification which the user can select at any time to launch the interface.
123 * To have AccountManager launch the interface directly, the caller must supply
124 * the current foreground {@link Activity} context.
125 *
126 * <p>Many AccountManager methods take {@link AccountManagerCallback} and
Dan Egnor8e4378b2010-08-02 18:22:09 -0700127 * {@link Handler} as parameters. These methods return immediately and
Dan Egnor661f0132010-02-19 11:23:00 -0800128 * run asynchronously. If a callback is provided then
129 * {@link AccountManagerCallback#run} will be invoked on the Handler's
130 * thread when the request completes, successfully or not.
Dan Egnor8e4378b2010-08-02 18:22:09 -0700131 * The result is retrieved by calling {@link AccountManagerFuture#getResult()}
132 * on the {@link AccountManagerFuture} returned by the method (and also passed
133 * to the callback). This method waits for the operation to complete (if
134 * necessary) and either returns the result or throws an exception if an error
135 * occurred during the operation. To make the request synchronously, call
Dan Egnor661f0132010-02-19 11:23:00 -0800136 * {@link AccountManagerFuture#getResult()} immediately on receiving the
Dan Egnor8e4378b2010-08-02 18:22:09 -0700137 * future from the method; no callback need be supplied.
Dan Egnor661f0132010-02-19 11:23:00 -0800138 *
139 * <p>Requests which may block, including
140 * {@link AccountManagerFuture#getResult()}, must never be called on
141 * the application's main event thread. These operations throw
142 * {@link IllegalStateException} if they are used on the main thread.
Fred Quintana60307342009-03-24 22:48:12 -0700143 */
144public class AccountManager {
145 private static final String TAG = "AccountManager";
146
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700147 public static final int ERROR_CODE_REMOTE_EXCEPTION = 1;
148 public static final int ERROR_CODE_NETWORK_ERROR = 3;
149 public static final int ERROR_CODE_CANCELED = 4;
150 public static final int ERROR_CODE_INVALID_RESPONSE = 5;
151 public static final int ERROR_CODE_UNSUPPORTED_OPERATION = 6;
152 public static final int ERROR_CODE_BAD_ARGUMENTS = 7;
153 public static final int ERROR_CODE_BAD_REQUEST = 8;
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700154 public static final int ERROR_CODE_BAD_AUTHENTICATION = 9;
Fred Quintana756b7352009-10-21 13:43:10 -0700155
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800156 /** @hide */
157 public static final int ERROR_CODE_USER_RESTRICTED = 100;
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100158 /** @hide */
159 public static final int ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE = 101;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800160
Dan Egnor661f0132010-02-19 11:23:00 -0800161 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700162 * Bundle key used for the {@link String} account name in results
Dan Egnor661f0132010-02-19 11:23:00 -0800163 * from methods which return information about a particular account.
164 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700165 public static final String KEY_ACCOUNT_NAME = "authAccount";
Dan Egnor661f0132010-02-19 11:23:00 -0800166
167 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700168 * Bundle key used for the {@link String} account type in results
Dan Egnor661f0132010-02-19 11:23:00 -0800169 * from methods which return information about a particular account.
170 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700171 public static final String KEY_ACCOUNT_TYPE = "accountType";
Dan Egnor661f0132010-02-19 11:23:00 -0800172
173 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700174 * Bundle key used for the auth token value in results
Dan Egnor661f0132010-02-19 11:23:00 -0800175 * from {@link #getAuthToken} and friends.
176 */
177 public static final String KEY_AUTHTOKEN = "authtoken";
178
179 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700180 * Bundle key used for an {@link Intent} in results from methods that
Dan Egnor661f0132010-02-19 11:23:00 -0800181 * may require the caller to interact with the user. The Intent can
182 * be used to start the corresponding user interface activity.
183 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700184 public static final String KEY_INTENT = "intent";
Dan Egnor661f0132010-02-19 11:23:00 -0800185
186 /**
Dan Egnor8e4378b2010-08-02 18:22:09 -0700187 * Bundle key used to supply the password directly in options to
Dan Egnor661f0132010-02-19 11:23:00 -0800188 * {@link #confirmCredentials}, rather than prompting the user with
189 * the standard password prompt.
190 */
191 public static final String KEY_PASSWORD = "password";
192
193 public static final String KEY_ACCOUNTS = "accounts";
Brian Carlstrom46703b02011-04-06 15:41:29 -0700194
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700195 public static final String KEY_ACCOUNT_AUTHENTICATOR_RESPONSE = "accountAuthenticatorResponse";
196 public static final String KEY_ACCOUNT_MANAGER_RESPONSE = "accountManagerResponse";
Dan Egnor661f0132010-02-19 11:23:00 -0800197 public static final String KEY_AUTHENTICATOR_TYPES = "authenticator_types";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700198 public static final String KEY_AUTH_FAILED_MESSAGE = "authFailedMessage";
199 public static final String KEY_AUTH_TOKEN_LABEL = "authTokenLabelKey";
Dan Egnor661f0132010-02-19 11:23:00 -0800200 public static final String KEY_BOOLEAN_RESULT = "booleanResult";
201 public static final String KEY_ERROR_CODE = "errorCode";
202 public static final String KEY_ERROR_MESSAGE = "errorMessage";
203 public static final String KEY_USERDATA = "userdata";
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700204
Costin Manolachea40c6302010-12-13 14:50:45 -0800205 /**
206 * Authenticators using 'customTokens' option will also get the UID of the
207 * caller
208 */
209 public static final String KEY_CALLER_UID = "callerUid";
210 public static final String KEY_CALLER_PID = "callerPid";
Dan Egnor661f0132010-02-19 11:23:00 -0800211
Costin Manolached6060452011-01-24 16:11:36 -0800212 /**
Fred Quintanaad93a322011-09-08 13:21:01 -0700213 * The Android package of the caller will be set in the options bundle by the
214 * {@link AccountManager} and will be passed to the AccountManagerService and
215 * to the AccountAuthenticators. The uid of the caller will be known by the
216 * AccountManagerService as well as the AccountAuthenticators so they will be able to
217 * verify that the package is consistent with the uid (a uid might be shared by many
218 * packages).
219 */
220 public static final String KEY_ANDROID_PACKAGE_NAME = "androidPackageName";
221
222 /**
Costin Manolached6060452011-01-24 16:11:36 -0800223 * Boolean, if set and 'customTokens' the authenticator is responsible for
224 * notifications.
225 * @hide
226 */
227 public static final String KEY_NOTIFY_ON_FAILURE = "notifyOnAuthFailure";
228
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700229 public static final String ACTION_AUTHENTICATOR_INTENT =
230 "android.accounts.AccountAuthenticator";
231 public static final String AUTHENTICATOR_META_DATA_NAME =
Dan Egnor661f0132010-02-19 11:23:00 -0800232 "android.accounts.AccountAuthenticator";
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700233 public static final String AUTHENTICATOR_ATTRIBUTES_NAME = "account-authenticator";
234
Fred Quintana60307342009-03-24 22:48:12 -0700235 private final Context mContext;
236 private final IAccountManager mService;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700237 private final Handler mMainHandler;
Dan Egnor661f0132010-02-19 11:23:00 -0800238
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700239 /**
240 * Action sent as a broadcast Intent by the AccountsService
Dan Egnor661f0132010-02-19 11:23:00 -0800241 * when accounts are added, accounts are removed, or an
242 * account's credentials (saved password, etc) are changed.
243 *
244 * @see #addOnAccountsUpdatedListener
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700245 */
246 public static final String LOGIN_ACCOUNTS_CHANGED_ACTION =
247 "android.accounts.LOGIN_ACCOUNTS_CHANGED";
Fred Quintana60307342009-03-24 22:48:12 -0700248
Fred Quintana33269202009-04-20 16:05:10 -0700249 /**
250 * @hide
251 */
Fred Quintana60307342009-03-24 22:48:12 -0700252 public AccountManager(Context context, IAccountManager service) {
253 mContext = context;
254 mService = service;
Fred Quintanad9d2f112009-04-23 13:36:27 -0700255 mMainHandler = new Handler(mContext.getMainLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700256 }
257
Fred Quintana0eabf022009-04-27 15:08:17 -0700258 /**
259 * @hide used for testing only
260 */
261 public AccountManager(Context context, IAccountManager service, Handler handler) {
262 mContext = context;
263 mService = service;
264 mMainHandler = handler;
265 }
266
Fred Quintana756b7352009-10-21 13:43:10 -0700267 /**
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800268 * @hide for internal use only
269 */
270 public static Bundle sanitizeResult(Bundle result) {
Fred Quintana382601f2010-03-25 12:25:10 -0700271 if (result != null) {
272 if (result.containsKey(KEY_AUTHTOKEN)
273 && !TextUtils.isEmpty(result.getString(KEY_AUTHTOKEN))) {
274 final Bundle newResult = new Bundle(result);
275 newResult.putString(KEY_AUTHTOKEN, "<omitted for logging purposes>");
276 return newResult;
277 }
Fred Quintanaf0fd8432010-03-08 12:48:05 -0800278 }
279 return result;
280 }
281
282 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800283 * Gets an AccountManager instance associated with a Context.
284 * The {@link Context} will be used as long as the AccountManager is
285 * active, so make sure to use a {@link Context} whose lifetime is
286 * commensurate with any listeners registered to
287 * {@link #addOnAccountsUpdatedListener} or similar methods.
288 *
289 * <p>It is safe to call this method from the main thread.
290 *
291 * <p>No permission is required to call this method.
292 *
Fred Quintana756b7352009-10-21 13:43:10 -0700293 * @param context The {@link Context} to use when necessary
Dan Egnor661f0132010-02-19 11:23:00 -0800294 * @return An {@link AccountManager} instance
Fred Quintana756b7352009-10-21 13:43:10 -0700295 */
Fred Quintanaa698f422009-04-08 19:14:54 -0700296 public static AccountManager get(Context context) {
Fred Quintana382601f2010-03-25 12:25:10 -0700297 if (context == null) throw new IllegalArgumentException("context is null");
Fred Quintanaa698f422009-04-08 19:14:54 -0700298 return (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
299 }
300
Fred Quintana756b7352009-10-21 13:43:10 -0700301 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800302 * Gets the saved password associated with the account.
303 * This is intended for authenticators and related code; applications
304 * should get an auth token instead.
305 *
306 * <p>It is safe to call this method from the main thread.
307 *
308 * <p>This method requires the caller to hold the permission
309 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
310 * and to have the same UID as the account's authenticator.
311 *
312 * @param account The account to query for a password
313 * @return The account's password, null if none or if the account doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700314 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700315 public String getPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700316 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana60307342009-03-24 22:48:12 -0700317 try {
318 return mService.getPassword(account);
319 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700320 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700321 throw new RuntimeException(e);
322 }
323 }
324
Fred Quintana756b7352009-10-21 13:43:10 -0700325 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800326 * Gets the user data named by "key" associated with the account.
327 * This is intended for authenticators and related code to store
328 * arbitrary metadata along with accounts. The meaning of the keys
329 * and values is up to the authenticator for the account.
330 *
331 * <p>It is safe to call this method from the main thread.
332 *
333 * <p>This method requires the caller to hold the permission
334 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
335 * and to have the same UID as the account's authenticator.
336 *
337 * @param account The account to query for user data
338 * @return The user data, null if the account or key doesn't exist
Fred Quintana756b7352009-10-21 13:43:10 -0700339 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700340 public String getUserData(final Account account, final String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700341 if (account == null) throw new IllegalArgumentException("account is null");
342 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintana60307342009-03-24 22:48:12 -0700343 try {
344 return mService.getUserData(account, key);
345 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700346 // will never happen
Fred Quintana60307342009-03-24 22:48:12 -0700347 throw new RuntimeException(e);
348 }
349 }
350
Fred Quintana756b7352009-10-21 13:43:10 -0700351 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800352 * Lists the currently registered authenticators.
353 *
354 * <p>It is safe to call this method from the main thread.
355 *
356 * <p>No permission is required to call this method.
357 *
358 * @return An array of {@link AuthenticatorDescription} for every
359 * authenticator known to the AccountManager service. Empty (never
360 * null) if no authenticators are known.
Fred Quintana756b7352009-10-21 13:43:10 -0700361 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700362 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintanaa698f422009-04-08 19:14:54 -0700363 try {
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100364 return mService.getAuthenticatorTypes(UserHandle.getCallingUserId());
365 } catch (RemoteException e) {
366 // will never happen
367 throw new RuntimeException(e);
368 }
369 }
370
371 /**
372 * @hide
373 * Lists the currently registered authenticators for a given user id.
374 *
375 * <p>It is safe to call this method from the main thread.
376 *
377 * <p>The caller has to be in the same user or have the permission
378 * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
379 *
380 * @return An array of {@link AuthenticatorDescription} for every
381 * authenticator known to the AccountManager service. Empty (never
382 * null) if no authenticators are known.
383 */
384 public AuthenticatorDescription[] getAuthenticatorTypesAsUser(int userId) {
385 try {
386 return mService.getAuthenticatorTypes(userId);
Fred Quintanaa698f422009-04-08 19:14:54 -0700387 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700388 // will never happen
Fred Quintanaa698f422009-04-08 19:14:54 -0700389 throw new RuntimeException(e);
390 }
391 }
392
Fred Quintana756b7352009-10-21 13:43:10 -0700393 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800394 * Lists all accounts of any type registered on the device.
395 * Equivalent to getAccountsByType(null).
396 *
397 * <p>It is safe to call this method from the main thread.
398 *
399 * <p>This method requires the caller to hold the permission
400 * {@link android.Manifest.permission#GET_ACCOUNTS}.
401 *
402 * @return An array of {@link Account}, one for each account. Empty
403 * (never null) if no accounts have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700404 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700405 public Account[] getAccounts() {
Fred Quintana60307342009-03-24 22:48:12 -0700406 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700407 return mService.getAccounts(null);
Fred Quintana60307342009-03-24 22:48:12 -0700408 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700409 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700410 throw new RuntimeException(e);
411 }
412 }
413
Fred Quintana756b7352009-10-21 13:43:10 -0700414 /**
Amith Yamasani27db4682013-03-30 17:07:47 -0700415 * @hide
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100416 * Lists all accounts of any type registered on the device for a given
417 * user id. Equivalent to getAccountsByType(null).
418 *
419 * <p>It is safe to call this method from the main thread.
420 *
421 * <p>This method requires the caller to hold the permission
422 * {@link android.Manifest.permission#GET_ACCOUNTS}.
423 *
424 * @return An array of {@link Account}, one for each account. Empty
425 * (never null) if no accounts have been added.
426 */
427 public Account[] getAccountsAsUser(int userId) {
428 try {
429 return mService.getAccountsAsUser(null, userId);
430 } catch (RemoteException e) {
431 // won't ever happen
432 throw new RuntimeException(e);
433 }
434 }
435
436 /**
437 * @hide
Amith Yamasani27db4682013-03-30 17:07:47 -0700438 * For use by internal activities. Returns the list of accounts that the calling package
439 * is authorized to use, particularly for shared accounts.
440 * @param packageName package name of the calling app.
441 * @param uid the uid of the calling app.
442 * @return the accounts that are available to this package and user.
443 */
444 public Account[] getAccountsForPackage(String packageName, int uid) {
445 try {
446 return mService.getAccountsForPackage(packageName, uid);
447 } catch (RemoteException re) {
448 // possible security exception
449 throw new RuntimeException(re);
450 }
451 }
452
453 /**
Amith Yamasani3b458ad2013-04-18 18:40:07 -0700454 * Returns the accounts visible to the specified package, in an environment where some apps
455 * are not authorized to view all accounts. This method can only be called by system apps.
456 * @param type The type of accounts to return, null to retrieve all accounts
457 * @param packageName The package name of the app for which the accounts are to be returned
458 * @return An array of {@link Account}, one per matching account. Empty
459 * (never null) if no accounts of the specified type have been added.
460 */
461 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
462 try {
463 return mService.getAccountsByTypeForPackage(type, packageName);
464 } catch (RemoteException re) {
465 // possible security exception
466 throw new RuntimeException(re);
467 }
468 }
469
470 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800471 * Lists all accounts of a particular type. The account type is a
472 * string token corresponding to the authenticator and useful domain
473 * of the account. For example, there are types corresponding to Google
474 * and Facebook. The exact string token to use will be published somewhere
475 * associated with the authenticator in question.
476 *
477 * <p>It is safe to call this method from the main thread.
478 *
479 * <p>This method requires the caller to hold the permission
480 * {@link android.Manifest.permission#GET_ACCOUNTS}.
481 *
482 * @param type The type of accounts to return, null to retrieve all accounts
483 * @return An array of {@link Account}, one per matching account. Empty
484 * (never null) if no accounts of the specified type have been added.
Fred Quintana756b7352009-10-21 13:43:10 -0700485 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700486 public Account[] getAccountsByType(String type) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800487 return getAccountsByTypeAsUser(type, Process.myUserHandle());
488 }
489
490 /** @hide Same as {@link #getAccountsByType(String)} but for a specific user. */
491 public Account[] getAccountsByTypeAsUser(String type, UserHandle userHandle) {
Fred Quintana60307342009-03-24 22:48:12 -0700492 try {
Amith Yamasani2c7bc262012-11-05 16:46:02 -0800493 return mService.getAccountsAsUser(type, userHandle.getIdentifier());
Fred Quintana60307342009-03-24 22:48:12 -0700494 } catch (RemoteException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700495 // won't ever happen
Fred Quintana60307342009-03-24 22:48:12 -0700496 throw new RuntimeException(e);
497 }
498 }
499
Fred Quintana756b7352009-10-21 13:43:10 -0700500 /**
Fred Quintanad9640ec2012-05-23 12:37:00 -0700501 * Change whether or not an app (identified by its uid) is allowed to retrieve an authToken
502 * for an account.
503 * <p>
504 * This is only meant to be used by system activities and is not in the SDK.
505 * @param account The account whose permissions are being modified
506 * @param authTokenType The type of token whose permissions are being modified
507 * @param uid The uid that identifies the app which is being granted or revoked permission.
508 * @param value true is permission is being granted, false for revoked
509 * @hide
510 */
511 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value) {
512 try {
513 mService.updateAppPermission(account, authTokenType, uid, value);
514 } catch (RemoteException e) {
515 // won't ever happen
516 throw new RuntimeException(e);
517 }
518 }
519
520 /**
521 * Get the user-friendly label associated with an authenticator's auth token.
522 * @param accountType the type of the authenticator. must not be null.
523 * @param authTokenType the token type. must not be null.
524 * @param callback callback to invoke when the result is available. may be null.
525 * @param handler the handler on which to invoke the callback, or null for the main thread
526 * @return a future containing the label string
527 * @hide
528 */
529 public AccountManagerFuture<String> getAuthTokenLabel(
530 final String accountType, final String authTokenType,
531 AccountManagerCallback<String> callback, Handler handler) {
532 if (accountType == null) throw new IllegalArgumentException("accountType is null");
533 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
534 return new Future2Task<String>(handler, callback) {
535 public void doWork() throws RemoteException {
536 mService.getAuthTokenLabel(mResponse, accountType, authTokenType);
537 }
538
539 @Override
540 public String bundleToResult(Bundle bundle) throws AuthenticatorException {
541 if (!bundle.containsKey(KEY_AUTH_TOKEN_LABEL)) {
542 throw new AuthenticatorException("no result in response");
543 }
544 return bundle.getString(KEY_AUTH_TOKEN_LABEL);
545 }
546 }.start();
547 }
548
549 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800550 * Finds out whether a particular account has all the specified features.
551 * Account features are authenticator-specific string tokens identifying
552 * boolean account properties. For example, features are used to tell
553 * whether Google accounts have a particular service (such as Google
554 * Calendar or Google Talk) enabled. The feature names and their meanings
555 * are published somewhere associated with the authenticator in question.
556 *
557 * <p>This method may be called from any thread, but the returned
558 * {@link AccountManagerFuture} must not be used on the main thread.
559 *
560 * <p>This method requires the caller to hold the permission
561 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800562 *
563 * @param account The {@link Account} to test
Dan Egnor661f0132010-02-19 11:23:00 -0800564 * @param features An array of the account features to check
565 * @param callback Callback to invoke when the request completes,
566 * null for no callback
567 * @param handler {@link Handler} identifying the callback thread,
568 * null for the main thread
569 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
570 * true if the account exists and has all of the specified features.
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800571 */
Fred Quintana3084a6f2010-01-14 18:02:03 -0800572 public AccountManagerFuture<Boolean> hasFeatures(final Account account,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800573 final String[] features,
574 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700575 if (account == null) throw new IllegalArgumentException("account is null");
576 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800577 return new Future2Task<Boolean>(handler, callback) {
578 public void doWork() throws RemoteException {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800579 mService.hasFeatures(mResponse, account, features);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800580 }
581 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
582 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
583 throw new AuthenticatorException("no result in response");
584 }
585 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
586 }
587 }.start();
588 }
589
590 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800591 * Lists all accounts of a type which have certain features. The account
592 * type identifies the authenticator (see {@link #getAccountsByType}).
593 * Account features are authenticator-specific string tokens identifying
594 * boolean account properties (see {@link #hasFeatures}).
Fred Quintana756b7352009-10-21 13:43:10 -0700595 *
Dan Egnor661f0132010-02-19 11:23:00 -0800596 * <p>Unlike {@link #getAccountsByType}, this method calls the authenticator,
597 * which may contact the server or do other work to check account features,
598 * so the method returns an {@link AccountManagerFuture}.
Fred Quintanaa698f422009-04-08 19:14:54 -0700599 *
Dan Egnor661f0132010-02-19 11:23:00 -0800600 * <p>This method may be called from any thread, but the returned
601 * {@link AccountManagerFuture} must not be used on the main thread.
Fred Quintana756b7352009-10-21 13:43:10 -0700602 *
Dan Egnor661f0132010-02-19 11:23:00 -0800603 * <p>This method requires the caller to hold the permission
604 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Fred Quintana756b7352009-10-21 13:43:10 -0700605 *
Dan Egnor661f0132010-02-19 11:23:00 -0800606 * @param type The type of accounts to return, must not be null
607 * @param features An array of the account features to require,
608 * may be null or empty
609 * @param callback Callback to invoke when the request completes,
610 * null for no callback
611 * @param handler {@link Handler} identifying the callback thread,
612 * null for the main thread
613 * @return An {@link AccountManagerFuture} which resolves to an array of
614 * {@link Account}, one per account of the specified type which
615 * matches the requested features.
Fred Quintana8570f742010-02-18 10:32:54 -0800616 */
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700617 public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
618 final String type, final String[] features,
619 AccountManagerCallback<Account[]> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700620 if (type == null) throw new IllegalArgumentException("type is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700621 return new Future2Task<Account[]>(handler, callback) {
622 public void doWork() throws RemoteException {
623 mService.getAccountsByFeatures(mResponse, type, features);
624 }
625 public Account[] bundleToResult(Bundle bundle) throws AuthenticatorException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700626 if (!bundle.containsKey(KEY_ACCOUNTS)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700627 throw new AuthenticatorException("no result in response");
628 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700629 final Parcelable[] parcelables = bundle.getParcelableArray(KEY_ACCOUNTS);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700630 Account[] descs = new Account[parcelables.length];
631 for (int i = 0; i < parcelables.length; i++) {
632 descs[i] = (Account) parcelables[i];
633 }
634 return descs;
635 }
636 }.start();
637 }
638
Fred Quintana756b7352009-10-21 13:43:10 -0700639 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800640 * Adds an account directly to the AccountManager. Normally used by sign-up
641 * wizards associated with authenticators, not directly by applications.
Fred Quintana756b7352009-10-21 13:43:10 -0700642 *
Dan Egnor661f0132010-02-19 11:23:00 -0800643 * <p>It is safe to call this method from the main thread.
644 *
645 * <p>This method requires the caller to hold the permission
646 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
647 * and to have the same UID as the added account's authenticator.
648 *
649 * @param account The {@link Account} to add
650 * @param password The password to associate with the account, null for none
651 * @param userdata String values to use for the account's userdata, null for none
Dan Egnor8e4378b2010-08-02 18:22:09 -0700652 * @return True if the account was successfully added, false if the account
Dan Egnor661f0132010-02-19 11:23:00 -0800653 * already exists, the account is null, or another error occurs.
654 */
655 public boolean addAccountExplicitly(Account account, String password, Bundle userdata) {
Fred Quintana382601f2010-03-25 12:25:10 -0700656 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800657 try {
Amith Yamasani27db4682013-03-30 17:07:47 -0700658 return mService.addAccountExplicitly(account, password, userdata);
Dan Egnor661f0132010-02-19 11:23:00 -0800659 } catch (RemoteException e) {
660 // won't ever happen
661 throw new RuntimeException(e);
662 }
663 }
664
665 /**
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700666 * Rename the specified {@link Account}. This is equivalent to removing
667 * the existing account and adding a new renamed account with the old
668 * account's user data.
669 *
670 * <p>It is safe to call this method from the main thread.
671 *
672 * <p>This method requires the caller to hold the permission
673 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
674 * and have the same UID as the account's authenticator.
675 *
676 * @param account The {@link Account} to rename
677 * @param newName String name to be associated with the account.
678 * @param callback Callback to invoke when the request completes, null for
679 * no callback
680 * @param handler {@link Handler} identifying the callback thread, null for
681 * the main thread
682 * @return An {@link AccountManagerFuture} which resolves to the Account
683 * after the name change. If successful the account's name will be the
684 * specified new name.
685 */
686 public AccountManagerFuture<Account> renameAccount(
687 final Account account,
688 final String newName,
689 AccountManagerCallback<Account> callback,
690 Handler handler) {
691 if (account == null) throw new IllegalArgumentException("account is null.");
692 if (TextUtils.isEmpty(newName)) {
693 throw new IllegalArgumentException("newName is empty or null.");
694 }
695 return new Future2Task<Account>(handler, callback) {
696 @Override
697 public void doWork() throws RemoteException {
698 mService.renameAccount(mResponse, account, newName);
699 }
700 @Override
701 public Account bundleToResult(Bundle bundle) throws AuthenticatorException {
702 String name = bundle.getString(KEY_ACCOUNT_NAME);
703 String type = bundle.getString(KEY_ACCOUNT_TYPE);
704 return new Account(name, type);
705 }
706 }.start();
707 }
708
709 /**
710 * Gets the previous name associated with the account or {@code null}, if
711 * none. This is intended so that clients of {@link
712 * #LOGIN_ACCOUNTS_CHANGED_ACTION} broadcasts can determine if an
713 * authenticator has renamed an account.
714 *
715 * <p>It is safe to call this method from the main thread.
716 *
717 * @param account The account to query for a previous name.
718 * @return The account's previous name, null if the account has never been
719 * renamed.
720 */
721 public String getPreviousName(final Account account) {
722 if (account == null) throw new IllegalArgumentException("account is null");
723 try {
724 return mService.getPreviousName(account);
725 } catch (RemoteException e) {
726 // will never happen
727 throw new RuntimeException(e);
728 }
729 }
730
731 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800732 * Removes an account from the AccountManager. Does nothing if the account
733 * does not exist. Does not delete the account from the server.
734 * The authenticator may have its own policies preventing account
735 * deletion, in which case the account will not be deleted.
736 *
737 * <p>This method may be called from any thread, but the returned
738 * {@link AccountManagerFuture} must not be used on the main thread.
739 *
740 * <p>This method requires the caller to hold the permission
741 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
742 *
743 * @param account The {@link Account} to remove
744 * @param callback Callback to invoke when the request completes,
745 * null for no callback
746 * @param handler {@link Handler} identifying the callback thread,
747 * null for the main thread
748 * @return An {@link AccountManagerFuture} which resolves to a Boolean,
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100749 * true if the account has been successfully removed
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800750 * @deprecated use
751 * {@link #removeAccount(Account, Activity, AccountManagerCallback, Handler)}
752 * instead
Dan Egnor661f0132010-02-19 11:23:00 -0800753 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800754 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -0800755 public AccountManagerFuture<Boolean> removeAccount(final Account account,
756 AccountManagerCallback<Boolean> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -0700757 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800758 return new Future2Task<Boolean>(handler, callback) {
759 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800760 mService.removeAccount(mResponse, account, false);
Dan Egnor661f0132010-02-19 11:23:00 -0800761 }
762 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
763 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
764 throw new AuthenticatorException("no result in response");
765 }
766 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
767 }
768 }.start();
769 }
770
771 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800772 * Removes an account from the AccountManager. Does nothing if the account
773 * does not exist. Does not delete the account from the server.
774 * The authenticator may have its own policies preventing account
775 * deletion, in which case the account will not be deleted.
776 *
777 * <p>This method may be called from any thread, but the returned
778 * {@link AccountManagerFuture} must not be used on the main thread.
779 *
780 * <p>This method requires the caller to hold the permission
781 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
782 *
783 * @param account The {@link Account} to remove
784 * @param activity The {@link Activity} context to use for launching a new
785 * authenticator-defined sub-Activity to prompt the user to delete an
786 * account; used only to call startActivity(); if null, the prompt
787 * will not be launched directly, but the {@link Intent} may be
788 * returned to the caller instead
789 * @param callback Callback to invoke when the request completes,
790 * null for no callback
791 * @param handler {@link Handler} identifying the callback thread,
792 * null for the main thread
793 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
794 * {@link #KEY_BOOLEAN_RESULT} if activity was specified and an account
795 * was removed or if active. If no activity was specified, the returned
796 * Bundle contains only {@link #KEY_INTENT} with the {@link Intent}
797 * needed to launch the actual account removal process, if authenticator
798 * needs the activity launch. If an error occurred,
799 * {@link AccountManagerFuture#getResult()} throws:
800 * <ul>
801 * <li> {@link AuthenticatorException} if no authenticator was registered for
802 * this account type or the authenticator failed to respond
803 * <li> {@link OperationCanceledException} if the operation was canceled for
804 * any reason, including the user canceling the creation process or
805 * adding accounts (of this type) has been disabled by policy
806 * </ul>
807 */
808 public AccountManagerFuture<Bundle> removeAccount(final Account account,
809 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
810 if (account == null) throw new IllegalArgumentException("account is null");
811 return new AmsTask(activity, handler, callback) {
812 public void doWork() throws RemoteException {
813 mService.removeAccount(mResponse, account, activity != null);
814 }
815 }.start();
816 }
817
818 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100819 * @see #removeAccount(Account, AccountManagerCallback, Handler)
820 * @hide
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800821 * @deprecated use
822 * {@link #removeAccountAsUser(Account, Activity, AccountManagerCallback, Handler)}
823 * instead
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100824 */
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800825 @Deprecated
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100826 public AccountManagerFuture<Boolean> removeAccountAsUser(final Account account,
827 AccountManagerCallback<Boolean> callback, Handler handler,
828 final UserHandle userHandle) {
829 if (account == null) throw new IllegalArgumentException("account is null");
830 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
831 return new Future2Task<Boolean>(handler, callback) {
832 public void doWork() throws RemoteException {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800833 mService.removeAccountAsUser(mResponse, account, false, userHandle.getIdentifier());
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100834 }
835 public Boolean bundleToResult(Bundle bundle) throws AuthenticatorException {
836 if (!bundle.containsKey(KEY_BOOLEAN_RESULT)) {
837 throw new AuthenticatorException("no result in response");
838 }
839 return bundle.getBoolean(KEY_BOOLEAN_RESULT);
840 }
841 }.start();
842 }
843
844 /**
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -0800845 * @see #removeAccount(Account, Activity, AccountManagerCallback, Handler)
846 * @hide
847 */
848 public AccountManagerFuture<Bundle> removeAccountAsUser(final Account account,
849 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler,
850 final UserHandle userHandle) {
851 if (account == null)
852 throw new IllegalArgumentException("account is null");
853 if (userHandle == null)
854 throw new IllegalArgumentException("userHandle is null");
855 return new AmsTask(activity, handler, callback) {
856 public void doWork() throws RemoteException {
857 mService.removeAccountAsUser(mResponse, account, activity != null,
858 userHandle.getIdentifier());
859 }
860 }.start();
861 }
862
863 /**
864 * Removes an account directly. Normally used by authenticators, not
865 * directly by applications. Does not delete the account from the server.
866 * The authenticator may have its own policies preventing account deletion,
867 * in which case the account will not be deleted.
868 * <p>
869 * It is safe to call this method from the main thread.
870 * <p>
871 * This method requires the caller to hold the permission
872 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS} and to have the
873 * same UID or signature as the account's authenticator.
874 *
875 * @param account The {@link Account} to delete.
876 * @return True if the account was successfully deleted, false if the
877 * account did not exist, the account is null, or another error
878 * occurs.
879 */
880 public boolean removeAccountExplicitly(Account account) {
881 if (account == null) throw new IllegalArgumentException("account is null");
882 try {
883 return mService.removeAccountExplicitly(account);
884 } catch (RemoteException e) {
885 // won't ever happen
886 throw new RuntimeException(e);
887 }
888 }
889
890 /**
Dan Egnor661f0132010-02-19 11:23:00 -0800891 * Removes an auth token from the AccountManager's cache. Does nothing if
892 * the auth token is not currently in the cache. Applications must call this
893 * method when the auth token is found to have expired or otherwise become
894 * invalid for authenticating requests. The AccountManager does not validate
895 * or expire cached auth tokens otherwise.
896 *
897 * <p>It is safe to call this method from the main thread.
898 *
899 * <p>This method requires the caller to hold the permission
Fred Quintanab38eb142010-02-24 13:40:54 -0800900 * {@link android.Manifest.permission#MANAGE_ACCOUNTS} or
901 * {@link android.Manifest.permission#USE_CREDENTIALS}
Dan Egnor661f0132010-02-19 11:23:00 -0800902 *
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700903 * @param accountType The account type of the auth token to invalidate, must not be null
904 * @param authToken The auth token to invalidate, may be null
Dan Egnor661f0132010-02-19 11:23:00 -0800905 */
906 public void invalidateAuthToken(final String accountType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700907 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800908 try {
Fred Quintanaf35b68f2010-04-01 11:36:00 -0700909 if (authToken != null) {
910 mService.invalidateAuthToken(accountType, authToken);
911 }
Dan Egnor661f0132010-02-19 11:23:00 -0800912 } catch (RemoteException e) {
913 // won't ever happen
914 throw new RuntimeException(e);
915 }
916 }
917
918 /**
919 * Gets an auth token from the AccountManager's cache. If no auth
920 * token is cached for this account, null will be returned -- a new
921 * auth token will not be generated, and the server will not be contacted.
922 * Intended for use by the authenticator, not directly by applications.
923 *
924 * <p>It is safe to call this method from the main thread.
925 *
926 * <p>This method requires the caller to hold the permission
927 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
928 * and to have the same UID as the account's authenticator.
929 *
930 * @param account The account to fetch an auth token for
931 * @param authTokenType The type of auth token to fetch, see {#getAuthToken}
932 * @return The cached auth token for this account and type, or null if
933 * no auth token is cached or the account does not exist.
934 */
935 public String peekAuthToken(final Account account, final String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700936 if (account == null) throw new IllegalArgumentException("account is null");
937 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800938 try {
939 return mService.peekAuthToken(account, authTokenType);
940 } catch (RemoteException e) {
941 // won't ever happen
942 throw new RuntimeException(e);
943 }
944 }
945
946 /**
947 * Sets or forgets a saved password. This modifies the local copy of the
948 * password used to automatically authenticate the user; it does
949 * not change the user's account password on the server. Intended for use
950 * by the authenticator, not directly by applications.
951 *
952 * <p>It is safe to call this method from the main thread.
953 *
954 * <p>This method requires the caller to hold the permission
955 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
956 * and have the same UID as the account's authenticator.
957 *
958 * @param account The account to set a password for
959 * @param password The password to set, null to clear the password
960 */
961 public void setPassword(final Account account, final String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700962 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800963 try {
964 mService.setPassword(account, password);
965 } catch (RemoteException e) {
966 // won't ever happen
967 throw new RuntimeException(e);
968 }
969 }
970
971 /**
972 * Forgets a saved password. This erases the local copy of the password;
973 * it does not change the user's account password on the server.
974 * Has the same effect as setPassword(account, null) but requires fewer
975 * permissions, and may be used by applications or management interfaces
976 * to "sign out" from an account.
977 *
978 * <p>It is safe to call this method from the main thread.
979 *
980 * <p>This method requires the caller to hold the permission
981 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}
982 *
983 * @param account The account whose password to clear
984 */
985 public void clearPassword(final Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700986 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -0800987 try {
988 mService.clearPassword(account);
989 } catch (RemoteException e) {
990 // won't ever happen
991 throw new RuntimeException(e);
992 }
993 }
994
995 /**
996 * Sets one userdata key for an account. Intended by use for the
997 * authenticator to stash state for itself, not directly by applications.
998 * The meaning of the keys and values is up to the authenticator.
999 *
1000 * <p>It is safe to call this method from the main thread.
1001 *
1002 * <p>This method requires the caller to hold the permission
1003 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
1004 * and to have the same UID as the account's authenticator.
1005 *
1006 * @param account The account to set the userdata for
1007 * @param key The userdata key to set. Must not be null
1008 * @param value The value to set, null to clear this userdata key
1009 */
1010 public void setUserData(final Account account, final String key, final String value) {
Fred Quintana382601f2010-03-25 12:25:10 -07001011 if (account == null) throw new IllegalArgumentException("account is null");
1012 if (key == null) throw new IllegalArgumentException("key is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001013 try {
1014 mService.setUserData(account, key, value);
1015 } catch (RemoteException e) {
1016 // won't ever happen
1017 throw new RuntimeException(e);
1018 }
1019 }
1020
1021 /**
1022 * Adds an auth token to the AccountManager cache for an account.
1023 * If the account does not exist then this call has no effect.
1024 * Replaces any previous auth token for this account and auth token type.
1025 * Intended for use by the authenticator, not directly by applications.
1026 *
1027 * <p>It is safe to call this method from the main thread.
1028 *
1029 * <p>This method requires the caller to hold the permission
1030 * {@link android.Manifest.permission#AUTHENTICATE_ACCOUNTS}
1031 * and to have the same UID as the account's authenticator.
1032 *
1033 * @param account The account to set an auth token for
1034 * @param authTokenType The type of the auth token, see {#getAuthToken}
1035 * @param authToken The auth token to add to the cache
1036 */
1037 public void setAuthToken(Account account, final String authTokenType, final String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -07001038 if (account == null) throw new IllegalArgumentException("account is null");
1039 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001040 try {
1041 mService.setAuthToken(account, authTokenType, authToken);
1042 } catch (RemoteException e) {
1043 // won't ever happen
1044 throw new RuntimeException(e);
1045 }
1046 }
1047
1048 /**
1049 * This convenience helper synchronously gets an auth token with
1050 * {@link #getAuthToken(Account, String, boolean, AccountManagerCallback, Handler)}.
1051 *
1052 * <p>This method may block while a network request completes, and must
1053 * never be made from the main thread.
1054 *
1055 * <p>This method requires the caller to hold the permission
1056 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1057 *
1058 * @param account The account to fetch an auth token for
Joe Malinb6a35262013-06-03 09:49:04 -07001059 * @param authTokenType The auth token type, see {@link #getAuthToken getAuthToken()}
Dan Egnor661f0132010-02-19 11:23:00 -08001060 * @param notifyAuthFailure If true, display a notification and return null
1061 * if authentication fails; if false, prompt and wait for the user to
1062 * re-enter correct credentials before returning
1063 * @return An auth token of the specified type for this account, or null
1064 * if authentication fails or none can be fetched.
1065 * @throws AuthenticatorException if the authenticator failed to respond
1066 * @throws OperationCanceledException if the request was canceled for any
1067 * reason, including the user canceling a credential request
1068 * @throws java.io.IOException if the authenticator experienced an I/O problem
1069 * creating a new auth token, usually because of network trouble
1070 */
1071 public String blockingGetAuthToken(Account account, String authTokenType,
1072 boolean notifyAuthFailure)
1073 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana382601f2010-03-25 12:25:10 -07001074 if (account == null) throw new IllegalArgumentException("account is null");
1075 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001076 Bundle bundle = getAuthToken(account, authTokenType, notifyAuthFailure, null /* callback */,
1077 null /* handler */).getResult();
Fred Quintana96580e02010-03-04 13:42:42 -08001078 if (bundle == null) {
1079 // This should never happen, but it does, occasionally. If it does return null to
1080 // signify that we were not able to get the authtoken.
1081 // TODO: remove this when the bug is found that sometimes causes a null bundle to be
1082 // returned
1083 Log.e(TAG, "blockingGetAuthToken: null was returned from getResult() for "
1084 + account + ", authTokenType " + authTokenType);
1085 return null;
1086 }
Dan Egnor661f0132010-02-19 11:23:00 -08001087 return bundle.getString(KEY_AUTHTOKEN);
1088 }
1089
1090 /**
1091 * Gets an auth token of the specified type for a particular account,
1092 * prompting the user for credentials if necessary. This method is
1093 * intended for applications running in the foreground where it makes
1094 * sense to ask the user directly for a password.
1095 *
1096 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001097 * type, then it is returned. Otherwise, if a saved password is
1098 * available, it is sent to the server to generate a new auth token.
1099 * Otherwise, the user is prompted to enter a password.
Dan Egnor661f0132010-02-19 11:23:00 -08001100 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001101 * <p>Some authenticators have auth token <em>types</em>, whose value
1102 * is authenticator-dependent. Some services use different token types to
1103 * access different functionality -- for example, Google uses different auth
1104 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001105 *
1106 * <p>This method may be called from any thread, but the returned
1107 * {@link AccountManagerFuture} must not be used on the main thread.
1108 *
1109 * <p>This method requires the caller to hold the permission
1110 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1111 *
1112 * @param account The account to fetch an auth token for
1113 * @param authTokenType The auth token type, an authenticator-dependent
1114 * string token, must not be null
1115 * @param options Authenticator-specific options for the request,
1116 * may be null or empty
1117 * @param activity The {@link Activity} context to use for launching a new
1118 * authenticator-defined sub-Activity to prompt the user for a password
1119 * if necessary; used only to call startActivity(); must not be null.
1120 * @param callback Callback to invoke when the request completes,
1121 * null for no callback
1122 * @param handler {@link Handler} identifying the callback thread,
1123 * null for the main thread
1124 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1125 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07001126 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001127 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1128 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1129 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07001130 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001131 *
1132 * (Other authenticator-specific values may be returned.) If an auth token
1133 * could not be fetched, {@link AccountManagerFuture#getResult()} throws:
1134 * <ul>
1135 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1136 * <li> {@link OperationCanceledException} if the operation is canceled for
1137 * any reason, incluidng the user canceling a credential request
1138 * <li> {@link IOException} if the authenticator experienced an I/O problem
1139 * creating a new auth token, usually because of network trouble
1140 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001141 * If the account is no longer present on the device, the return value is
1142 * authenticator-dependent. The caller should verify the validity of the
1143 * account before requesting an auth token.
Dan Egnor661f0132010-02-19 11:23:00 -08001144 */
1145 public AccountManagerFuture<Bundle> getAuthToken(
1146 final Account account, final String authTokenType, final Bundle options,
1147 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001148 if (account == null) throw new IllegalArgumentException("account is null");
Dan Egnor661f0132010-02-19 11:23:00 -08001149 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001150 final Bundle optionsIn = new Bundle();
1151 if (options != null) {
1152 optionsIn.putAll(options);
1153 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001154 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Dan Egnor661f0132010-02-19 11:23:00 -08001155 return new AmsTask(activity, handler, callback) {
1156 public void doWork() throws RemoteException {
1157 mService.getAuthToken(mResponse, account, authTokenType,
1158 false /* notifyOnAuthFailure */, true /* expectActivityLaunch */,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001159 optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001160 }
1161 }.start();
1162 }
1163
1164 /**
1165 * Gets an auth token of the specified type for a particular account,
1166 * optionally raising a notification if the user must enter credentials.
1167 * This method is intended for background tasks and services where the
1168 * user should not be immediately interrupted with a password prompt.
1169 *
1170 * <p>If a previously generated auth token is cached for this account and
Dan Egnor8e4378b2010-08-02 18:22:09 -07001171 * type, then it is returned. Otherwise, if a saved password is
1172 * available, it is sent to the server to generate a new auth token.
1173 * Otherwise, an {@link Intent} is returned which, when started, will
1174 * prompt the user for a password. If the notifyAuthFailure parameter is
1175 * set, a status bar notification is also created with the same Intent,
Dan Egnor661f0132010-02-19 11:23:00 -08001176 * alerting the user that they need to enter a password at some point.
1177 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001178 * <p>In that case, you may need to wait until the user responds, which
1179 * could take hours or days or forever. When the user does respond and
1180 * supply a new password, the account manager will broadcast the
1181 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1182 * use to try again.
Dan Egnor661f0132010-02-19 11:23:00 -08001183 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001184 * <p>If notifyAuthFailure is not set, it is the application's
1185 * responsibility to launch the returned Intent at some point.
1186 * Either way, the result from this call will not wait for user action.
Dan Egnor661f0132010-02-19 11:23:00 -08001187 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001188 * <p>Some authenticators have auth token <em>types</em>, whose value
1189 * is authenticator-dependent. Some services use different token types to
1190 * access different functionality -- for example, Google uses different auth
1191 * tokens to access Gmail and Google Calendar for the same account.
Dan Egnor661f0132010-02-19 11:23:00 -08001192 *
1193 * <p>This method may be called from any thread, but the returned
1194 * {@link AccountManagerFuture} must not be used on the main thread.
1195 *
1196 * <p>This method requires the caller to hold the permission
1197 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1198 *
1199 * @param account The account to fetch an auth token for
1200 * @param authTokenType The auth token type, an authenticator-dependent
1201 * string token, must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08001202 * @param notifyAuthFailure True to add a notification to prompt the
1203 * user for a password if necessary, false to leave that to the caller
1204 * @param callback Callback to invoke when the request completes,
1205 * null for no callback
1206 * @param handler {@link Handler} identifying the callback thread,
1207 * null for the main thread
1208 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1209 * at least the following fields on success:
1210 * <ul>
1211 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1212 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1213 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1214 * </ul>
1215 *
1216 * (Other authenticator-specific values may be returned.) If the user
1217 * must enter credentials, the returned Bundle contains only
1218 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1219 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07001220 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001221 * <ul>
1222 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1223 * <li> {@link OperationCanceledException} if the operation is canceled for
1224 * any reason, incluidng the user canceling a credential request
1225 * <li> {@link IOException} if the authenticator experienced an I/O problem
1226 * creating a new auth token, usually because of network trouble
1227 * </ul>
Dan Egnor8e4378b2010-08-02 18:22:09 -07001228 * If the account is no longer present on the device, the return value is
1229 * authenticator-dependent. The caller should verify the validity of the
1230 * account before requesting an auth token.
Fred Quintanaad93a322011-09-08 13:21:01 -07001231 * @deprecated use {@link #getAuthToken(Account, String, android.os.Bundle,
1232 * boolean, AccountManagerCallback, android.os.Handler)} instead
Dan Egnor661f0132010-02-19 11:23:00 -08001233 */
Fred Quintanaad93a322011-09-08 13:21:01 -07001234 @Deprecated
Dan Egnor661f0132010-02-19 11:23:00 -08001235 public AccountManagerFuture<Bundle> getAuthToken(
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001236 final Account account, final String authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001237 final boolean notifyAuthFailure,
Dan Egnor661f0132010-02-19 11:23:00 -08001238 AccountManagerCallback<Bundle> callback, Handler handler) {
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001239 return getAuthToken(account, authTokenType, null, notifyAuthFailure, callback,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001240 handler);
Dan Egnor661f0132010-02-19 11:23:00 -08001241 }
1242
1243 /**
Fred Quintanaad93a322011-09-08 13:21:01 -07001244 * Gets an auth token of the specified type for a particular account,
1245 * optionally raising a notification if the user must enter credentials.
1246 * This method is intended for background tasks and services where the
1247 * user should not be immediately interrupted with a password prompt.
1248 *
1249 * <p>If a previously generated auth token is cached for this account and
1250 * type, then it is returned. Otherwise, if a saved password is
1251 * available, it is sent to the server to generate a new auth token.
1252 * Otherwise, an {@link Intent} is returned which, when started, will
1253 * prompt the user for a password. If the notifyAuthFailure parameter is
1254 * set, a status bar notification is also created with the same Intent,
1255 * alerting the user that they need to enter a password at some point.
1256 *
1257 * <p>In that case, you may need to wait until the user responds, which
1258 * could take hours or days or forever. When the user does respond and
1259 * supply a new password, the account manager will broadcast the
1260 * {@link #LOGIN_ACCOUNTS_CHANGED_ACTION} Intent, which applications can
1261 * use to try again.
1262 *
1263 * <p>If notifyAuthFailure is not set, it is the application's
1264 * responsibility to launch the returned Intent at some point.
1265 * Either way, the result from this call will not wait for user action.
1266 *
1267 * <p>Some authenticators have auth token <em>types</em>, whose value
1268 * is authenticator-dependent. Some services use different token types to
1269 * access different functionality -- for example, Google uses different auth
1270 * tokens to access Gmail and Google Calendar for the same account.
1271 *
1272 * <p>This method may be called from any thread, but the returned
1273 * {@link AccountManagerFuture} must not be used on the main thread.
1274 *
1275 * <p>This method requires the caller to hold the permission
1276 * {@link android.Manifest.permission#USE_CREDENTIALS}.
1277 *
1278 * @param account The account to fetch an auth token for
1279 * @param authTokenType The auth token type, an authenticator-dependent
1280 * string token, must not be null
1281 * @param options Authenticator-specific options for the request,
1282 * may be null or empty
1283 * @param notifyAuthFailure True to add a notification to prompt the
1284 * user for a password if necessary, false to leave that to the caller
1285 * @param callback Callback to invoke when the request completes,
1286 * null for no callback
1287 * @param handler {@link Handler} identifying the callback thread,
1288 * null for the main thread
1289 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
1290 * at least the following fields on success:
1291 * <ul>
1292 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account you supplied
1293 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1294 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
1295 * </ul>
1296 *
1297 * (Other authenticator-specific values may be returned.) If the user
1298 * must enter credentials, the returned Bundle contains only
1299 * {@link #KEY_INTENT} with the {@link Intent} needed to launch a prompt.
1300 *
1301 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
1302 * <ul>
1303 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1304 * <li> {@link OperationCanceledException} if the operation is canceled for
1305 * any reason, incluidng the user canceling a credential request
1306 * <li> {@link IOException} if the authenticator experienced an I/O problem
1307 * creating a new auth token, usually because of network trouble
1308 * </ul>
1309 * If the account is no longer present on the device, the return value is
1310 * authenticator-dependent. The caller should verify the validity of the
1311 * account before requesting an auth token.
1312 */
1313 public AccountManagerFuture<Bundle> getAuthToken(
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001314 final Account account, final String authTokenType, final Bundle options,
1315 final boolean notifyAuthFailure,
Fred Quintanaad93a322011-09-08 13:21:01 -07001316 AccountManagerCallback<Bundle> callback, Handler handler) {
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001317
Fred Quintanaad93a322011-09-08 13:21:01 -07001318 if (account == null) throw new IllegalArgumentException("account is null");
1319 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001320 final Bundle optionsIn = new Bundle();
1321 if (options != null) {
1322 optionsIn.putAll(options);
1323 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001324 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Fred Quintanaad93a322011-09-08 13:21:01 -07001325 return new AmsTask(null, handler, callback) {
1326 public void doWork() throws RemoteException {
1327 mService.getAuthToken(mResponse, account, authTokenType,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001328 notifyAuthFailure, false /* expectActivityLaunch */, optionsIn);
Fred Quintanaad93a322011-09-08 13:21:01 -07001329 }
1330 }.start();
1331 }
1332
1333 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001334 * Asks the user to add an account of a specified type. The authenticator
1335 * for this account type processes this request with the appropriate user
1336 * interface. If the user does elect to create a new account, the account
1337 * name is returned.
1338 *
1339 * <p>This method may be called from any thread, but the returned
1340 * {@link AccountManagerFuture} must not be used on the main thread.
1341 *
1342 * <p>This method requires the caller to hold the permission
1343 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1344 *
1345 * @param accountType The type of account to add; must not be null
1346 * @param authTokenType The type of auth token (see {@link #getAuthToken})
1347 * this account will need to be able to generate, null for none
1348 * @param requiredFeatures The features (see {@link #hasFeatures}) this
1349 * account must have, null for none
1350 * @param addAccountOptions Authenticator-specific options for the request,
1351 * may be null or empty
1352 * @param activity The {@link Activity} context to use for launching a new
1353 * authenticator-defined sub-Activity to prompt the user to create an
1354 * account; used only to call startActivity(); if null, the prompt
1355 * will not be launched directly, but the necessary {@link Intent}
1356 * will be returned to the caller instead
1357 * @param callback Callback to invoke when the request completes,
1358 * null for no callback
1359 * @param handler {@link Handler} identifying the callback thread,
1360 * null for the main thread
Doug Zongkerff592dc2010-02-23 12:26:33 -08001361 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
Dan Egnor661f0132010-02-19 11:23:00 -08001362 * these fields if activity was specified and an account was created:
1363 * <ul>
1364 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1365 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1366 * </ul>
1367 *
1368 * If no activity was specified, the returned Bundle contains only
1369 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001370 * actual account creation process. If an error occurred,
1371 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001372 * <ul>
1373 * <li> {@link AuthenticatorException} if no authenticator was registered for
1374 * this account type or the authenticator failed to respond
1375 * <li> {@link OperationCanceledException} if the operation was canceled for
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001376 * any reason, including the user canceling the creation process or adding accounts
1377 * (of this type) has been disabled by policy
Dan Egnor661f0132010-02-19 11:23:00 -08001378 * <li> {@link IOException} if the authenticator experienced an I/O problem
1379 * creating a new account, usually because of network trouble
1380 * </ul>
1381 */
1382 public AccountManagerFuture<Bundle> addAccount(final String accountType,
1383 final String authTokenType, final String[] requiredFeatures,
1384 final Bundle addAccountOptions,
1385 final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001386 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolachee5847ad2011-09-14 12:52:19 -07001387 final Bundle optionsIn = new Bundle();
1388 if (addAccountOptions != null) {
1389 optionsIn.putAll(addAccountOptions);
1390 }
1391 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001392
Dan Egnor661f0132010-02-19 11:23:00 -08001393 return new AmsTask(activity, handler, callback) {
1394 public void doWork() throws RemoteException {
Amith Yamasani27db4682013-03-30 17:07:47 -07001395 mService.addAccount(mResponse, accountType, authTokenType,
Costin Manolachee5847ad2011-09-14 12:52:19 -07001396 requiredFeatures, activity != null, optionsIn);
Dan Egnor661f0132010-02-19 11:23:00 -08001397 }
1398 }.start();
1399 }
1400
1401 /**
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001402 * @see #addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback, Handler)
1403 * @hide
1404 */
1405 public AccountManagerFuture<Bundle> addAccountAsUser(final String accountType,
1406 final String authTokenType, final String[] requiredFeatures,
1407 final Bundle addAccountOptions, final Activity activity,
1408 AccountManagerCallback<Bundle> callback, Handler handler, final UserHandle userHandle) {
1409 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1410 if (userHandle == null) throw new IllegalArgumentException("userHandle is null");
1411 final Bundle optionsIn = new Bundle();
1412 if (addAccountOptions != null) {
1413 optionsIn.putAll(addAccountOptions);
1414 }
1415 optionsIn.putString(KEY_ANDROID_PACKAGE_NAME, mContext.getPackageName());
1416
1417 return new AmsTask(activity, handler, callback) {
1418 public void doWork() throws RemoteException {
1419 mService.addAccountAsUser(mResponse, accountType, authTokenType,
1420 requiredFeatures, activity != null, optionsIn, userHandle.getIdentifier());
1421 }
1422 }.start();
1423 }
1424
1425 /**
Amith Yamasani67df64b2012-12-14 12:09:36 -08001426 * Adds a shared account from the primary user to a secondary user. Adding the shared account
1427 * doesn't take effect immediately. When the target user starts up, any pending shared accounts
1428 * are attempted to be copied to the target user from the primary via calls to the
1429 * authenticator.
1430 * @param account the account to share
1431 * @param user the target user
1432 * @return
1433 * @hide
1434 */
1435 public boolean addSharedAccount(final Account account, UserHandle user) {
1436 try {
1437 boolean val = mService.addSharedAccountAsUser(account, user.getIdentifier());
1438 return val;
1439 } catch (RemoteException re) {
1440 // won't ever happen
1441 throw new RuntimeException(re);
1442 }
1443 }
1444
1445 /**
1446 * @hide
1447 * Removes the shared account.
1448 * @param account the account to remove
1449 * @param user the user to remove the account from
1450 * @return
1451 */
1452 public boolean removeSharedAccount(final Account account, UserHandle user) {
1453 try {
1454 boolean val = mService.removeSharedAccountAsUser(account, user.getIdentifier());
1455 return val;
1456 } catch (RemoteException re) {
1457 // won't ever happen
1458 throw new RuntimeException(re);
1459 }
1460 }
1461
1462 /**
1463 * @hide
1464 * @param user
1465 * @return
1466 */
1467 public Account[] getSharedAccounts(UserHandle user) {
1468 try {
1469 return mService.getSharedAccountsAsUser(user.getIdentifier());
1470 } catch (RemoteException re) {
1471 // won't ever happen
1472 throw new RuntimeException(re);
1473 }
1474 }
1475
1476 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001477 * Confirms that the user knows the password for an account to make extra
1478 * sure they are the owner of the account. The user-entered password can
1479 * be supplied directly, otherwise the authenticator for this account type
1480 * prompts the user with the appropriate interface. This method is
1481 * intended for applications which want extra assurance; for example, the
1482 * phone lock screen uses this to let the user unlock the phone with an
1483 * account password if they forget the lock pattern.
1484 *
1485 * <p>If the user-entered password matches a saved password for this
1486 * account, the request is considered valid; otherwise the authenticator
1487 * verifies the password (usually by contacting the server).
1488 *
1489 * <p>This method may be called from any thread, but the returned
1490 * {@link AccountManagerFuture} must not be used on the main thread.
1491 *
1492 * <p>This method requires the caller to hold the permission
1493 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1494 *
1495 * @param account The account to confirm password knowledge for
1496 * @param options Authenticator-specific options for the request;
1497 * if the {@link #KEY_PASSWORD} string field is present, the
1498 * authenticator may use it directly rather than prompting the user;
1499 * may be null or empty
1500 * @param activity The {@link Activity} context to use for launching a new
1501 * authenticator-defined sub-Activity to prompt the user to enter a
1502 * password; used only to call startActivity(); if null, the prompt
1503 * will not be launched directly, but the necessary {@link Intent}
1504 * will be returned to the caller instead
1505 * @param callback Callback to invoke when the request completes,
1506 * null for no callback
1507 * @param handler {@link Handler} identifying the callback thread,
1508 * null for the main thread
1509 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1510 * with these fields if activity or password was supplied and
1511 * the account was successfully verified:
1512 * <ul>
1513 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1514 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
1515 * <li> {@link #KEY_BOOLEAN_RESULT} - true to indicate success
1516 * </ul>
1517 *
1518 * If no activity or password was specified, the returned Bundle contains
1519 * only {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001520 * password prompt. If an error occurred,
1521 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001522 * <ul>
1523 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1524 * <li> {@link OperationCanceledException} if the operation was canceled for
1525 * any reason, including the user canceling the password prompt
1526 * <li> {@link IOException} if the authenticator experienced an I/O problem
1527 * verifying the password, usually because of network trouble
1528 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001529 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001530 public AccountManagerFuture<Bundle> confirmCredentials(final Account account,
1531 final Bundle options,
1532 final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001533 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001534 final Handler handler) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001535 return confirmCredentialsAsUser(account, options, activity, callback, handler,
1536 Process.myUserHandle());
1537 }
1538
1539 /**
1540 * @hide
1541 * Same as {@link #confirmCredentials(Account, Bundle, Activity, AccountManagerCallback, Handler)}
1542 * but for the specified user.
1543 */
1544 public AccountManagerFuture<Bundle> confirmCredentialsAsUser(final Account account,
1545 final Bundle options,
1546 final Activity activity,
1547 final AccountManagerCallback<Bundle> callback,
1548 final Handler handler, UserHandle userHandle) {
Fred Quintana382601f2010-03-25 12:25:10 -07001549 if (account == null) throw new IllegalArgumentException("account is null");
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001550 final int userId = userHandle.getIdentifier();
Fred Quintanaa698f422009-04-08 19:14:54 -07001551 return new AmsTask(activity, handler, callback) {
1552 public void doWork() throws RemoteException {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001553 mService.confirmCredentialsAsUser(mResponse, account, options, activity != null,
1554 userId);
Fred Quintanaa698f422009-04-08 19:14:54 -07001555 }
Fred Quintana33269202009-04-20 16:05:10 -07001556 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001557 }
1558
Fred Quintana756b7352009-10-21 13:43:10 -07001559 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001560 * Asks the user to enter a new password for an account, updating the
1561 * saved credentials for the account. Normally this happens automatically
1562 * when the server rejects credentials during an auth token fetch, but this
1563 * can be invoked directly to ensure we have the correct credentials stored.
Fred Quintana756b7352009-10-21 13:43:10 -07001564 *
Dan Egnor661f0132010-02-19 11:23:00 -08001565 * <p>This method may be called from any thread, but the returned
1566 * {@link AccountManagerFuture} must not be used on the main thread.
1567 *
1568 * <p>This method requires the caller to hold the permission
1569 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1570 *
1571 * @param account The account to update credentials for
1572 * @param authTokenType The credentials entered must allow an auth token
1573 * of this type to be created (but no actual auth token is returned);
1574 * may be null
1575 * @param options Authenticator-specific options for the request;
1576 * may be null or empty
1577 * @param activity The {@link Activity} context to use for launching a new
1578 * authenticator-defined sub-Activity to prompt the user to enter a
1579 * password; used only to call startActivity(); if null, the prompt
1580 * will not be launched directly, but the necessary {@link Intent}
1581 * will be returned to the caller instead
1582 * @param callback Callback to invoke when the request completes,
1583 * null for no callback
1584 * @param handler {@link Handler} identifying the callback thread,
1585 * null for the main thread
1586 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1587 * with these fields if an activity was supplied and the account
1588 * credentials were successfully updated:
Fred Quintana756b7352009-10-21 13:43:10 -07001589 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001590 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account created
1591 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
Fred Quintana756b7352009-10-21 13:43:10 -07001592 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001593 *
1594 * If no activity was specified, the returned Bundle contains only
1595 * {@link #KEY_INTENT} with the {@link Intent} needed to launch the
Dan Egnor8e4378b2010-08-02 18:22:09 -07001596 * password prompt. If an error occurred,
1597 * {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08001598 * <ul>
1599 * <li> {@link AuthenticatorException} if the authenticator failed to respond
1600 * <li> {@link OperationCanceledException} if the operation was canceled for
1601 * any reason, including the user canceling the password prompt
1602 * <li> {@link IOException} if the authenticator experienced an I/O problem
1603 * verifying the password, usually because of network trouble
1604 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001605 */
1606 public AccountManagerFuture<Bundle> updateCredentials(final Account account,
1607 final String authTokenType,
Fred Quintana31957f12009-10-21 13:43:10 -07001608 final Bundle options, final Activity activity,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001609 final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001610 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001611 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001612 return new AmsTask(activity, handler, callback) {
1613 public void doWork() throws RemoteException {
1614 mService.updateCredentials(mResponse, account, authTokenType, activity != null,
Fred Quintana31957f12009-10-21 13:43:10 -07001615 options);
Fred Quintanaa698f422009-04-08 19:14:54 -07001616 }
Fred Quintana33269202009-04-20 16:05:10 -07001617 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001618 }
1619
Fred Quintana756b7352009-10-21 13:43:10 -07001620 /**
Dan Egnor661f0132010-02-19 11:23:00 -08001621 * Offers the user an opportunity to change an authenticator's settings.
1622 * These properties are for the authenticator in general, not a particular
1623 * account. Not all authenticators support this method.
Fred Quintana756b7352009-10-21 13:43:10 -07001624 *
Dan Egnor661f0132010-02-19 11:23:00 -08001625 * <p>This method may be called from any thread, but the returned
1626 * {@link AccountManagerFuture} must not be used on the main thread.
1627 *
1628 * <p>This method requires the caller to hold the permission
1629 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
1630 *
1631 * @param accountType The account type associated with the authenticator
1632 * to adjust
1633 * @param activity The {@link Activity} context to use for launching a new
1634 * authenticator-defined sub-Activity to adjust authenticator settings;
1635 * used only to call startActivity(); if null, the settings dialog will
1636 * not be launched directly, but the necessary {@link Intent} will be
1637 * returned to the caller instead
1638 * @param callback Callback to invoke when the request completes,
1639 * null for no callback
1640 * @param handler {@link Handler} identifying the callback thread,
1641 * null for the main thread
1642 * @return An {@link AccountManagerFuture} which resolves to a Bundle
1643 * which is empty if properties were edited successfully, or
1644 * if no activity was specified, contains only {@link #KEY_INTENT}
1645 * needed to launch the authenticator's settings dialog.
Dan Egnor8e4378b2010-08-02 18:22:09 -07001646 * If an error occurred, {@link AccountManagerFuture#getResult()}
1647 * throws:
Fred Quintana756b7352009-10-21 13:43:10 -07001648 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08001649 * <li> {@link AuthenticatorException} if no authenticator was registered for
1650 * this account type or the authenticator failed to respond
1651 * <li> {@link OperationCanceledException} if the operation was canceled for
1652 * any reason, including the user canceling the settings dialog
1653 * <li> {@link IOException} if the authenticator experienced an I/O problem
1654 * updating settings, usually because of network trouble
Fred Quintana756b7352009-10-21 13:43:10 -07001655 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07001656 */
1657 public AccountManagerFuture<Bundle> editProperties(final String accountType,
1658 final Activity activity, final AccountManagerCallback<Bundle> callback,
Fred Quintanaa698f422009-04-08 19:14:54 -07001659 final Handler handler) {
Fred Quintana382601f2010-03-25 12:25:10 -07001660 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanaa698f422009-04-08 19:14:54 -07001661 return new AmsTask(activity, handler, callback) {
1662 public void doWork() throws RemoteException {
1663 mService.editProperties(mResponse, accountType, activity != null);
1664 }
Fred Quintana33269202009-04-20 16:05:10 -07001665 }.start();
Fred Quintanaa698f422009-04-08 19:14:54 -07001666 }
1667
1668 private void ensureNotOnMainThread() {
1669 final Looper looper = Looper.myLooper();
1670 if (looper != null && looper == mContext.getMainLooper()) {
Fred Quintana53bd2522010-02-05 15:28:12 -08001671 final IllegalStateException exception = new IllegalStateException(
1672 "calling this from your main thread can lead to deadlock");
1673 Log.e(TAG, "calling this from your main thread can lead to deadlock and/or ANRs",
1674 exception);
Fred Quintana751fdc02010-02-09 14:13:18 -08001675 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.FROYO) {
1676 throw exception;
1677 }
Fred Quintana60307342009-03-24 22:48:12 -07001678 }
1679 }
1680
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001681 private void postToHandler(Handler handler, final AccountManagerCallback<Bundle> callback,
1682 final AccountManagerFuture<Bundle> future) {
Fred Quintanad9d2f112009-04-23 13:36:27 -07001683 handler = handler == null ? mMainHandler : handler;
1684 handler.post(new Runnable() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001685 public void run() {
1686 callback.run(future);
1687 }
1688 });
1689 }
Fred Quintana60307342009-03-24 22:48:12 -07001690
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001691 private void postToHandler(Handler handler, final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07001692 final Account[] accounts) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001693 final Account[] accountsCopy = new Account[accounts.length];
1694 // send a copy to make sure that one doesn't
1695 // change what another sees
1696 System.arraycopy(accounts, 0, accountsCopy, 0, accountsCopy.length);
1697 handler = (handler == null) ? mMainHandler : handler;
Fred Quintanad9d2f112009-04-23 13:36:27 -07001698 handler.post(new Runnable() {
1699 public void run() {
Costin Manolacheb6437242009-09-10 16:14:12 -07001700 try {
1701 listener.onAccountsUpdated(accountsCopy);
1702 } catch (SQLException e) {
1703 // Better luck next time. If the problem was disk-full,
1704 // the STORAGE_OK intent will re-trigger the update.
1705 Log.e(TAG, "Can't update accounts", e);
1706 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07001707 }
1708 });
1709 }
1710
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001711 private abstract class AmsTask extends FutureTask<Bundle> implements AccountManagerFuture<Bundle> {
Fred Quintanaa698f422009-04-08 19:14:54 -07001712 final IAccountManagerResponse mResponse;
1713 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001714 final AccountManagerCallback<Bundle> mCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -07001715 final Activity mActivity;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001716 public AmsTask(Activity activity, Handler handler, AccountManagerCallback<Bundle> callback) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001717 super(new Callable<Bundle>() {
1718 public Bundle call() throws Exception {
1719 throw new IllegalStateException("this should never be called");
1720 }
1721 });
1722
1723 mHandler = handler;
1724 mCallback = callback;
1725 mActivity = activity;
1726 mResponse = new Response();
Fred Quintana33269202009-04-20 16:05:10 -07001727 }
1728
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001729 public final AccountManagerFuture<Bundle> start() {
1730 try {
1731 doWork();
1732 } catch (RemoteException e) {
1733 setException(e);
1734 }
Fred Quintana33269202009-04-20 16:05:10 -07001735 return this;
Fred Quintana60307342009-03-24 22:48:12 -07001736 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001737
Fred Quintana96580e02010-03-04 13:42:42 -08001738 protected void set(Bundle bundle) {
1739 // TODO: somehow a null is being set as the result of the Future. Log this
1740 // case to help debug where this is occurring. When this bug is fixed this
1741 // condition statement should be removed.
1742 if (bundle == null) {
1743 Log.e(TAG, "the bundle must not be null", new Exception());
1744 }
1745 super.set(bundle);
1746 }
1747
Fred Quintanaa698f422009-04-08 19:14:54 -07001748 public abstract void doWork() throws RemoteException;
1749
1750 private Bundle internalGetResult(Long timeout, TimeUnit unit)
1751 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001752 if (!isDone()) {
1753 ensureNotOnMainThread();
1754 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001755 try {
1756 if (timeout == null) {
1757 return get();
1758 } else {
1759 return get(timeout, unit);
1760 }
1761 } catch (CancellationException e) {
1762 throw new OperationCanceledException();
1763 } catch (TimeoutException e) {
1764 // fall through and cancel
1765 } catch (InterruptedException e) {
1766 // fall through and cancel
1767 } catch (ExecutionException e) {
1768 final Throwable cause = e.getCause();
1769 if (cause instanceof IOException) {
1770 throw (IOException) cause;
1771 } else if (cause instanceof UnsupportedOperationException) {
1772 throw new AuthenticatorException(cause);
1773 } else if (cause instanceof AuthenticatorException) {
1774 throw (AuthenticatorException) cause;
1775 } else if (cause instanceof RuntimeException) {
1776 throw (RuntimeException) cause;
1777 } else if (cause instanceof Error) {
1778 throw (Error) cause;
1779 } else {
1780 throw new IllegalStateException(cause);
1781 }
1782 } finally {
1783 cancel(true /* interrupt if running */);
1784 }
1785 throw new OperationCanceledException();
1786 }
1787
1788 public Bundle getResult()
1789 throws OperationCanceledException, IOException, AuthenticatorException {
1790 return internalGetResult(null, null);
1791 }
1792
1793 public Bundle getResult(long timeout, TimeUnit unit)
1794 throws OperationCanceledException, IOException, AuthenticatorException {
1795 return internalGetResult(timeout, unit);
1796 }
1797
1798 protected void done() {
1799 if (mCallback != null) {
1800 postToHandler(mHandler, mCallback, this);
1801 }
1802 }
1803
1804 /** Handles the responses from the AccountManager */
1805 private class Response extends IAccountManagerResponse.Stub {
1806 public void onResult(Bundle bundle) {
Brian Carlstrom46703b02011-04-06 15:41:29 -07001807 Intent intent = bundle.getParcelable(KEY_INTENT);
Fred Quintanaa698f422009-04-08 19:14:54 -07001808 if (intent != null && mActivity != null) {
1809 // since the user provided an Activity we will silently start intents
1810 // that we see
1811 mActivity.startActivity(intent);
1812 // leave the Future running to wait for the real response to this request
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001813 } else if (bundle.getBoolean("retry")) {
1814 try {
1815 doWork();
1816 } catch (RemoteException e) {
1817 // this will only happen if the system process is dead, which means
1818 // we will be dying ourselves
1819 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001820 } else {
1821 set(bundle);
1822 }
1823 }
1824
1825 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001826 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1827 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1828 // the authenticator indicated that this request was canceled or we were
1829 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001830 cancel(true /* mayInterruptIfRunning */);
1831 return;
1832 }
1833 setException(convertErrorToException(code, message));
1834 }
1835 }
1836
Fred Quintana60307342009-03-24 22:48:12 -07001837 }
1838
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001839 private abstract class BaseFutureTask<T> extends FutureTask<T> {
1840 final public IAccountManagerResponse mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001841 final Handler mHandler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001842
1843 public BaseFutureTask(Handler handler) {
1844 super(new Callable<T>() {
1845 public T call() throws Exception {
Fred Quintanaa698f422009-04-08 19:14:54 -07001846 throw new IllegalStateException("this should never be called");
1847 }
1848 });
Fred Quintanaa698f422009-04-08 19:14:54 -07001849 mHandler = handler;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001850 mResponse = new Response();
Fred Quintana60307342009-03-24 22:48:12 -07001851 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001852
1853 public abstract void doWork() throws RemoteException;
1854
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001855 public abstract T bundleToResult(Bundle bundle) throws AuthenticatorException;
Fred Quintanaa698f422009-04-08 19:14:54 -07001856
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001857 protected void postRunnableToHandler(Runnable runnable) {
1858 Handler handler = (mHandler == null) ? mMainHandler : mHandler;
1859 handler.post(runnable);
Fred Quintanaa698f422009-04-08 19:14:54 -07001860 }
1861
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001862 protected void startTask() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001863 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001864 doWork();
1865 } catch (RemoteException e) {
1866 setException(e);
Fred Quintanaa698f422009-04-08 19:14:54 -07001867 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001868 }
1869
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001870 protected class Response extends IAccountManagerResponse.Stub {
Fred Quintanaa698f422009-04-08 19:14:54 -07001871 public void onResult(Bundle bundle) {
1872 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001873 T result = bundleToResult(bundle);
1874 if (result == null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001875 return;
1876 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001877 set(result);
1878 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001879 } catch (ClassCastException e) {
1880 // we will set the exception below
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001881 } catch (AuthenticatorException e) {
1882 // we will set the exception below
Fred Quintanaa698f422009-04-08 19:14:54 -07001883 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001884 onError(ERROR_CODE_INVALID_RESPONSE, "no result in response");
Fred Quintanaa698f422009-04-08 19:14:54 -07001885 }
1886
1887 public void onError(int code, String message) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001888 if (code == ERROR_CODE_CANCELED || code == ERROR_CODE_USER_RESTRICTED
1889 || code == ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
1890 // the authenticator indicated that this request was canceled or we were
1891 // forbidden to fulfill; cancel now
Fred Quintanaa698f422009-04-08 19:14:54 -07001892 cancel(true /* mayInterruptIfRunning */);
1893 return;
1894 }
1895 setException(convertErrorToException(code, message));
1896 }
1897 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001898 }
1899
1900 private abstract class Future2Task<T>
1901 extends BaseFutureTask<T> implements AccountManagerFuture<T> {
1902 final AccountManagerCallback<T> mCallback;
1903 public Future2Task(Handler handler, AccountManagerCallback<T> callback) {
1904 super(handler);
1905 mCallback = callback;
1906 }
1907
1908 protected void done() {
1909 if (mCallback != null) {
1910 postRunnableToHandler(new Runnable() {
1911 public void run() {
1912 mCallback.run(Future2Task.this);
1913 }
1914 });
1915 }
1916 }
1917
1918 public Future2Task<T> start() {
1919 startTask();
1920 return this;
1921 }
1922
1923 private T internalGetResult(Long timeout, TimeUnit unit)
1924 throws OperationCanceledException, IOException, AuthenticatorException {
Fred Quintana53bd2522010-02-05 15:28:12 -08001925 if (!isDone()) {
1926 ensureNotOnMainThread();
1927 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001928 try {
1929 if (timeout == null) {
1930 return get();
1931 } else {
1932 return get(timeout, unit);
1933 }
1934 } catch (InterruptedException e) {
1935 // fall through and cancel
1936 } catch (TimeoutException e) {
1937 // fall through and cancel
1938 } catch (CancellationException e) {
1939 // fall through and cancel
1940 } catch (ExecutionException e) {
1941 final Throwable cause = e.getCause();
1942 if (cause instanceof IOException) {
1943 throw (IOException) cause;
1944 } else if (cause instanceof UnsupportedOperationException) {
1945 throw new AuthenticatorException(cause);
1946 } else if (cause instanceof AuthenticatorException) {
1947 throw (AuthenticatorException) cause;
1948 } else if (cause instanceof RuntimeException) {
1949 throw (RuntimeException) cause;
1950 } else if (cause instanceof Error) {
1951 throw (Error) cause;
1952 } else {
1953 throw new IllegalStateException(cause);
1954 }
1955 } finally {
1956 cancel(true /* interrupt if running */);
1957 }
1958 throw new OperationCanceledException();
1959 }
1960
1961 public T getResult()
1962 throws OperationCanceledException, IOException, AuthenticatorException {
1963 return internalGetResult(null, null);
1964 }
1965
1966 public T getResult(long timeout, TimeUnit unit)
1967 throws OperationCanceledException, IOException, AuthenticatorException {
1968 return internalGetResult(timeout, unit);
1969 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001970
Fred Quintana60307342009-03-24 22:48:12 -07001971 }
1972
Fred Quintanaa698f422009-04-08 19:14:54 -07001973 private Exception convertErrorToException(int code, String message) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001974 if (code == ERROR_CODE_NETWORK_ERROR) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001975 return new IOException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001976 }
Fred Quintana60307342009-03-24 22:48:12 -07001977
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001978 if (code == ERROR_CODE_UNSUPPORTED_OPERATION) {
Fred Quintana33269202009-04-20 16:05:10 -07001979 return new UnsupportedOperationException(message);
Fred Quintana60307342009-03-24 22:48:12 -07001980 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001981
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001982 if (code == ERROR_CODE_INVALID_RESPONSE) {
Fred Quintana33269202009-04-20 16:05:10 -07001983 return new AuthenticatorException(message);
Fred Quintanaa698f422009-04-08 19:14:54 -07001984 }
1985
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001986 if (code == ERROR_CODE_BAD_ARGUMENTS) {
Fred Quintana33269202009-04-20 16:05:10 -07001987 return new IllegalArgumentException(message);
1988 }
1989
1990 return new AuthenticatorException(message);
1991 }
1992
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001993 private class GetAuthTokenByTypeAndFeaturesTask
1994 extends AmsTask implements AccountManagerCallback<Bundle> {
Fred Quintana33269202009-04-20 16:05:10 -07001995 GetAuthTokenByTypeAndFeaturesTask(final String accountType, final String authTokenType,
1996 final String[] features, Activity activityForPrompting,
1997 final Bundle addAccountOptions, final Bundle loginOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001998 AccountManagerCallback<Bundle> callback, Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07001999 super(activityForPrompting, handler, callback);
2000 if (accountType == null) throw new IllegalArgumentException("account type is null");
2001 mAccountType = accountType;
2002 mAuthTokenType = authTokenType;
2003 mFeatures = features;
2004 mAddAccountOptions = addAccountOptions;
2005 mLoginOptions = loginOptions;
2006 mMyCallback = this;
2007 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002008 volatile AccountManagerFuture<Bundle> mFuture = null;
Fred Quintana33269202009-04-20 16:05:10 -07002009 final String mAccountType;
2010 final String mAuthTokenType;
2011 final String[] mFeatures;
2012 final Bundle mAddAccountOptions;
2013 final Bundle mLoginOptions;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002014 final AccountManagerCallback<Bundle> mMyCallback;
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002015 private volatile int mNumAccounts = 0;
Fred Quintana33269202009-04-20 16:05:10 -07002016
2017 public void doWork() throws RemoteException {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002018 getAccountsByTypeAndFeatures(mAccountType, mFeatures,
2019 new AccountManagerCallback<Account[]>() {
2020 public void run(AccountManagerFuture<Account[]> future) {
2021 Account[] accounts;
Fred Quintana33269202009-04-20 16:05:10 -07002022 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002023 accounts = future.getResult();
2024 } catch (OperationCanceledException e) {
2025 setException(e);
2026 return;
2027 } catch (IOException e) {
2028 setException(e);
2029 return;
2030 } catch (AuthenticatorException e) {
2031 setException(e);
2032 return;
Fred Quintana33269202009-04-20 16:05:10 -07002033 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002034
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002035 mNumAccounts = accounts.length;
2036
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002037 if (accounts.length == 0) {
2038 if (mActivity != null) {
2039 // no accounts, add one now. pretend that the user directly
2040 // made this request
2041 mFuture = addAccount(mAccountType, mAuthTokenType, mFeatures,
2042 mAddAccountOptions, mActivity, mMyCallback, mHandler);
2043 } else {
2044 // send result since we can't prompt to add an account
2045 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002046 result.putString(KEY_ACCOUNT_NAME, null);
2047 result.putString(KEY_ACCOUNT_TYPE, null);
2048 result.putString(KEY_AUTHTOKEN, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002049 try {
2050 mResponse.onResult(result);
2051 } catch (RemoteException e) {
2052 // this will never happen
2053 }
2054 // we are done
2055 }
2056 } else if (accounts.length == 1) {
2057 // have a single account, return an authtoken for it
2058 if (mActivity == null) {
2059 mFuture = getAuthToken(accounts[0], mAuthTokenType,
2060 false /* notifyAuthFailure */, mMyCallback, mHandler);
2061 } else {
2062 mFuture = getAuthToken(accounts[0],
2063 mAuthTokenType, mLoginOptions,
Fred Quintana33269202009-04-20 16:05:10 -07002064 mActivity, mMyCallback, mHandler);
2065 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002066 } else {
2067 if (mActivity != null) {
2068 IAccountManagerResponse chooseResponse =
2069 new IAccountManagerResponse.Stub() {
2070 public void onResult(Bundle value) throws RemoteException {
2071 Account account = new Account(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002072 value.getString(KEY_ACCOUNT_NAME),
2073 value.getString(KEY_ACCOUNT_TYPE));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002074 mFuture = getAuthToken(account, mAuthTokenType, mLoginOptions,
2075 mActivity, mMyCallback, mHandler);
2076 }
Fred Quintana33269202009-04-20 16:05:10 -07002077
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002078 public void onError(int errorCode, String errorMessage)
2079 throws RemoteException {
2080 mResponse.onError(errorCode, errorMessage);
2081 }
2082 };
2083 // have many accounts, launch the chooser
2084 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002085 ComponentName componentName = ComponentName.unflattenFromString(
2086 Resources.getSystem().getString(
2087 R.string.config_chooseAccountActivity));
2088 intent.setClassName(componentName.getPackageName(),
2089 componentName.getClassName());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002090 intent.putExtra(KEY_ACCOUNTS, accounts);
2091 intent.putExtra(KEY_ACCOUNT_MANAGER_RESPONSE,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002092 new AccountManagerResponse(chooseResponse));
2093 mActivity.startActivity(intent);
2094 // the result will arrive via the IAccountManagerResponse
2095 } else {
2096 // send result since we can't prompt to select an account
2097 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002098 result.putString(KEY_ACCOUNTS, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002099 try {
2100 mResponse.onResult(result);
2101 } catch (RemoteException e) {
2102 // this will never happen
2103 }
2104 // we are done
Fred Quintana33269202009-04-20 16:05:10 -07002105 }
Fred Quintana33269202009-04-20 16:05:10 -07002106 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002107 }}, mHandler);
Fred Quintana33269202009-04-20 16:05:10 -07002108 }
2109
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002110 public void run(AccountManagerFuture<Bundle> future) {
Fred Quintana33269202009-04-20 16:05:10 -07002111 try {
Fred Quintanaf0fd8432010-03-08 12:48:05 -08002112 final Bundle result = future.getResult();
2113 if (mNumAccounts == 0) {
2114 final String accountName = result.getString(KEY_ACCOUNT_NAME);
2115 final String accountType = result.getString(KEY_ACCOUNT_TYPE);
2116 if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(accountType)) {
2117 setException(new AuthenticatorException("account not in result"));
2118 return;
2119 }
2120 final Account account = new Account(accountName, accountType);
2121 mNumAccounts = 1;
2122 getAuthToken(account, mAuthTokenType, null /* options */, mActivity,
2123 mMyCallback, mHandler);
2124 return;
2125 }
2126 set(result);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002127 } catch (OperationCanceledException e) {
2128 cancel(true /* mayInterruptIfRUnning */);
2129 } catch (IOException e) {
2130 setException(e);
2131 } catch (AuthenticatorException e) {
2132 setException(e);
Fred Quintana33269202009-04-20 16:05:10 -07002133 }
2134 }
2135 }
2136
Fred Quintana756b7352009-10-21 13:43:10 -07002137 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002138 * This convenience helper combines the functionality of
2139 * {@link #getAccountsByTypeAndFeatures}, {@link #getAuthToken}, and
2140 * {@link #addAccount}.
Fred Quintana756b7352009-10-21 13:43:10 -07002141 *
Dan Egnor661f0132010-02-19 11:23:00 -08002142 * <p>This method gets a list of the accounts matching the
2143 * specified type and feature set; if there is exactly one, it is
2144 * used; if there are more than one, the user is prompted to pick one;
2145 * if there are none, the user is prompted to add one. Finally,
2146 * an auth token is acquired for the chosen account.
2147 *
2148 * <p>This method may be called from any thread, but the returned
2149 * {@link AccountManagerFuture} must not be used on the main thread.
2150 *
2151 * <p>This method requires the caller to hold the permission
2152 * {@link android.Manifest.permission#MANAGE_ACCOUNTS}.
2153 *
2154 * @param accountType The account type required
Doug Zongkerff592dc2010-02-23 12:26:33 -08002155 * (see {@link #getAccountsByType}), must not be null
Dan Egnor661f0132010-02-19 11:23:00 -08002156 * @param authTokenType The desired auth token type
2157 * (see {@link #getAuthToken}), must not be null
2158 * @param features Required features for the account
2159 * (see {@link #getAccountsByTypeAndFeatures}), may be null or empty
2160 * @param activity The {@link Activity} context to use for launching new
2161 * sub-Activities to prompt to add an account, select an account,
2162 * and/or enter a password, as necessary; used only to call
2163 * startActivity(); should not be null
2164 * @param addAccountOptions Authenticator-specific options to use for
2165 * adding new accounts; may be null or empty
2166 * @param getAuthTokenOptions Authenticator-specific options to use for
2167 * getting auth tokens; may be null or empty
2168 * @param callback Callback to invoke when the request completes,
2169 * null for no callback
2170 * @param handler {@link Handler} identifying the callback thread,
2171 * null for the main thread
2172 * @return An {@link AccountManagerFuture} which resolves to a Bundle with
2173 * at least the following fields:
Fred Quintana756b7352009-10-21 13:43:10 -07002174 * <ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002175 * <li> {@link #KEY_ACCOUNT_NAME} - the name of the account
2176 * <li> {@link #KEY_ACCOUNT_TYPE} - the type of the account
2177 * <li> {@link #KEY_AUTHTOKEN} - the auth token you wanted
Fred Quintana756b7352009-10-21 13:43:10 -07002178 * </ul>
Dan Egnor661f0132010-02-19 11:23:00 -08002179 *
Dan Egnor8e4378b2010-08-02 18:22:09 -07002180 * If an error occurred, {@link AccountManagerFuture#getResult()} throws:
Dan Egnor661f0132010-02-19 11:23:00 -08002181 * <ul>
2182 * <li> {@link AuthenticatorException} if no authenticator was registered for
2183 * this account type or the authenticator failed to respond
2184 * <li> {@link OperationCanceledException} if the operation was canceled for
2185 * any reason, including the user canceling any operation
2186 * <li> {@link IOException} if the authenticator experienced an I/O problem
2187 * updating settings, usually because of network trouble
2188 * </ul>
Fred Quintana756b7352009-10-21 13:43:10 -07002189 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002190 public AccountManagerFuture<Bundle> getAuthTokenByFeatures(
Fred Quintana33269202009-04-20 16:05:10 -07002191 final String accountType, final String authTokenType, final String[] features,
Dan Egnor661f0132010-02-19 11:23:00 -08002192 final Activity activity, final Bundle addAccountOptions,
Fred Quintana31957f12009-10-21 13:43:10 -07002193 final Bundle getAuthTokenOptions,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002194 final AccountManagerCallback<Bundle> callback, final Handler handler) {
Fred Quintana33269202009-04-20 16:05:10 -07002195 if (accountType == null) throw new IllegalArgumentException("account type is null");
2196 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002197 final GetAuthTokenByTypeAndFeaturesTask task =
2198 new GetAuthTokenByTypeAndFeaturesTask(accountType, authTokenType, features,
Dan Egnor661f0132010-02-19 11:23:00 -08002199 activity, addAccountOptions, getAuthTokenOptions, callback, handler);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002200 task.start();
2201 return task;
Fred Quintana60307342009-03-24 22:48:12 -07002202 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002203
Fred Quintana1121bb52011-09-14 23:19:35 -07002204 /**
2205 * Returns an intent to an {@link Activity} that prompts the user to choose from a list of
2206 * accounts.
2207 * The caller will then typically start the activity by calling
Mark Fickettab249e02012-09-05 09:45:47 -04002208 * <code>startActivityForResult(intent, ...);</code>.
Fred Quintana1121bb52011-09-14 23:19:35 -07002209 * <p>
2210 * On success the activity returns a Bundle with the account name and type specified using
2211 * keys {@link #KEY_ACCOUNT_NAME} and {@link #KEY_ACCOUNT_TYPE}.
2212 * <p>
2213 * The most common case is to call this with one account type, e.g.:
2214 * <p>
kmccormickf783ce52013-03-29 14:31:54 -07002215 * <pre> newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null,
Fred Quintanad88324d2011-09-19 11:43:05 -07002216 * null, null, null);</pre>
Fred Quintana1121bb52011-09-14 23:19:35 -07002217 * @param selectedAccount if specified, indicates that the {@link Account} is the currently
2218 * selected one, according to the caller's definition of selected.
2219 * @param allowableAccounts an optional {@link ArrayList} of accounts that are allowed to be
2220 * shown. If not specified then this field will not limit the displayed accounts.
2221 * @param allowableAccountTypes an optional string array of account types. These are used
2222 * both to filter the shown accounts and to filter the list of account types that are shown
2223 * when adding an account.
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002224 * @param alwaysPromptForAccount if set the account chooser screen is always shown, otherwise
2225 * it is only shown when there is more than one account from which to choose
Fred Quintanad88324d2011-09-19 11:43:05 -07002226 * @param descriptionOverrideText if non-null this string is used as the description in the
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002227 * accounts chooser screen rather than the default
Fred Quintanad88324d2011-09-19 11:43:05 -07002228 * @param addAccountAuthTokenType this string is passed as the {@link #addAccount}
2229 * authTokenType parameter
2230 * @param addAccountRequiredFeatures this string array is passed as the {@link #addAccount}
2231 * requiredFeatures parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002232 * @param addAccountOptions This {@link Bundle} is passed as the {@link #addAccount} options
Fred Quintanad88324d2011-09-19 11:43:05 -07002233 * parameter
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002234 * @return an {@link Intent} that can be used to launch the ChooseAccount activity flow.
Fred Quintana1121bb52011-09-14 23:19:35 -07002235 */
2236 static public Intent newChooseAccountIntent(Account selectedAccount,
2237 ArrayList<Account> allowableAccounts,
2238 String[] allowableAccountTypes,
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002239 boolean alwaysPromptForAccount,
2240 String descriptionOverrideText,
2241 String addAccountAuthTokenType,
2242 String[] addAccountRequiredFeatures,
Fred Quintana1121bb52011-09-14 23:19:35 -07002243 Bundle addAccountOptions) {
2244 Intent intent = new Intent();
Amith Yamasani12b8e132013-03-14 10:48:07 -07002245 ComponentName componentName = ComponentName.unflattenFromString(
2246 Resources.getSystem().getString(R.string.config_chooseTypeAndAccountActivity));
2247 intent.setClassName(componentName.getPackageName(),
2248 componentName.getClassName());
Fred Quintana1121bb52011-09-14 23:19:35 -07002249 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST,
2250 allowableAccounts);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002251 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
2252 allowableAccountTypes);
Fred Quintana1121bb52011-09-14 23:19:35 -07002253 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
2254 addAccountOptions);
2255 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_SELECTED_ACCOUNT, selectedAccount);
Fred Quintanab04fe4e2011-09-16 21:17:21 -07002256 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT,
2257 alwaysPromptForAccount);
2258 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_DESCRIPTION_TEXT_OVERRIDE,
2259 descriptionOverrideText);
2260 intent.putExtra(ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
2261 addAccountAuthTokenType);
2262 intent.putExtra(
2263 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
2264 addAccountRequiredFeatures);
Fred Quintana1121bb52011-09-14 23:19:35 -07002265 return intent;
2266 }
2267
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002268 private final HashMap<OnAccountsUpdateListener, Handler> mAccountsUpdatedListeners =
Fred Quintanad9d2f112009-04-23 13:36:27 -07002269 Maps.newHashMap();
2270
Fred Quintanad9d2f112009-04-23 13:36:27 -07002271 /**
2272 * BroadcastReceiver that listens for the LOGIN_ACCOUNTS_CHANGED_ACTION intent
2273 * so that it can read the updated list of accounts and send them to the listener
2274 * in mAccountsUpdatedListeners.
2275 */
2276 private final BroadcastReceiver mAccountsChangedBroadcastReceiver = new BroadcastReceiver() {
2277 public void onReceive(final Context context, final Intent intent) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002278 final Account[] accounts = getAccounts();
2279 // send the result to the listeners
2280 synchronized (mAccountsUpdatedListeners) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002281 for (Map.Entry<OnAccountsUpdateListener, Handler> entry :
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002282 mAccountsUpdatedListeners.entrySet()) {
2283 postToHandler(entry.getValue(), entry.getKey(), accounts);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002284 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002285 }
Fred Quintanad9d2f112009-04-23 13:36:27 -07002286 }
2287 };
2288
2289 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002290 * Adds an {@link OnAccountsUpdateListener} to this instance of the
2291 * {@link AccountManager}. This listener will be notified whenever the
2292 * list of accounts on the device changes.
2293 *
2294 * <p>As long as this listener is present, the AccountManager instance
2295 * will not be garbage-collected, and neither will the {@link Context}
2296 * used to retrieve it, which may be a large Activity instance. To avoid
2297 * memory leaks, you must remove this listener before then. Normally
2298 * listeners are added in an Activity or Service's {@link Activity#onCreate}
2299 * and removed in {@link Activity#onDestroy}.
2300 *
2301 * <p>It is safe to call this method from the main thread.
2302 *
Nicolas Falliere9530e3a2012-06-18 17:21:06 -07002303 * <p>This method requires the caller to hold the permission
2304 * {@link android.Manifest.permission#GET_ACCOUNTS}.
Dan Egnor661f0132010-02-19 11:23:00 -08002305 *
2306 * @param listener The listener to send notifications to
2307 * @param handler {@link Handler} identifying the thread to use
2308 * for notifications, null for the main thread
2309 * @param updateImmediately If true, the listener will be invoked
2310 * (on the handler thread) right away with the current account list
Fred Quintanad9d2f112009-04-23 13:36:27 -07002311 * @throws IllegalArgumentException if listener is null
2312 * @throws IllegalStateException if listener was already added
2313 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002314 public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener,
Fred Quintanad9d2f112009-04-23 13:36:27 -07002315 Handler handler, boolean updateImmediately) {
2316 if (listener == null) {
2317 throw new IllegalArgumentException("the listener is null");
2318 }
2319 synchronized (mAccountsUpdatedListeners) {
2320 if (mAccountsUpdatedListeners.containsKey(listener)) {
2321 throw new IllegalStateException("this listener is already added");
2322 }
2323 final boolean wasEmpty = mAccountsUpdatedListeners.isEmpty();
2324
2325 mAccountsUpdatedListeners.put(listener, handler);
2326
2327 if (wasEmpty) {
2328 // Register a broadcast receiver to monitor account changes
2329 IntentFilter intentFilter = new IntentFilter();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002330 intentFilter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
Costin Manolacheb6437242009-09-10 16:14:12 -07002331 // To recover from disk-full.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002332 intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002333 mContext.registerReceiver(mAccountsChangedBroadcastReceiver, intentFilter);
2334 }
2335 }
2336
2337 if (updateImmediately) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002338 postToHandler(handler, listener, getAccounts());
Fred Quintanad9d2f112009-04-23 13:36:27 -07002339 }
2340 }
2341
2342 /**
Dan Egnor661f0132010-02-19 11:23:00 -08002343 * Removes an {@link OnAccountsUpdateListener} previously registered with
2344 * {@link #addOnAccountsUpdatedListener}. The listener will no longer
2345 * receive notifications of account changes.
2346 *
2347 * <p>It is safe to call this method from the main thread.
2348 *
2349 * <p>No permission is required to call this method.
2350 *
2351 * @param listener The previously added listener to remove
Fred Quintanad9d2f112009-04-23 13:36:27 -07002352 * @throws IllegalArgumentException if listener is null
2353 * @throws IllegalStateException if listener was not already added
2354 */
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002355 public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) {
Fred Quintana382601f2010-03-25 12:25:10 -07002356 if (listener == null) throw new IllegalArgumentException("listener is null");
Fred Quintanad9d2f112009-04-23 13:36:27 -07002357 synchronized (mAccountsUpdatedListeners) {
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002358 if (!mAccountsUpdatedListeners.containsKey(listener)) {
Costin Manolache88a211b2009-10-29 11:30:11 -07002359 Log.e(TAG, "Listener was not previously added");
2360 return;
Fred Quintanad9d2f112009-04-23 13:36:27 -07002361 }
Bryan Mawhinney5be61f52009-09-24 14:50:25 +01002362 mAccountsUpdatedListeners.remove(listener);
Fred Quintanad9d2f112009-04-23 13:36:27 -07002363 if (mAccountsUpdatedListeners.isEmpty()) {
2364 mContext.unregisterReceiver(mAccountsChangedBroadcastReceiver);
2365 }
2366 }
2367 }
Fred Quintana60307342009-03-24 22:48:12 -07002368}