• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 package android.accounts;
17 
18 import static android.app.admin.DevicePolicyResources.Strings.Core.CANT_ADD_ACCOUNT_MESSAGE;
19 
20 import android.app.Activity;
21 import android.app.admin.DevicePolicyManager;
22 import android.content.Intent;
23 import android.os.Bundle;
24 import android.os.Parcelable;
25 import android.os.UserHandle;
26 import android.os.UserManager;
27 import android.text.TextUtils;
28 import android.util.Log;
29 import android.view.View;
30 import android.view.Window;
31 import android.widget.AdapterView;
32 import android.widget.ArrayAdapter;
33 import android.widget.Button;
34 import android.widget.ListView;
35 import android.widget.TextView;
36 
37 import com.android.internal.R;
38 
39 import com.google.android.collect.Sets;
40 
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.HashSet;
44 import java.util.LinkedHashMap;
45 import java.util.Map;
46 import java.util.Set;
47 
48 /**
49  * @hide
50  */
51 public class ChooseTypeAndAccountActivity extends Activity
52         implements AccountManagerCallback<Bundle> {
53     private static final String TAG = "AccountChooser";
54 
55     /**
56      * A Parcelable ArrayList of Account objects that limits the choosable accounts to those
57      * in this list, if this parameter is supplied.
58      */
59     public static final String EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST = "allowableAccounts";
60 
61     /**
62      * A Parcelable ArrayList of String objects that limits the accounts to choose to those
63      * that match the types in this list, if this parameter is supplied. This list is also
64      * used to filter the allowable account types if add account is selected.
65      */
66     public static final String EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY = "allowableAccountTypes";
67 
68     /**
69      * This is passed as the addAccountOptions parameter in AccountManager.addAccount()
70      * if it is called.
71      */
72     public static final String EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE = "addAccountOptions";
73 
74     /**
75      * This is passed as the requiredFeatures parameter in AccountManager.addAccount()
76      * if it is called.
77      */
78     public static final String EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY =
79             "addAccountRequiredFeatures";
80 
81     /**
82      * This is passed as the authTokenType string in AccountManager.addAccount()
83      * if it is called.
84      */
85     public static final String EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING = "authTokenType";
86 
87     /**
88      * If set then the specified account is already "selected".
89      */
90     public static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
91 
92     /**
93      * Deprecated. Providing this extra to {@link ChooseTypeAndAccountActivity}
94      * will have no effect.
95      */
96     @Deprecated
97     public static final String EXTRA_ALWAYS_PROMPT_FOR_ACCOUNT =
98             "alwaysPromptForAccount";
99 
100     /**
101      * If set then this string will be used as the description rather than
102      * the default.
103      */
104     public static final String EXTRA_DESCRIPTION_TEXT_OVERRIDE = "descriptionTextOverride";
105 
106     public static final int REQUEST_NULL = 0;
107     public static final int REQUEST_CHOOSE_TYPE = 1;
108     public static final int REQUEST_ADD_ACCOUNT = 2;
109 
110     private static final String KEY_INSTANCE_STATE_PENDING_REQUEST = "pendingRequest";
111     private static final String KEY_INSTANCE_STATE_EXISTING_ACCOUNTS = "existingAccounts";
112     private static final String KEY_INSTANCE_STATE_SELECTED_ACCOUNT_NAME = "selectedAccountName";
113     private static final String KEY_INSTANCE_STATE_SELECTED_ADD_ACCOUNT = "selectedAddAccount";
114     private static final String KEY_INSTANCE_STATE_ACCOUNTS_LIST = "accountsList";
115     private static final String KEY_INSTANCE_STATE_VISIBILITY_LIST = "visibilityList";
116 
117     private static final int SELECTED_ITEM_NONE = -1;
118 
119     private Set<Account> mSetOfAllowableAccounts;
120     private Set<String> mSetOfRelevantAccountTypes;
121     private String mSelectedAccountName = null;
122     private boolean mSelectedAddNewAccount = false;
123     private String mDescriptionOverride;
124 
125     private LinkedHashMap<Account, Integer> mAccounts;
126     // TODO Redesign flow to show NOT_VISIBLE accounts
127     // and display a warning if they are selected.
128     // Currently NOT_VISBILE accounts are not shown at all.
129     private ArrayList<Account> mPossiblyVisibleAccounts;
130     private int mPendingRequest = REQUEST_NULL;
131     private Parcelable[] mExistingAccounts = null;
132     private int mSelectedItemIndex;
133     private Button mOkButton;
134     private int mCallingUid;
135     private String mCallingPackage;
136     private boolean mDisallowAddAccounts;
137     private boolean mDontShowPicker;
138 
139     @Override
onCreate(Bundle savedInstanceState)140     public void onCreate(Bundle savedInstanceState) {
141         if (Log.isLoggable(TAG, Log.VERBOSE)) {
142             Log.v(TAG, "ChooseTypeAndAccountActivity.onCreate(savedInstanceState="
143                     + savedInstanceState + ")");
144         }
145         getWindow().addSystemFlags(
146                 android.view.WindowManager.LayoutParams
147                         .SYSTEM_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS);
148 
149         mCallingUid = getLaunchedFromUid();
150         mCallingPackage = getLaunchedFromPackage();
151         if (mCallingUid != 0 && mCallingPackage != null) {
152             Bundle restrictions = UserManager.get(this)
153                     .getUserRestrictions(new UserHandle(UserHandle.getUserId(mCallingUid)));
154             mDisallowAddAccounts =
155                     restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false);
156         }
157 
158         // save some items we use frequently
159         final Intent intent = getIntent();
160 
161         mSetOfAllowableAccounts = getAllowableAccountSet(intent);
162         mSetOfRelevantAccountTypes = getReleventAccountTypes(intent);
163         mDescriptionOverride = intent.getStringExtra(EXTRA_DESCRIPTION_TEXT_OVERRIDE);
164 
165         if (savedInstanceState != null) {
166             mPendingRequest = savedInstanceState.getInt(KEY_INSTANCE_STATE_PENDING_REQUEST);
167             mExistingAccounts =
168                     savedInstanceState.getParcelableArray(KEY_INSTANCE_STATE_EXISTING_ACCOUNTS);
169 
170             // Makes sure that any user selection is preserved across orientation changes.
171             mSelectedAccountName =
172                     savedInstanceState.getString(KEY_INSTANCE_STATE_SELECTED_ACCOUNT_NAME);
173             mSelectedAddNewAccount =
174                     savedInstanceState.getBoolean(KEY_INSTANCE_STATE_SELECTED_ADD_ACCOUNT, false);
175             // restore mAccounts
176             Parcelable[] accounts =
177                 savedInstanceState.getParcelableArray(KEY_INSTANCE_STATE_ACCOUNTS_LIST);
178             ArrayList<Integer> visibility =
179                 savedInstanceState.getIntegerArrayList(KEY_INSTANCE_STATE_VISIBILITY_LIST);
180             mAccounts = new LinkedHashMap<>();
181             for (int i = 0; i < accounts.length; i++) {
182                 mAccounts.put((Account) accounts[i], visibility.get(i));
183             }
184         } else {
185             mPendingRequest = REQUEST_NULL;
186             mExistingAccounts = null;
187             // If the selected account as specified in the intent matches one in the list we will
188             // show is as pre-selected.
189             Account selectedAccount = (Account) intent.getParcelableExtra(EXTRA_SELECTED_ACCOUNT);
190             if (selectedAccount != null) {
191                 mSelectedAccountName = selectedAccount.name;
192             }
193             mAccounts = getAcceptableAccountChoices(AccountManager.get(this));
194         }
195 
196         mPossiblyVisibleAccounts = new ArrayList<>(mAccounts.size());
197         for (Map.Entry<Account, Integer> entry : mAccounts.entrySet()) {
198             if (AccountManager.VISIBILITY_NOT_VISIBLE != entry.getValue()) {
199                 mPossiblyVisibleAccounts.add(entry.getKey());
200             }
201         }
202 
203         if (mPossiblyVisibleAccounts.isEmpty() && mDisallowAddAccounts) {
204             requestWindowFeature(Window.FEATURE_NO_TITLE);
205 
206             setContentView(R.layout.app_not_authorized);
207             TextView view = findViewById(R.id.description);
208             String text = getSystemService(DevicePolicyManager.class).getResources().getString(
209                     CANT_ADD_ACCOUNT_MESSAGE,
210                     () -> getString(R.string.error_message_change_not_allowed));
211             view.setText(text);
212 
213             mDontShowPicker = true;
214         }
215 
216         if (mDontShowPicker) {
217             super.onCreate(savedInstanceState);
218             return;
219         }
220 
221         // In cases where the activity does not need to show an account picker, cut the chase
222         // and return the result directly. Eg:
223         // Single account -> select it directly
224         // No account -> launch add account activity directly
225         if (mPendingRequest == REQUEST_NULL) {
226             // If there are no relevant accounts and only one relevant account type go directly to
227             // add account. Otherwise let the user choose.
228             if (mPossiblyVisibleAccounts.isEmpty()) {
229                 setNonLabelThemeAndCallSuperCreate(savedInstanceState);
230                 if (mSetOfRelevantAccountTypes.size() == 1) {
231                     runAddAccountForAuthenticator(mSetOfRelevantAccountTypes.iterator().next());
232                 } else {
233                     startChooseAccountTypeActivity();
234                 }
235             }
236         }
237 
238         String[] listItems = getListOfDisplayableOptions(mPossiblyVisibleAccounts);
239         mSelectedItemIndex = getItemIndexToSelect(mPossiblyVisibleAccounts, mSelectedAccountName,
240                 mSelectedAddNewAccount);
241 
242         super.onCreate(savedInstanceState);
243         setContentView(R.layout.choose_type_and_account);
244         overrideDescriptionIfSupplied(mDescriptionOverride);
245         populateUIAccountList(listItems);
246 
247         // Only enable "OK" button if something has been selected.
248         mOkButton = findViewById(android.R.id.button2);
249         mOkButton.setEnabled(mSelectedItemIndex != SELECTED_ITEM_NONE);
250     }
251 
252     @Override
onDestroy()253     protected void onDestroy() {
254         if (Log.isLoggable(TAG, Log.VERBOSE)) {
255             Log.v(TAG, "ChooseTypeAndAccountActivity.onDestroy()");
256         }
257         super.onDestroy();
258     }
259 
260     @Override
onSaveInstanceState(final Bundle outState)261     protected void onSaveInstanceState(final Bundle outState) {
262         super.onSaveInstanceState(outState);
263         outState.putInt(KEY_INSTANCE_STATE_PENDING_REQUEST, mPendingRequest);
264         if (mPendingRequest == REQUEST_ADD_ACCOUNT) {
265             outState.putParcelableArray(KEY_INSTANCE_STATE_EXISTING_ACCOUNTS, mExistingAccounts);
266         }
267         if (mSelectedItemIndex != SELECTED_ITEM_NONE) {
268             if (mSelectedItemIndex == mPossiblyVisibleAccounts.size()) {
269                 outState.putBoolean(KEY_INSTANCE_STATE_SELECTED_ADD_ACCOUNT, true);
270             } else {
271                 outState.putBoolean(KEY_INSTANCE_STATE_SELECTED_ADD_ACCOUNT, false);
272                 outState.putString(KEY_INSTANCE_STATE_SELECTED_ACCOUNT_NAME,
273                         mPossiblyVisibleAccounts.get(mSelectedItemIndex).name);
274             }
275         }
276         // save mAccounts
277         Parcelable[] accounts = new Parcelable[mAccounts.size()];
278         ArrayList<Integer> visibility = new ArrayList<>(mAccounts.size());
279         int i = 0;
280         for (Map.Entry<Account, Integer> e : mAccounts.entrySet()) {
281             accounts[i++] = e.getKey();
282             visibility.add(e.getValue());
283         }
284         outState.putParcelableArray(KEY_INSTANCE_STATE_ACCOUNTS_LIST, accounts);
285         outState.putIntegerArrayList(KEY_INSTANCE_STATE_VISIBILITY_LIST, visibility);
286     }
287 
onCancelButtonClicked(View view)288     public void onCancelButtonClicked(View view) {
289         onBackPressed();
290     }
291 
onOkButtonClicked(View view)292     public void onOkButtonClicked(View view) {
293         if (mSelectedItemIndex == mPossiblyVisibleAccounts.size()) {
294             // Selected "Add New Account" option
295             startChooseAccountTypeActivity();
296         } else if (mSelectedItemIndex != SELECTED_ITEM_NONE) {
297             onAccountSelected(mPossiblyVisibleAccounts.get(mSelectedItemIndex));
298         }
299     }
300 
301     // Called when the choose account type activity (for adding an account) returns.
302     // If it was a success read the account and set it in the result. In all cases
303     // return the result and finish this activity.
304     @Override
onActivityResult(final int requestCode, final int resultCode, final Intent data)305     protected void onActivityResult(final int requestCode, final int resultCode,
306             final Intent data) {
307         if (Log.isLoggable(TAG, Log.VERBOSE)) {
308             if (data != null && data.getExtras() != null) data.getExtras().keySet();
309             Bundle extras = data != null ? data.getExtras() : null;
310             Log.v(TAG, "ChooseTypeAndAccountActivity.onActivityResult(reqCode=" + requestCode
311                     + ", resCode=" + resultCode + ")");
312         }
313 
314         // we got our result, so clear the fact that we had a pending request
315         mPendingRequest = REQUEST_NULL;
316 
317         if (resultCode == RESULT_CANCELED) {
318             // if canceling out of addAccount and the original state caused us to skip this,
319             // finish this activity
320             if (mPossiblyVisibleAccounts.isEmpty()) {
321                 setResult(Activity.RESULT_CANCELED);
322                 finish();
323             }
324             return;
325         }
326 
327         if (resultCode == RESULT_OK) {
328             if (requestCode == REQUEST_CHOOSE_TYPE) {
329                 if (data != null) {
330                     String accountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
331                     if (accountType != null) {
332                         runAddAccountForAuthenticator(accountType);
333                         return;
334                     }
335                 }
336                 Log.d(TAG, "ChooseTypeAndAccountActivity.onActivityResult: unable to find account "
337                         + "type, pretending the request was canceled");
338             } else if (requestCode == REQUEST_ADD_ACCOUNT) {
339                 String accountName = null;
340                 String accountType = null;
341 
342                 if (data != null) {
343                     accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
344                     accountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
345                 }
346 
347                 if (accountName == null || accountType == null) {
348                     // new account was added.
349                     Account[] currentAccounts = AccountManager.get(this).getAccountsForPackage(
350                             mCallingPackage, mCallingUid);
351                     Set<Account> preExistingAccounts = new HashSet<Account>();
352                     for (Parcelable accountParcel : mExistingAccounts) {
353                         preExistingAccounts.add((Account) accountParcel);
354                     }
355                     for (Account account : currentAccounts) {
356                         // New account is visible to the app - return it.
357                         if (!preExistingAccounts.contains(account)) {
358                             accountName = account.name;
359                             accountType = account.type;
360                             break;
361                         }
362                     }
363                 }
364 
365                 if (accountName != null || accountType != null) {
366                     setResultAndFinish(accountName, accountType);
367                     return;
368                 }
369             }
370             Log.d(TAG, "ChooseTypeAndAccountActivity.onActivityResult: unable to find added "
371                     + "account, pretending the request was canceled");
372         }
373         if (Log.isLoggable(TAG, Log.VERBOSE)) {
374             Log.v(TAG, "ChooseTypeAndAccountActivity.onActivityResult: canceled");
375         }
376         setResult(Activity.RESULT_CANCELED);
377         finish();
378     }
379 
runAddAccountForAuthenticator(String type)380     protected void runAddAccountForAuthenticator(String type) {
381         if (Log.isLoggable(TAG, Log.VERBOSE)) {
382             Log.v(TAG, "runAddAccountForAuthenticator: " + type);
383         }
384         final Bundle options = getIntent().getBundleExtra(
385                 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE);
386         final String[] requiredFeatures = getIntent().getStringArrayExtra(
387                 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY);
388         final String authTokenType = getIntent().getStringExtra(
389                 ChooseTypeAndAccountActivity.EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING);
390         AccountManager.get(this).addAccount(type, authTokenType, requiredFeatures,
391                 options, null /* activity */, this /* callback */, null /* Handler */);
392     }
393 
394     @Override
run(final AccountManagerFuture<Bundle> accountManagerFuture)395     public void run(final AccountManagerFuture<Bundle> accountManagerFuture) {
396         try {
397             final Bundle accountManagerResult = accountManagerFuture.getResult();
398             final Intent intent = (Intent)accountManagerResult.getParcelable(
399                     AccountManager.KEY_INTENT);
400             if (intent != null) {
401                 mPendingRequest = REQUEST_ADD_ACCOUNT;
402                 mExistingAccounts = AccountManager.get(this).getAccountsForPackage(mCallingPackage,
403                         mCallingUid);
404                 intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
405                 startActivityForResult(new Intent(intent), REQUEST_ADD_ACCOUNT);
406                 return;
407             }
408         } catch (OperationCanceledException e) {
409             setResult(Activity.RESULT_CANCELED);
410             finish();
411             return;
412         } catch (IOException e) {
413         } catch (AuthenticatorException e) {
414         }
415         Bundle bundle = new Bundle();
416         bundle.putString(AccountManager.KEY_ERROR_MESSAGE, "error communicating with server");
417         setResult(Activity.RESULT_OK, new Intent().putExtras(bundle));
418         finish();
419     }
420 
421     /**
422      * The default activity theme shows label at the top. Set a theme which does
423      * not show label, which effectively makes the activity invisible. Note that
424      * no content is being set. If something gets set, using this theme may be
425      * useless.
426      */
setNonLabelThemeAndCallSuperCreate(Bundle savedInstanceState)427     private void setNonLabelThemeAndCallSuperCreate(Bundle savedInstanceState) {
428         setTheme(R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar);
429         super.onCreate(savedInstanceState);
430     }
431 
onAccountSelected(Account account)432     private void onAccountSelected(Account account) {
433         Log.d(TAG, "selected account " + account.toSafeString());
434         setResultAndFinish(account.name, account.type);
435     }
436 
setResultAndFinish(final String accountName, final String accountType)437     private void setResultAndFinish(final String accountName, final String accountType) {
438         // Mark account as visible since user chose it.
439         Account account = new Account(accountName, accountType);
440         Integer oldVisibility =
441             AccountManager.get(this).getAccountVisibility(account, mCallingPackage);
442         if (oldVisibility != null
443                 && oldVisibility == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE) {
444             AccountManager.get(this).setAccountVisibility(account, mCallingPackage,
445                     AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
446         }
447 
448         if (oldVisibility != null && oldVisibility == AccountManager.VISIBILITY_NOT_VISIBLE) {
449             // Added account is not visible to caller.
450             setResult(Activity.RESULT_CANCELED);
451             finish();
452             return;
453         }
454         Bundle bundle = new Bundle();
455         bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
456         bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
457         setResult(Activity.RESULT_OK, new Intent().putExtras(bundle));
458         if (Log.isLoggable(TAG, Log.VERBOSE)) {
459             Log.v(TAG, "ChooseTypeAndAccountActivity.setResultAndFinish: selected account "
460                     + account.toSafeString());
461         }
462         finish();
463     }
464 
startChooseAccountTypeActivity()465     private void startChooseAccountTypeActivity() {
466         if (Log.isLoggable(TAG, Log.VERBOSE)) {
467             Log.v(TAG, "ChooseAccountTypeActivity.startChooseAccountTypeActivity()");
468         }
469         final Intent intent = new Intent(this, ChooseAccountTypeActivity.class);
470         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
471         intent.putExtra(EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
472                 getIntent().getStringArrayExtra(EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY));
473         intent.putExtra(EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE,
474                 getIntent().getBundleExtra(EXTRA_ADD_ACCOUNT_OPTIONS_BUNDLE));
475         intent.putExtra(EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY,
476                 getIntent().getStringArrayExtra(EXTRA_ADD_ACCOUNT_REQUIRED_FEATURES_STRING_ARRAY));
477         intent.putExtra(EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING,
478                 getIntent().getStringExtra(EXTRA_ADD_ACCOUNT_AUTH_TOKEN_TYPE_STRING));
479         startActivityForResult(intent, REQUEST_CHOOSE_TYPE);
480         mPendingRequest = REQUEST_CHOOSE_TYPE;
481     }
482 
483     /**
484      * @return a value between 0 (inclusive) and accounts.size() (inclusive) or SELECTED_ITEM_NONE.
485      *      An index value of accounts.size() indicates 'Add account' option.
486      */
getItemIndexToSelect(ArrayList<Account> accounts, String selectedAccountName, boolean selectedAddNewAccount)487     private int getItemIndexToSelect(ArrayList<Account> accounts, String selectedAccountName,
488         boolean selectedAddNewAccount) {
489       // If "Add account" option was previously selected by user, preserve it across
490       // orientation changes.
491       if (selectedAddNewAccount) {
492           return accounts.size();
493       }
494       // search for the selected account name if present
495       for (int i = 0; i < accounts.size(); i++) {
496         if (accounts.get(i).name.equals(selectedAccountName)) {
497           return i;
498         }
499       }
500       // no account selected.
501       return SELECTED_ITEM_NONE;
502     }
503 
getListOfDisplayableOptions(ArrayList<Account> accounts)504     private String[] getListOfDisplayableOptions(ArrayList<Account> accounts) {
505       // List of options includes all accounts found together with "Add new account" as the
506       // last item in the list.
507       String[] listItems = new String[accounts.size() + (mDisallowAddAccounts ? 0 : 1)];
508       for (int i = 0; i < accounts.size(); i++) {
509           listItems[i] = accounts.get(i).name;
510       }
511       if (!mDisallowAddAccounts) {
512           listItems[accounts.size()] = getResources().getString(
513                   R.string.add_account_button_label);
514       }
515       return listItems;
516     }
517 
518     /**
519      * Create a list of Account objects for each account that is acceptable. Filter out accounts
520      * that don't match the allowable types, if provided, or that don't match the allowable
521      * accounts, if provided.
522      */
getAcceptableAccountChoices(AccountManager accountManager)523     private LinkedHashMap<Account, Integer> getAcceptableAccountChoices(AccountManager accountManager) {
524         Map<Account, Integer> accountsAndVisibilityForCaller =
525                 accountManager.getAccountsAndVisibilityForPackage(mCallingPackage, null);
526         Account[] allAccounts = accountManager.getAccounts();
527         LinkedHashMap<Account, Integer> accountsToPopulate =
528                 new LinkedHashMap<>(accountsAndVisibilityForCaller.size());
529         for (Account account : allAccounts) {
530             if (mSetOfAllowableAccounts != null
531                     && !mSetOfAllowableAccounts.contains(account)) {
532                 continue;
533             }
534             if (mSetOfRelevantAccountTypes != null
535                     && !mSetOfRelevantAccountTypes.contains(account.type)) {
536                 continue;
537             }
538             if (accountsAndVisibilityForCaller.get(account) != null) {
539                 accountsToPopulate.put(account, accountsAndVisibilityForCaller.get(account));
540             }
541         }
542         return accountsToPopulate;
543     }
544 
545     /**
546      * Return a set of account types specified by the intent as well as supported by the
547      * AccountManager.
548      */
getReleventAccountTypes(final Intent intent)549     private Set<String> getReleventAccountTypes(final Intent intent) {
550       // An account type is relevant iff it is allowed by the caller and supported by the account
551       // manager.
552       Set<String> setOfRelevantAccountTypes = null;
553       final String[] allowedAccountTypes =
554               intent.getStringArrayExtra(EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY);
555         AuthenticatorDescription[] descs = AccountManager.get(this).getAuthenticatorTypes();
556         Set<String> supportedAccountTypes = new HashSet<String>(descs.length);
557         for (AuthenticatorDescription desc : descs) {
558             supportedAccountTypes.add(desc.type);
559         }
560         if (allowedAccountTypes != null) {
561             setOfRelevantAccountTypes = Sets.newHashSet(allowedAccountTypes);
562             setOfRelevantAccountTypes.retainAll(supportedAccountTypes);
563         } else {
564             setOfRelevantAccountTypes = supportedAccountTypes;
565       }
566       return setOfRelevantAccountTypes;
567     }
568 
569     /**
570      * Returns a set of allowlisted accounts given by the intent or null if none specified by the
571      * intent.
572      */
getAllowableAccountSet(final Intent intent)573     private Set<Account> getAllowableAccountSet(final Intent intent) {
574       Set<Account> setOfAllowableAccounts = null;
575       final ArrayList<Parcelable> validAccounts =
576               intent.getParcelableArrayListExtra(EXTRA_ALLOWABLE_ACCOUNTS_ARRAYLIST);
577       if (validAccounts != null) {
578           setOfAllowableAccounts = new HashSet<Account>(validAccounts.size());
579           for (Parcelable parcelable : validAccounts) {
580               setOfAllowableAccounts.add((Account)parcelable);
581           }
582       }
583       return setOfAllowableAccounts;
584     }
585 
586     /**
587      * Overrides the description text view for the picker activity if specified by the intent.
588      * If not specified then makes the description invisible.
589      */
overrideDescriptionIfSupplied(String descriptionOverride)590     private void overrideDescriptionIfSupplied(String descriptionOverride) {
591       TextView descriptionView = findViewById(R.id.description);
592       if (!TextUtils.isEmpty(descriptionOverride)) {
593           descriptionView.setText(descriptionOverride);
594       } else {
595           descriptionView.setVisibility(View.GONE);
596       }
597     }
598 
599     /**
600      * Populates the UI ListView with the given list of items and selects an item
601      * based on {@code mSelectedItemIndex} member variable.
602      */
populateUIAccountList(String[] listItems)603     private final void populateUIAccountList(String[] listItems) {
604       ListView list = findViewById(android.R.id.list);
605       list.setAdapter(new ArrayAdapter<String>(this,
606               android.R.layout.simple_list_item_single_choice, listItems));
607       list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
608       list.setItemsCanFocus(false);
609       list.setOnItemClickListener(
610               new AdapterView.OnItemClickListener() {
611                   @Override
612                   public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
613                       mSelectedItemIndex = position;
614                       mOkButton.setEnabled(true);
615                   }
616               });
617       if (mSelectedItemIndex != SELECTED_ITEM_NONE) {
618           list.setItemChecked(mSelectedItemIndex, true);
619           if (Log.isLoggable(TAG, Log.VERBOSE)) {
620               Log.v(TAG, "List item " + mSelectedItemIndex + " should be selected");
621           }
622       }
623     }
624 }
625