gt:         if (addCategory) {
context: /*
   * Copyright (C) 2014 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package com.android.settings.accounts;
  
  
  import android.accounts.Account;
  import android.accounts.AccountManager;
  import android.app.ActivityManager;
  import android.app.AlertDialog;
  import android.app.Dialog;
  import android.app.DialogFragment;
  import android.content.BroadcastReceiver;
  import android.content.ContentResolver;
  import android.content.Context;
  import android.content.DialogInterface;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.content.pm.UserInfo;
  import android.graphics.drawable.Drawable;
  import android.os.Bundle;
  import android.os.UserHandle;
  import android.os.UserManager;
  import android.os.Process;
  import android.util.Log;
  import android.util.SparseArray;
  import android.view.Menu;
  import android.view.MenuInflater;
  import android.view.MenuItem;
  import android.preference.Preference;
  import android.preference.Preference.OnPreferenceClickListener;
  import android.preference.PreferenceGroup;
  import android.preference.PreferenceCategory;
  import android.preference.PreferenceScreen;
  
  import com.android.settings.R;
  import com.android.settings.SettingsPreferenceFragment;
  import com.android.settings.Utils;
  
  import java.util.ArrayList;
  import java.util.Collections;
  import java.util.Comparator;
  import java.util.List;
  
  import static android.content.Intent.EXTRA_USER;
  import static android.os.UserManager.DISALLOW_MODIFY_ACCOUNTS;
  import static android.provider.Settings.EXTRA_AUTHORITIES;
  
  /**
   * Settings screen for the account types on the device.
   * This shows all account types available for personal and work profiles.
   *
   * An extra {@link UserHandle} can be specified in the intent as {@link EXTRA_USER}, if the user for
   * which the action needs to be performed is different to the one the Settings App will run in.
   */
  public class AccountSettings extends SettingsPreferenceFragment
          implements AuthenticatorHelper.OnAccountsUpdateListener,
          OnPreferenceClickListener {
      public static final String TAG = "AccountSettings";
  
      private static final String KEY_ACCOUNT = "account";
  
      private static final String ADD_ACCOUNT_ACTION = "android.settings.ADD_ACCOUNT_SETTINGS";
      private static final String TAG_CONFIRM_AUTO_SYNC_CHANGE = "confirmAutoSyncChange";
  
      private static final int ORDER_LAST = 1001;
      private static final int ORDER_NEXT_TO_LAST = 1000;
  
      private UserManager mUm;
      private SparseArray<ProfileData> mProfiles = new SparseArray<ProfileData>();
      private ManagedProfileBroadcastReceiver mManagedProfileBroadcastReceiver
                  = new ManagedProfileBroadcastReceiver();
      private Preference mProfileNotAvailablePreference;
      private String[] mAuthorities;
      private int mAuthoritiesCount = 0;
  
      /**
       * Holds data related to the accounts belonging to one profile.
       */
      private static class ProfileData {
          /**
           * The preference that displays the accounts.
           */
          public PreferenceGroup preferenceGroup;
          /**
           * The preference that displays the add account button.
           */
          public Preference addAccountPreference;
          /**
           * The preference that displays the button to remove the managed profile
           */
          public Preference removeWorkProfilePreference;
          /**
           * The {@link AuthenticatorHelper} that holds accounts data for this profile.
           */
          public AuthenticatorHelper authenticatorHelper;
          /**
           * The {@link UserInfo} of the profile.
           */
          public UserInfo userInfo;
      }
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          mUm = (UserManager) getSystemService(Context.USER_SERVICE);
          mProfileNotAvailablePreference = new Preference(getActivity());
          mAuthorities = getActivity().getIntent().getStringArrayExtra(EXTRA_AUTHORITIES);
          if (mAuthorities != null) {
              mAuthoritiesCount = mAuthorities.length;
          }
          setHasOptionsMenu(true);
      }
  
      @Override
      public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
          inflater.inflate(R.menu.account_settings, menu);
          super.onCreateOptionsMenu(menu, inflater);
      }
  
      @Override
      public void onPrepareOptionsMenu(Menu menu) {
          final UserHandle currentProfile = Process.myUserHandle();
          if (mProfiles.size() == 1) {
              menu.findItem(R.id.account_settings_menu_auto_sync)
                      .setVisible(true)
                      .setOnMenuItemClickListener(new MasterSyncStateClickListener(currentProfile))
                      .setChecked(ContentResolver.getMasterSyncAutomaticallyAsUser(
                              currentProfile.getIdentifier()));
              menu.findItem(R.id.account_settings_menu_auto_sync_personal).setVisible(false);
              menu.findItem(R.id.account_settings_menu_auto_sync_work).setVisible(false);
          } else if (mProfiles.size() > 1) {
              // We assume there's only one managed profile, otherwise UI needs to change
              final UserHandle managedProfile = mProfiles.valueAt(1).userInfo.getUserHandle();
  
              menu.findItem(R.id.account_settings_menu_auto_sync_personal)
                      .setVisible(true)
                      .setOnMenuItemClickListener(new MasterSyncStateClickListener(currentProfile))
                      .setChecked(ContentResolver.getMasterSyncAutomaticallyAsUser(
                              currentProfile.getIdentifier()));
              menu.findItem(R.id.account_settings_menu_auto_sync_work)
                      .setVisible(true)
                      .setOnMenuItemClickListener(new MasterSyncStateClickListener(managedProfile))
                      .setChecked(ContentResolver.getMasterSyncAutomaticallyAsUser(
                              managedProfile.getIdentifier()));
              menu.findItem(R.id.account_settings_menu_auto_sync).setVisible(false);
           } else {
               Log.w(TAG, "Method onPrepareOptionsMenu called before mProfiles was initialized");
           }
      }
  
      @Override
      public void onResume() {
          super.onResume();
          updateUi();
          mManagedProfileBroadcastReceiver.register(getActivity());
          listenToAccountUpdates();
      }
  
      @Override
      public void onPause() {
          super.onPause();
          stopListeningToAccountUpdates();
          mManagedProfileBroadcastReceiver.unregister(getActivity());
          cleanUpPreferences();
      }
  
      @Override
      public void onAccountsUpdate(UserHandle userHandle) {
          final ProfileData profileData = mProfiles.get(userHandle.getIdentifier());
          if (profileData != null) {
              updateAccountTypes(profileData);
          } else {
              Log.w(TAG, "Missing Settings screen for: " + userHandle.getIdentifier());
          }
      }
  
      @Override
      public boolean onPreferenceClick(Preference preference) {
          // Check the preference
          final int count = mProfiles.size();
          for (int i = 0; i < count; i++) {
              ProfileData profileData = mProfiles.valueAt(i);
              if (preference == profileData.addAccountPreference) {
                  Intent intent = new Intent(ADD_ACCOUNT_ACTION);
                  intent.putExtra(EXTRA_USER, profileData.userInfo.getUserHandle());
                  intent.putExtra(EXTRA_AUTHORITIES, mAuthorities);
                  startActivity(intent);
                  return true;
              }
              if (preference == profileData.removeWorkProfilePreference) {
                  final int userId = profileData.userInfo.id;
                  Utils.createRemoveConfirmationDialog(getActivity(), userId,
                          new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {
                                  mUm.removeUser(userId);
                              }
                          }
                  ).show();
                  return true;
              }
          }
          return false;
      }
  
      void updateUi() {
          // Load the preferences from an XML resource
          addPreferencesFromResource(R.xml.account_settings);
  
          if (Utils.isManagedProfile(mUm)) {
              // This should not happen
              Log.e(TAG, "We should not be showing settings for a managed profile");
              finish();
              return;
          }
  
          final PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference(KEY_ACCOUNT);
          if(mUm.isLinkedUser()) {
              // Restricted user or similar
              UserInfo userInfo = mUm.getUserInfo(UserHandle.myUserId());
              updateProfileUi(userInfo, false /* no category needed */, preferenceScreen);
          } else {
              List<UserInfo> profiles = mUm.getProfiles(UserHandle.myUserId());
              final int profilesCount = profiles.size();
              final boolean addCategory = profilesCount > 1;
              for (int i = 0; i < profilesCount; i++) {
                  updateProfileUi(profiles.get(i), addCategory, preferenceScreen);
              }
          }
  
          // Add all preferences, starting with one for the primary profile.
          // Note that we're relying on the ordering given by the SparseArray keys, and on the
          // value of UserHandle.USER_OWNER being smaller than all the rest.
          final int profilesCount = mProfiles.size();
          for (int i = 0; i < profilesCount; i++) {
              ProfileData profileData = mProfiles.valueAt(i);
              if (!profileData.preferenceGroup.equals(preferenceScreen)) {
                  preferenceScreen.addPreference(profileData.preferenceGroup);
              }
              updateAccountTypes(profileData);
          }
      }
  
      private void updateProfileUi(final UserInfo userInfo, boolean addCategory,
              PreferenceScreen parent) {
          final Context context = getActivity();
          final ProfileData profileData = new ProfileData();
          profileData.userInfo = userInfo;
  