// update the channel list ui by channel array
  private void updateChannelUIList() {
    MmsLog.d(LOG_TAG, "updateChannelUIList start");
    mChannelListPreference.removeAll();
    int length = mChannelArray.size();
    for (int i = 0; i < length; i++) {
      Preference channel = new Preference(this);
      int keyId = mChannelArray.get(i).getKeyId();
      String channelName = mChannelArray.get(i).getChannelName();
      int channelId = mChannelArray.get(i).getChannelId();
      boolean channelState = mChannelArray.get(i).getChannelState();
      String title = channelName + "(" + String.valueOf(channelId) + ")";
      channel.setTitle(title);
      final CellBroadcastChannel oldChannel =
          new CellBroadcastChannel(keyId, channelId, channelName, channelState);
      if (channelState) {
        channel.setSummary(R.string.enable);
      } else {
        channel.setSummary(R.string.disable);
      }

      channel.setOnPreferenceClickListener(
          new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
              showEditChannelDialog(oldChannel);
              return false;
            }
          });
      mChannelListPreference.addPreference(channel);
    }
    MmsLog.d(LOG_TAG, "updateChannelUIList end");
  }
  /** Method is beeing called on any click of an preference... */
  public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference.getKey().equals(KEY_WIFI_BASED_SCREEN)) {
      mWifiList = mWifiManager.getConfiguredNetworks();
      if (mWifiList == null) {
        return false;
      }

      for (WifiConfiguration wifi : mWifiList) {
        // Friendly SSID-Name
        String ssid = wifi.SSID.replaceAll("\"", "");
        // Add PreferenceScreen for each network
        PreferenceScreen pref = getPreferenceManager().createPreferenceScreen(this);
        pref.setPersistent(false);
        pref.setKey("wifiNetwork" + ssid);
        pref.setTitle(ssid);

        Intent intent = new Intent(this, ConnectionSettings.class);
        intent.putExtra("SSID", ssid);
        pref.setIntent(intent);
        if (WifiConfiguration.Status.CURRENT == wifi.status) pref.setSummary(R.string.connected);
        else pref.setSummary(R.string.notInRange);
        mWifibasedCategory.addPreference(pref);
      }
    }

    return false;
  }
  private void loadAccountPreference() {
    mAccountCategory.removeAll();

    Preference accountPref = new Preference(this);
    final String defaultAccount = getSyncAccountName(this);
    accountPref.setTitle(getString(R.string.preferences_account_title));
    accountPref.setSummary(getString(R.string.preferences_account_summary));
    accountPref.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          public boolean onPreferenceClick(Preference preference) {
            if (!GTaskSyncService.isSyncing()) {
              if (TextUtils.isEmpty(defaultAccount)) {
                // the first time to set account
                showSelectAccountAlertDialog();
              } else {
                // if the account has already been set, we need to promp
                // user about the risk
                showChangeAccountConfirmAlertDialog();
              }
            } else {
              Toast.makeText(
                      NotesPreferenceActivity.this,
                      R.string.preferences_toast_cannot_change_account,
                      Toast.LENGTH_SHORT)
                  .show();
            }
            return true;
          }
        });

    mAccountCategory.addPreference(accountPref);
  }
Beispiel #4
0
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      requestWindowFeature(Window.FEATURE_NO_TITLE);

      super.onCreate(savedInstanceState);

      setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));

      dmesgMode = getIntent().getBooleanExtra(DMESG_MODE, false);

      PreferenceCategory pc = new PreferenceCategory(this);
      pc.setTitle(R.string.preference);
      getPreferenceScreen().addPreference(pc);

      Preference perfLevel = new Preference(this);
      perfLevel.setKey("level_filter"); // $NON-NLS-1$
      perfLevel.setTitle(R.string.log_level);
      pc.addPreference(perfLevel);

      if (!dmesgMode) {
        Preference perfRingBuffer = new Preference(this);
        perfRingBuffer.setKey(PREF_KEY_RING_BUFFER);
        perfRingBuffer.setTitle(R.string.ring_buffer);
        pc.addPreference(perfRingBuffer);

        Preference perfTagFilter = new Preference(this);
        perfTagFilter.setKey(PREF_KEY_TAG_FILTER);
        perfTagFilter.setTitle(R.string.tag_filter);
        pc.addPreference(perfTagFilter);

        Preference perfPidFilter = new Preference(this);
        perfPidFilter.setKey(PREF_KEY_PID_FILTER);
        perfPidFilter.setTitle(R.string.pid_filter);
        pc.addPreference(perfPidFilter);

        refreshRingBuffer();
        refreshTagFilter();
        refreshPidFilter();
      }

      refreshLevelFilter();

      setResult(RESULT_OK, getIntent());
    }
  private void updateHardKeyboards() {
    mHardKeyboardPreferenceList.clear();
    if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY) {
      final int[] devices = InputDevice.getDeviceIds();
      for (int i = 0; i < devices.length; i++) {
        InputDevice device = InputDevice.getDevice(devices[i]);
        if (device != null && !device.isVirtual() && device.isFullKeyboard()) {
          final String inputDeviceDescriptor = device.getDescriptor();
          final String keyboardLayoutDescriptor =
              mIm.getCurrentKeyboardLayoutForInputDevice(inputDeviceDescriptor);
          final KeyboardLayout keyboardLayout =
              keyboardLayoutDescriptor != null
                  ? mIm.getKeyboardLayout(keyboardLayoutDescriptor)
                  : null;

          final PreferenceScreen pref = new PreferenceScreen(getActivity(), null);
          pref.setTitle(device.getName());
          if (keyboardLayout != null) {
            pref.setSummary(keyboardLayout.toString());
          } else {
            pref.setSummary(R.string.keyboard_layout_default_label);
          }
          pref.setOnPreferenceClickListener(
              new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                  showKeyboardLayoutDialog(inputDeviceDescriptor);
                  return true;
                }
              });
          mHardKeyboardPreferenceList.add(pref);
        }
      }
    }

    if (!mHardKeyboardPreferenceList.isEmpty()) {
      for (int i = mHardKeyboardCategory.getPreferenceCount(); i-- > 0; ) {
        final Preference pref = mHardKeyboardCategory.getPreference(i);
        if (pref.getOrder() < 1000) {
          mHardKeyboardCategory.removePreference(pref);
        }
      }

      Collections.sort(mHardKeyboardPreferenceList);
      final int count = mHardKeyboardPreferenceList.size();
      for (int i = 0; i < count; i++) {
        final Preference pref = mHardKeyboardPreferenceList.get(i);
        pref.setOrder(i);
        mHardKeyboardCategory.addPreference(pref);
      }

      getPreferenceScreen().addPreference(mHardKeyboardCategory);
    } else {
      getPreferenceScreen().removePreference(mHardKeyboardCategory);
    }
  }
  private void updateNetworks(Context context) {
    if (SHOW_MOBILE_CATEGORY && hasReadyMobileRadio(context)) {
      mMobileCategory.removeAll();
      mMobileCategory.addPreference(buildMobilePref(context));
    } else {
      getPreferenceScreen().removePreference(mMobileCategory);
    }

    mWifiCategory.removeAll();
    if (hasWifiRadio(context) && mWifiManager.isWifiEnabled()) {
      for (WifiConfiguration config : mWifiManager.getConfiguredNetworks()) {
        if (config.SSID != null) {
          mWifiCategory.addPreference(buildWifiPref(context, config));
        }
      }
    } else {
      mWifiCategory.addPreference(mWifiDisabled);
    }
  }
Beispiel #7
0
 public static Preference Preference(
     Context paramContext,
     PreferenceCategory paramPreferenceCategory,
     String paramString1,
     String paramString2,
     boolean paramBoolean,
     Preference.OnPreferenceClickListener paramOnPreferenceClickListener) {
   Preference localPreference = new Preference(paramContext);
   localPreference.setTitle(paramString1);
   localPreference.setSummary(paramString2);
   localPreference.setEnabled(paramBoolean);
   if (paramOnPreferenceClickListener != null)
     localPreference.setOnPreferenceClickListener(paramOnPreferenceClickListener);
   paramPreferenceCategory.addPreference(localPreference);
   return localPreference;
 }
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      // this is important because although the handler classes that read
      // these settings
      // are in the same package, they are executed in the context of the
      // hooked package
      getPreferenceManager().setSharedPreferencesMode(Context.MODE_WORLD_READABLE);
      addPreferencesFromResource(R.xml.settings);

      mPrefs = getPreferenceScreen().getSharedPreferences();
      AppPickerPreference.sPrefsFragment = this;
      AppPickerPreference.cleanupAsync(getActivity());

      PreferenceCategory mPrefCatLsShortcuts =
          (PreferenceCategory) findPreference(PREF_CAT_KEY_LOCKSCREEN_SHORTCUTS);
      mPrefs = getPreferenceManager().getSharedPreferences();

      if (isPackageInstalled(getActivity(), "com.ceco.lollipop.gravitybox")
          && mPrefs.getBoolean("welcome", true)) {
        AlertDialog alert =
            new AlertDialog.Builder(getActivity())
                .setTitle(R.string.warning)
                .setMessage(R.string.gravitybox_installed)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, null)
                .create();
        alert.show();

        mPrefs.edit().putBoolean("welcome", false).apply();
      }

      for (int i = 0; i < PREF_KEY_LOCKSCREEN_SHORTCUT.size(); i++) {
        AppPickerPreference appPref = new AppPickerPreference(getActivity(), null);
        appPref.setKey(PREF_KEY_LOCKSCREEN_SHORTCUT.get(i));
        appPref.setTitle(String.format(getString(R.string.pref_app_launcher_slot_title), i + 1));
        appPref.setDialogTitle(appPref.getTitle());
        appPref.setDefaultSummary(getString(R.string.app_picker_none));
        appPref.setSummary(getString(R.string.app_picker_none));
        mPrefCatLsShortcuts.addPreference(appPref);
        if (mPrefs.getString(appPref.getKey(), null) == null) {
          mPrefs.edit().putString(appPref.getKey(), null).apply();
        }
      }
    }
Beispiel #9
0
 public static CheckBoxPreference Check(
     Context paramContext,
     PreferenceCategory paramPreferenceCategory,
     String paramString1,
     String paramString2,
     String paramString3,
     Object paramObject,
     boolean paramBoolean) {
   CheckBoxPreference localCheckBoxPreference = new CheckBoxPreference(paramContext);
   localCheckBoxPreference.setTitle(paramString1);
   localCheckBoxPreference.setSummary(paramString2);
   localCheckBoxPreference.setEnabled(paramBoolean);
   localCheckBoxPreference.setKey(paramString3);
   localCheckBoxPreference.setDefaultValue(paramObject);
   paramPreferenceCategory.addPreference(localCheckBoxPreference);
   return localCheckBoxPreference;
 }
 protected void updateSyncServerPreference() {
   final String syncServer = fxAccount.getTokenServerURI();
   final boolean shouldBeShown =
       ALWAYS_SHOW_SYNC_SERVER
           || !FxAccountConstants.DEFAULT_TOKEN_SERVER_ENDPOINT.equals(syncServer);
   final boolean currentlyShown = null != findPreference(syncServerPreference.getKey());
   if (currentlyShown != shouldBeShown) {
     if (shouldBeShown) {
       syncCategory.addPreference(syncServerPreference);
     } else {
       syncCategory.removePreference(syncServerPreference);
     }
   }
   // Always set the summary, because on first run, the preference is visible,
   // and the above block will be skipped if there is a custom value.
   syncServerPreference.setSummary(syncServer);
 }
 /**
  * Show at most one error preference, hiding all others.
  *
  * @param errorPreferenceToShow single error preference to show; if null, hide all error
  *     preferences
  */
 protected void showOnlyOneErrorPreference(Preference errorPreferenceToShow) {
   final Preference[] errorPreferences =
       new Preference[] {
         this.needsPasswordPreference,
         this.needsUpgradePreference,
         this.needsVerificationPreference,
         this.needsMasterSyncAutomaticallyEnabledPreference,
         this.needsFinishMigratingPreference,
       };
   for (Preference errorPreference : errorPreferences) {
     final boolean currentlyShown = null != findPreference(errorPreference.getKey());
     final boolean shouldBeShown = errorPreference == errorPreferenceToShow;
     if (currentlyShown == shouldBeShown) {
       continue;
     }
     if (shouldBeShown) {
       syncCategory.addPreference(errorPreference);
     } else {
       syncCategory.removePreference(errorPreference);
     }
   }
 }
Beispiel #12
0
 public static EditTextPreference Edit(
     Context paramContext,
     PreferenceCategory paramPreferenceCategory,
     String paramString1,
     String paramString2,
     String paramString3,
     String paramString4,
     Object paramObject,
     boolean paramBoolean,
     Integer paramInteger) {
   EditTextPreference localEditTextPreference = new EditTextPreference(paramContext);
   localEditTextPreference.setTitle(paramString1);
   localEditTextPreference.setSummary(paramString2);
   localEditTextPreference.setEnabled(paramBoolean);
   localEditTextPreference.setKey(paramString4);
   localEditTextPreference.setDefaultValue(paramObject);
   localEditTextPreference.setDialogTitle(paramString3);
   if (paramInteger != null)
     localEditTextPreference.getEditText().setInputType(paramInteger.intValue());
   paramPreferenceCategory.addPreference(localEditTextPreference);
   return localEditTextPreference;
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View v = inflater.inflate(R.layout.layout_list, container, false);

    File f = new File("/sys/block/mmcblk0/queue/iosched");
    String curSched = Helpers.getCurrentScheduler();
    File[] files = f.listFiles();
    if (files.length != 0) {
      MainActivity.menu.setEnabled(false);
      addPreferences();
      mCategory.setTitle(curSched + " Tweakable values");
    } else {
      Preference pref = new Preference(mContext);
      pref.setTitle("No tweakable values");
      pref.setSummary(curSched + " Doesn\'t have tweakable values");
      mCategory.addPreference(pref);
    }

    return v;
  }
Beispiel #14
0
 public static ListPreference List(
     Context paramContext,
     PreferenceCategory paramPreferenceCategory,
     String paramString1,
     String paramString2,
     String paramString3,
     String paramString4,
     Object paramObject,
     CharSequence[] paramArrayOfCharSequence1,
     CharSequence[] paramArrayOfCharSequence2,
     boolean paramBoolean) {
   ListPreference localListPreference = new ListPreference(paramContext);
   localListPreference.setTitle(paramString1);
   localListPreference.setSummary(paramString2);
   localListPreference.setEnabled(paramBoolean);
   localListPreference.setKey(paramString4);
   localListPreference.setDefaultValue(paramObject);
   localListPreference.setDialogTitle(paramString3);
   localListPreference.setEntries(paramArrayOfCharSequence1);
   localListPreference.setEntryValues(paramArrayOfCharSequence2);
   paramPreferenceCategory.addPreference(localListPreference);
   return localListPreference;
 }
Beispiel #15
0
  @SuppressWarnings("nls")
  private void addDebugPreferences() {
    if (!Constants.DEBUG) return;

    PreferenceCategory group = new PreferenceCategory(this);
    group.setTitle("DEBUG");
    getPreferenceScreen().addPreference(group);

    Preference preference = new Preference(this);
    preference.setTitle("Flush detail cache");
    preference.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          public boolean onPreferenceClick(Preference p) {
            database.openForWriting();
            Toast.makeText(
                    EditPreferences.this,
                    "" + taskService.clearDetails(Criterion.all),
                    Toast.LENGTH_LONG)
                .show();
            return false;
          }
        });
    group.addPreference(preference);

    preference = new Preference(this);
    preference.setTitle("Make Lots of Tasks");
    preference.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          public boolean onPreferenceClick(Preference p) {
            database.openForWriting();
            Task task = new Task();
            for (int i = 0; i < 100; i++) {
              task.clear();
              task.setValue(Task.TITLE, Integer.toString(i));
              taskService.save(task);
            }
            DialogUtilities.okDialog(EditPreferences.this, "done", null);
            return false;
          }
        });
    group.addPreference(preference);

    preference = new Preference(this);
    preference.setTitle("Delete all tasks");
    preference.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          public boolean onPreferenceClick(Preference p) {
            database.openForWriting();
            taskService.deleteWhere(Criterion.all);
            DialogUtilities.okDialog(EditPreferences.this, "done", null);
            return false;
          }
        });
    group.addPreference(preference);

    preference = new Preference(this);
    preference.setTitle("Make lots of contacts");
    preference.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          public boolean onPreferenceClick(Preference p) {
            ContactListAdapter.makeLotsOfContacts();
            DialogUtilities.okDialog(EditPreferences.this, "done", null);
            return false;
          }
        });
    group.addPreference(preference);
  }
Beispiel #16
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    CustomTitleBar titleBar =
        new CustomTitleBar(this, R.string.settings_activity, R.drawable.tab_settings_screen_icon);
    setTheme(R.style.CustomTitleTheme_Preference);
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings_pref);
    titleBar.afterSetContentView();

    String[] entries;
    String[] entrieValues;
    PreferenceScreen screen = getPreferenceScreen();
    osmandSettings = getMyApplication().getSettings();

    PreferenceCategory cat = (PreferenceCategory) screen.findPreference("global_app_settings");
    if (!Version.isBlackberry(this)) {
      CheckBoxPreference nativeCheckbox =
          createCheckBoxPreference(
              osmandSettings.SAFE_MODE, R.string.safe_mode, R.string.safe_mode_description);
      // disable the checkbox if the library cannot be used
      if ((NativeOsmandLibrary.isLoaded() && !NativeOsmandLibrary.isSupported())
          || osmandSettings.NATIVE_RENDERING_FAILED.get()) {
        nativeCheckbox.setEnabled(false);
        nativeCheckbox.setChecked(true);
      }
      cat.addPreference(nativeCheckbox);

      applicationDir = new EditTextPreference(this);
      applicationDir.setTitle(R.string.application_dir);
      applicationDir.setKey("external_storage_dir");
      applicationDir.setDialogTitle(R.string.application_dir);
      applicationDir.setOnPreferenceChangeListener(this);
      cat.addPreference(applicationDir);
    }

    //		BidForFixHelper bidForFixHelper = getMyApplication().getBidForFix();
    //		bidForFixHelper.generatePreferenceList(screen, getString(R.string.support_new_features),
    // this);
    OsmandPlugin.onSettingsActivityCreate(this, screen);

    registerBooleanPreference(osmandSettings.USE_ENGLISH_NAMES, screen);
    registerBooleanPreference(osmandSettings.AUTO_ZOOM_MAP, screen);
    registerBooleanPreference(osmandSettings.FAST_ROUTE_MODE, screen);
    registerBooleanPreference(osmandSettings.SNAP_TO_ROAD, screen);
    registerBooleanPreference(osmandSettings.USE_COMPASS_IN_NAVIGATION, screen);
    registerBooleanPreference(osmandSettings.LEFT_SIDE_NAVIGATION, screen);

    // List preferences
    //		registerListPreference(osmandSettings.ROTATE_MAP, screen,
    //				new String[]{getString(R.string.rotate_map_none_opt),
    // getString(R.string.rotate_map_bearing_opt), getString(R.string.rotate_map_compass_opt)},
    //				new Integer[]{OsmandSettings.ROTATE_MAP_NONE, OsmandSettings.ROTATE_MAP_BEARING,
    // OsmandSettings.ROTATE_MAP_COMPASS});

    registerListPreference(
        osmandSettings.MAP_SCREEN_ORIENTATION,
        screen,
        new String[] {
          getString(R.string.map_orientation_portrait),
          getString(R.string.map_orientation_landscape),
          getString(R.string.map_orientation_default)
        },
        new Integer[] {
          ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
          ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
          ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        });

    MetricsConstants[] mvls =
        new MetricsConstants[] {
          MetricsConstants.KILOMETERS_AND_METERS,
          MetricsConstants.MILES_AND_FOOTS,
          MetricsConstants.MILES_AND_YARDS
        }; // MetricsConstants.values();
    entries = new String[mvls.length];
    for (int i = 0; i < entries.length; i++) {
      entries[i] = mvls[i].toHumanString(this);
    }
    registerListPreference(osmandSettings.METRIC_SYSTEM, screen, entries, mvls);

    // getResources().getAssets().getLocales();
    entrieValues =
        new String[] {
          "", "en", "af", "hy", "eu", "bs", "bg", "ca", "cs", "nl", "fi", "fr", "ka", "de", "el",
          "he", "hi", "hu", "id", "it", "ja", "ko", "lv", "lt", "mr", "no", "pl", "pt", "ro", "ru",
          "sk", "sl", "es", "sv", "uk", "vi"
        };
    entries =
        new String[] {
          getString(R.string.system_locale),
          "English",
          "Afrikaans",
          "Armenian",
          "Basque",
          "Bosnian",
          "Bulgarian",
          "Catalan",
          "Czech",
          "Dutch",
          "Finnish",
          "French",
          "Georgian",
          "German",
          "Greek",
          "Hebrew",
          "Hindi",
          "Hungarian",
          "Indonesian",
          "Italian",
          "Japanese",
          "Korean",
          "Latvian",
          "Lithuanian",
          "Marathi",
          "Norwegian",
          "Polish",
          "Portuguese",
          "Romanian",
          "Russian",
          "Slovak",
          "Slovenian",
          "Spanish",
          "Swedish",
          "Ukrainian",
          "Vietnamese"
        };
    registerListPreference(osmandSettings.PREFERRED_LOCALE, screen, entries, entrieValues);

    Integer[] intValues = new Integer[] {0, 5, 10, 15, 20, 25, 30, 45, 60, 90};
    entries = new String[intValues.length];
    entries[0] = getString(R.string.auto_follow_route_never);
    for (int i = 1; i < intValues.length; i++) {
      entries[i] = (int) intValues[i] + " " + getString(R.string.int_seconds);
    }
    registerListPreference(osmandSettings.AUTO_FOLLOW_ROUTE, screen, entries, intValues);

    entries = new String[RouteService.values().length];
    for (int i = 0; i < entries.length; i++) {
      entries[i] = RouteService.values()[i].getName();
    }
    registerListPreference(osmandSettings.ROUTER_SERVICE, screen, entries, RouteService.values());

    //		entries = new String[ApplicationMode.values().length];
    //		for(int i=0; i<entries.length; i++){
    //			entries[i] = ApplicationMode.values()[i].toHumanString(this);
    //		}
    //		registerListPreference(osmandSettings.APPLICATION_MODE, screen, entries,
    // ApplicationMode.values());
    //
    //		applicationModePreference = (ListPreference)
    // screen.findPreference(osmandSettings.APPLICATION_MODE.getId());
    //		applicationModePreference.setOnPreferenceChangeListener(this);

    routerServicePreference =
        (ListPreference) screen.findPreference(osmandSettings.ROUTER_SERVICE.getId());
    routerServicePreference.setOnPreferenceChangeListener(this);

    Preference localIndexes = (Preference) screen.findPreference(OsmandSettings.LOCAL_INDEXES);
    localIndexes.setOnPreferenceClickListener(this);
    bidforfix = (Preference) screen.findPreference("bidforfix");
    bidforfix.setOnPreferenceClickListener(this);
    plugins = (Preference) screen.findPreference("plugins");
    plugins.setOnPreferenceClickListener(this);
    avoidRouting = (Preference) screen.findPreference("avoid_in_routing");
    avoidRouting.setOnPreferenceClickListener(this);
    showAlarms = (Preference) screen.findPreference("show_routing_alarms");
    showAlarms.setOnPreferenceClickListener(this);

    Intent intent = getIntent();
    if (intent != null && intent.getIntExtra(INTENT_KEY_SETTINGS_SCREEN, 0) != 0) {
      int s = intent.getIntExtra(INTENT_KEY_SETTINGS_SCREEN, 0);
      String pref = null;
      if (s == SCREEN_GENERAL_SETTINGS) {
        pref = SCREEN_ID_GENERAL_SETTINGS;
      } else if (s == SCREEN_NAVIGATION_SETTINGS) {
        pref = SCREEN_ID_NAVIGATION_SETTINGS;
      }
      if (pref != null) {
        Preference toOpen = screen.findPreference(pref);
        if (toOpen instanceof PreferenceScreen) {
          setPreferenceScreen((PreferenceScreen) toOpen);
        }
      }
    }
  }
  private void updateServicesPreferences() {
    // Since services category is auto generated we have to do a pass
    // to generate it since services can come and go and then based on
    // the global accessibility state to decided whether it is enabled.

    // Generate.
    mServicesCategory.removeAll();

    AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(getActivity());

    List<AccessibilityServiceInfo> installedServices =
        accessibilityManager.getInstalledAccessibilityServiceList();
    Set<ComponentName> enabledServices =
        AccessibilityUtils.getEnabledServicesFromSettings(getActivity());
    List<String> permittedServices = mDpm.getPermittedAccessibilityServices(UserHandle.myUserId());
    final boolean accessibilityEnabled =
        Settings.Secure.getInt(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;

    for (int i = 0, count = installedServices.size(); i < count; ++i) {
      AccessibilityServiceInfo info = installedServices.get(i);

      PreferenceScreen preference = getPreferenceManager().createPreferenceScreen(getActivity());
      String title = info.getResolveInfo().loadLabel(getPackageManager()).toString();

      ServiceInfo serviceInfo = info.getResolveInfo().serviceInfo;
      ComponentName componentName = new ComponentName(serviceInfo.packageName, serviceInfo.name);

      preference.setKey(componentName.flattenToString());

      preference.setTitle(title);
      final boolean serviceEnabled =
          accessibilityEnabled && enabledServices.contains(componentName);
      String serviceEnabledString;
      if (serviceEnabled) {
        serviceEnabledString = getString(R.string.accessibility_feature_state_on);
      } else {
        serviceEnabledString = getString(R.string.accessibility_feature_state_off);
      }

      // Disable all accessibility services that are not permitted.
      String packageName = serviceInfo.packageName;
      boolean serviceAllowed = permittedServices == null || permittedServices.contains(packageName);
      preference.setEnabled(serviceAllowed || serviceEnabled);

      String summaryString;
      if (serviceAllowed) {
        summaryString = serviceEnabledString;
      } else {
        summaryString = getString(R.string.accessibility_feature_or_input_method_not_allowed);
      }
      preference.setSummary(summaryString);

      preference.setOrder(i);
      preference.setFragment(ToggleAccessibilityServicePreferenceFragment.class.getName());
      preference.setPersistent(true);

      Bundle extras = preference.getExtras();
      extras.putString(EXTRA_PREFERENCE_KEY, preference.getKey());
      extras.putBoolean(EXTRA_CHECKED, serviceEnabled);
      extras.putString(EXTRA_TITLE, title);

      String description = info.loadDescription(getPackageManager());
      if (TextUtils.isEmpty(description)) {
        description = getString(R.string.accessibility_service_default_description);
      }
      extras.putString(EXTRA_SUMMARY, description);

      String settingsClassName = info.getSettingsActivityName();
      if (!TextUtils.isEmpty(settingsClassName)) {
        extras.putString(
            EXTRA_SETTINGS_TITLE, getString(R.string.accessibility_menu_item_settings));
        extras.putString(
            EXTRA_SETTINGS_COMPONENT_NAME,
            new ComponentName(info.getResolveInfo().serviceInfo.packageName, settingsClassName)
                .flattenToString());
      }

      extras.putParcelable(EXTRA_COMPONENT_NAME, componentName);

      mServicesCategory.addPreference(preference);
    }

    if (mServicesCategory.getPreferenceCount() == 0) {
      if (mNoServicesMessagePreference == null) {
        mNoServicesMessagePreference = new Preference(getActivity());
        mNoServicesMessagePreference.setPersistent(false);
        mNoServicesMessagePreference.setLayoutResource(R.layout.text_description_preference);
        mNoServicesMessagePreference.setSelectable(false);
        mNoServicesMessagePreference.setSummary(
            getString(R.string.accessibility_no_services_installed));
      }
      mServicesCategory.addPreference(mNoServicesMessagePreference);
    }
  }
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    addPreferencesFromResource(R.xml.language_settings);

    try {
      mDefaultInputMethodSelectorVisibility =
          Integer.valueOf(getString(R.string.input_method_selector_visibility_default_value));
    } catch (NumberFormatException e) {
    }

    if (getActivity().getAssets().getLocales().length == 1) {
      // No "Select language" pref if there's only one system locale available.
      getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
    } else {
      mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
    }
    if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
      mShowInputMethodSelectorPref = (ListPreference) findPreference(KEY_INPUT_METHOD_SELECTOR);
      mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
      // TODO: Update current input method name on summary
      updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
    }

    new VoiceInputOutputSettings(this).onCreate();

    // Get references to dynamically constructed categories.
    mHardKeyboardCategory = (PreferenceCategory) findPreference("hard_keyboard");
    mKeyboardSettingsCategory = (PreferenceCategory) findPreference("keyboard_settings_category");
    mGameControllerCategory =
        (PreferenceCategory) findPreference("game_controller_settings_category");

    // Filter out irrelevant features if invoked from IME settings button.
    mIsOnlyImeSettings =
        Settings.ACTION_INPUT_METHOD_SETTINGS.equals(getActivity().getIntent().getAction());
    getActivity().getIntent().setAction(null);
    if (mIsOnlyImeSettings) {
      getPreferenceScreen().removeAll();
      getPreferenceScreen().addPreference(mHardKeyboardCategory);
      if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
        getPreferenceScreen().addPreference(mShowInputMethodSelectorPref);
      }
      getPreferenceScreen().addPreference(mKeyboardSettingsCategory);
    }

    // Build IME preference category.
    mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mImis = mImm.getInputMethodList();

    mKeyboardSettingsCategory.removeAll();
    if (!mIsOnlyImeSettings) {
      final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null);
      currentIme.setKey(KEY_CURRENT_INPUT_METHOD);
      currentIme.setTitle(getResources().getString(R.string.current_input_method));
      mKeyboardSettingsCategory.addPreference(currentIme);
    }

    mInputMethodPreferenceList.clear();
    final int N = (mImis == null ? 0 : mImis.size());
    for (int i = 0; i < N; ++i) {
      final InputMethodInfo imi = mImis.get(i);
      final InputMethodPreference pref = getInputMethodPreference(imi, N);
      mInputMethodPreferenceList.add(pref);
    }

    if (!mInputMethodPreferenceList.isEmpty()) {
      Collections.sort(mInputMethodPreferenceList);
      for (int i = 0; i < N; ++i) {
        mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i));
      }
    }

    // Build hard keyboard and game controller preference categories.
    mIm = (InputManager) getActivity().getSystemService(Context.INPUT_SERVICE);
    updateInputDevices();

    // Enable or disable mStatusBarImeSwitcher based on boolean value: config_show_cmIMESwitcher
    final Preference keyImeSwitcherPref = findPreference(KEY_IME_SWITCHER);
    if (keyImeSwitcherPref != null) {
      if (!getResources().getBoolean(com.android.internal.R.bool.config_show_cmIMESwitcher)) {
        getPreferenceScreen().removePreference(keyImeSwitcherPref);
      } else {
        mStatusBarImeSwitcher = (CheckBoxPreference) keyImeSwitcherPref;
      }
    }

    // Spell Checker
    final Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
    final SpellCheckersPreference scp =
        ((SpellCheckersPreference) findPreference("spellcheckers_settings"));
    if (scp != null) {
      scp.setFragmentIntent(this, intent);
    }

    mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL);
    if (mVolumeKeyCursorControl != null) {
      mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
      mVolumeKeyCursorControl.setValue(
          Integer.toString(
              Settings.System.getInt(
                  getActivity().getContentResolver(),
                  Settings.System.VOLUME_KEY_CURSOR_CONTROL,
                  0)));
      mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
    }

    mHandler = new Handler();
    mSettingsObserver = new SettingsObserver(mHandler, getActivity());
  }
 private void prepareRoutingPrefs(PreferenceScreen screen) {
   PreferenceCategory cat = (PreferenceCategory) screen.findPreference("routing_preferences");
   cat.removeAll();
   CheckBoxPreference fastRoute =
       createCheckBoxPreference(
           settings.FAST_ROUTE_MODE, R.string.fast_route_mode, R.string.fast_route_mode_descr);
   if (settings.ROUTER_SERVICE.get() != RouteService.OSMAND) {
     cat.addPreference(fastRoute);
   } else {
     ApplicationMode am = settings.getApplicationMode();
     GeneralRouter router = getRouter(getMyApplication().getDefaultRoutingConfig(), am);
     clearParameters();
     if (router != null) {
       Map<String, RoutingParameter> parameters = router.getParameters();
       if (parameters.containsKey("short_way")) {
         cat.addPreference(fastRoute);
       }
       List<RoutingParameter> others = new ArrayList<GeneralRouter.RoutingParameter>();
       for (Map.Entry<String, RoutingParameter> e : parameters.entrySet()) {
         String param = e.getKey();
         if (param.startsWith("avoid_")) {
           avoidParameters.add(e.getValue());
         } else if (param.startsWith("prefer_")) {
           preferParameters.add(e.getValue());
         } else if (!param.equals("short_way")) {
           others.add(e.getValue());
         }
       }
       if (avoidParameters.size() > 0) {
         avoidRouting = new Preference(this);
         avoidRouting.setTitle(R.string.avoid_in_routing_title);
         avoidRouting.setSummary(R.string.avoid_in_routing_descr);
         avoidRouting.setOnPreferenceClickListener(this);
         cat.addPreference(avoidRouting);
       }
       if (preferParameters.size() > 0) {
         preferRouting = new Preference(this);
         preferRouting.setTitle(R.string.prefer_in_routing_title);
         preferRouting.setSummary(R.string.prefer_in_routing_descr);
         preferRouting.setOnPreferenceClickListener(this);
         cat.addPreference(preferRouting);
       }
       for (RoutingParameter p : others) {
         Preference basePref;
         if (p.getType() == RoutingParameterType.BOOLEAN) {
           basePref =
               createCheckBoxPreference(settings.getCustomRoutingBooleanProperty(p.getId()));
         } else {
           Object[] vls = p.getPossibleValues();
           String[] svlss = new String[vls.length];
           int i = 0;
           for (Object o : vls) {
             svlss[i++] = o.toString();
           }
           basePref =
               createListPreference(
                   settings.getCustomRoutingProperty(
                       p.getId(), p.getType() == RoutingParameterType.NUMERIC ? "0.0" : "-"),
                   p.getPossibleValueDescriptions(),
                   svlss,
                   SettingsBaseActivity.getRoutingStringPropertyName(this, p.getId(), p.getName()),
                   SettingsBaseActivity.getRoutingStringPropertyDescription(
                       this, p.getId(), p.getDescription()));
         }
         basePref.setTitle(
             SettingsBaseActivity.getRoutingStringPropertyName(this, p.getId(), p.getName()));
         basePref.setSummary(
             SettingsBaseActivity.getRoutingStringPropertyDescription(
                 this, p.getId(), p.getDescription()));
         cat.addPreference(basePref);
       }
     }
     ApplicationMode mode = getMyApplication().getSettings().getApplicationMode();
     if (mode.isDerivedRoutingFrom(ApplicationMode.CAR)) {
       PreferenceCategory category =
           (PreferenceCategory) screen.findPreference("guidance_preferences");
       category.addPreference(speedLimitExceed);
     } else {
       PreferenceCategory category =
           (PreferenceCategory) screen.findPreference("guidance_preferences");
       category.removePreference(speedLimitExceed);
     }
   }
 }
  private static void setupPreferences(PreferenceActivity context) {
    // create Categories
    PreferenceScreen prefScreen = context.getPreferenceManager().createPreferenceScreen(context);
    prefScreen.removeAll();

    // selected location category
    PreferenceCategory selectedCat = new PreferenceCategory(context);
    selectedCat.setTitle(R.string.selected_location_str);
    // location list category
    PreferenceCategory locationListCat = new PreferenceCategory(context);
    locationListCat.setTitle(R.string.location_list_str);
    // general category
    PreferenceCategory generalCat = new PreferenceCategory(context);
    generalCat.setTitle(R.string.general_preferences_str);
    //		//gesture category
    //		PreferenceCategory gestureCat = new PreferenceCategory(context);
    //		gestureCat.setTitle(R.string.gesture_settings_str);

    // add categories to preference screen
    prefScreen.addPreference(selectedCat);
    prefScreen.addPreference(locationListCat);
    //		prefScreen.addPreference(gestureCat);
    prefScreen.addPreference(generalCat);

    // Create add and delete location preferences and add to location list
    locationListCat.addPreference(
        createAddLocationPreference(
            context,
            context.getString(R.string.add_location_str),
            context.getString(R.string.add_location_description_str)));
    locationListCat.addPreference(
        createDeleteLocationPreference(
            context,
            context.getString(R.string.delete_location_str),
            context.getString(R.string.delete_location_description_str)));

    // create apptheme action preference
    generalCat.addPreference(
        createIntListPreference(
            context,
            PREF_APP_THEME,
            R.string.pref_app_theme,
            R.string.pref_app_theme_description,
            R.array.app_theme_strings,
            R.array.app_theme_values,
            "0"));

    // create mythfrontend update status interval preference
    generalCat.addPreference(
        createIntListPreference(
            context,
            PREF_STATUS_UPDATE_INTERVAL,
            R.string.status_update_interval_str,
            R.string.status_update_interval_description_str,
            R.array.status_Update_Interval_strings,
            R.array.status_Update_Interval_values,
            "0"));

    // create haptic feedback shared preference
    generalCat.addPreference(
        createCheckBox(
            context,
            PREF_HAPTIC_FEEDBACK_ENABLED,
            R.string.haptic_feedback_enabled_str,
            R.string.haptic_feedback_enabled_description_str,
            false));

    // create longpress action preference
    generalCat.addPreference(
        createIntListPreference(
            context,
            PREF_LONGPRESS_ACTION,
            R.string.longpress_action_str,
            R.string.longpress_action_description_str,
            R.array.longpress_action_strings,
            R.array.longpress_action_values,
            "0"));

    // create key repeat interval preference
    generalCat.addPreference(
        createIntListPreference(
            context,
            PREF_KEY_REPEAT_INTERVAL,
            R.string.key_repeat_interval_str,
            R.string.key_repeat_interval_description_str,
            R.array.key_repeat_interval_strings,
            R.array.key_repeat_interval_values,
            "100"));

    // create connection timeout interval preference
    generalCat.addPreference(
        createIntListPreference(
            context,
            PREF_CONNECTION_TIMEOUT_INTERVAL,
            R.string.conection_timeout_interval_str,
            R.string.conection_timeout_interval_description_str,
            R.array.connection_timeout_interval_strings,
            R.array.connection_timeout_interval_values,
            "5000"));

    // create donate button visible checkbox
    generalCat.addPreference(
        createCheckBox(
            context,
            PREF_SHOW_DONATE_MENU_ITEM,
            R.string.show_donate_menu_item_str,
            R.string.show_donate_menu_item_str,
            true));

    //		//create gestures enabled
    //		gestureCat.addPreference(createCheckBox(context,
    //				PREF_GESTURES_ENABLED,
    //				R.string.gestures_enabled_str,
    //				R.string.gestures_enabled_str, false));
    //
    //		//gesture list preference
    //		Preference gestureList = createGestureListPreference(context);
    //		gestureCat.addPreference(gestureList);

    // open DB
    MythMoteDbManager _dbAdapter = new MythMoteDbManager(context);
    _dbAdapter.open();

    // get list of locations
    Cursor cursor = _dbAdapter.fetchAllFrontendLocations();

    // get column indexes
    sIdIndex = cursor.getColumnIndex(MythMoteDbHelper.KEY_ROWID);
    sAddressIndex = cursor.getColumnIndex(MythMoteDbHelper.KEY_ADDRESS);
    sNameIndex = cursor.getColumnIndex(MythMoteDbHelper.KEY_NAME);
    sPortIndex = cursor.getColumnIndex(MythMoteDbHelper.KEY_PORT);
    sMacIndex = cursor.getColumnIndex(MythMoteDbHelper.KEY_MAC);
    sWifiOnlyIndex = cursor.getColumnIndex(MythMoteDbHelper.KEY_WIFIONLY);

    // determine if we have locations saved
    int count = cursor.getCount();
    if (count > 0 && cursor.moveToFirst()) {
      // get selected frontend id
      int selected =
          context
              .getSharedPreferences(MYTHMOTE_SHARED_PREFERENCES_ID, MODE_PRIVATE)
              .getInt(MythMotePreferences.PREF_SELECTED_LOCATION, -1);

      // if selected failed
      if (selected == -1) {
        // set to first in list
        selected = cursor.getInt(sIdIndex);
        // save (defaulted) selected location
        SaveSelectedLocationId(context, selected);
      }

      // put each location in the preference list
      for (int i = 0; i < count; i++) {
        locationListCat.addPreference(
            MythMotePreferences.createLocationPreference(
                context,
                cursor.getString(sIdIndex),
                cursor.getString(sNameIndex),
                cursor.getString(sAddressIndex)));

        if (cursor.getInt(sIdIndex) == selected) {
          // create preference for selected location
          selectedCat.addPreference(
              MythMotePreferences.createSelectedLocationPreference(
                  context,
                  context.getString(R.string.selected_location_str),
                  cursor.getString(sNameIndex)));
        }

        cursor.moveToNext();
      }

      // the saved selected location was not found just pick the first one
      if (selectedCat.getPreferenceCount() <= 0) {
        cursor.moveToFirst();
        selectedCat.addPreference(
            MythMotePreferences.createSelectedLocationPreference(
                context,
                context.getString(R.string.selected_location_str),
                cursor.getString(sNameIndex)));

        // save location ID so that it is for real
        SaveSelectedLocationId(context, cursor.getInt(sIdIndex));
      }
    } else {
      selectedCat.addPreference(
          MythMotePreferences.createSelectedLocationPreference(
              context,
              context.getString(R.string.selected_location_str),
              context.getString(R.string.no_frontend_locations_defined_str)));
    }

    cursor.close();
    _dbAdapter.close();

    // set preference screen
    context.setPreferenceScreen(prefScreen);

    // Assign dependences
    //		gestureList.setDependency(PREF_GESTURES_ENABLED);
  }
  private void updateServicesPreferences() {
    // Since services category is auto generated we have to do a pass
    // to generate it since services can come and go and then based on
    // the global accessibility state to decided whether it is enabled.

    // Generate.
    mServicesCategory.removeAll();

    AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(getActivity());

    List<AccessibilityServiceInfo> installedServices =
        accessibilityManager.getInstalledAccessibilityServiceList();
    Set<ComponentName> enabledServices = getEnabledServicesFromSettings(getActivity());

    final boolean accessibilityEnabled =
        Settings.Secure.getInt(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;

    for (int i = 0, count = installedServices.size(); i < count; ++i) {
      AccessibilityServiceInfo info = installedServices.get(i);

      PreferenceScreen preference = getPreferenceManager().createPreferenceScreen(getActivity());
      String title = info.getResolveInfo().loadLabel(getPackageManager()).toString();

      ServiceInfo serviceInfo = info.getResolveInfo().serviceInfo;
      ComponentName componentName = new ComponentName(serviceInfo.packageName, serviceInfo.name);

      preference.setKey(componentName.flattenToString());

      preference.setTitle(title);
      final boolean serviceEnabled =
          accessibilityEnabled && enabledServices.contains(componentName);
      if (serviceEnabled) {
        preference.setSummary(getString(R.string.accessibility_service_state_on));
      } else {
        preference.setSummary(getString(R.string.accessibility_service_state_off));
      }

      preference.setOrder(i);
      preference.setFragment(ToggleAccessibilityServiceFragment.class.getName());
      preference.setPersistent(true);

      Bundle extras = preference.getExtras();
      extras.putString(EXTRA_PREFERENCE_KEY, preference.getKey());
      extras.putBoolean(EXTRA_CHECKED, serviceEnabled);
      extras.putString(EXTRA_TITLE, title);

      String description = info.getDescription();
      if (TextUtils.isEmpty(description)) {
        description = getString(R.string.accessibility_service_default_description);
      }
      extras.putString(EXTRA_SUMMARY, description);

      CharSequence applicationLabel = info.getResolveInfo().loadLabel(getPackageManager());

      extras.putString(
          EXTRA_ENABLE_WARNING_TITLE,
          getString(R.string.accessibility_service_security_warning_title, applicationLabel));
      extras.putString(
          EXTRA_ENABLE_WARNING_MESSAGE,
          getString(R.string.accessibility_service_security_warning_summary, applicationLabel));

      extras.putString(
          EXTRA_DISABLE_WARNING_TITLE,
          getString(R.string.accessibility_service_disable_warning_title, applicationLabel));
      extras.putString(
          EXTRA_DISABLE_WARNING_MESSAGE,
          getString(R.string.accessibility_service_disable_warning_summary, applicationLabel));

      String settingsClassName = info.getSettingsActivityName();
      if (!TextUtils.isEmpty(settingsClassName)) {
        extras.putString(
            EXTRA_SETTINGS_TITLE, getString(R.string.accessibility_menu_item_settings));
        extras.putString(
            EXTRA_SETTINGS_COMPONENT_NAME,
            new ComponentName(info.getResolveInfo().serviceInfo.packageName, settingsClassName)
                .flattenToString());
      }

      mServicesCategory.addPreference(preference);
    }

    if (mServicesCategory.getPreferenceCount() == 0) {
      if (mNoServicesMessagePreference == null) {
        mNoServicesMessagePreference =
            new Preference(getActivity()) {
              @Override
              protected void onBindView(View view) {
                super.onBindView(view);

                LinearLayout containerView =
                    (LinearLayout) view.findViewById(R.id.message_container);
                containerView.setGravity(Gravity.CENTER);

                TextView summaryView = (TextView) view.findViewById(R.id.summary);
                String title = getString(R.string.accessibility_no_services_installed);
                summaryView.setText(title);
              }
            };
        mNoServicesMessagePreference.setPersistent(false);
        mNoServicesMessagePreference.setLayoutResource(R.layout.text_description_preference);
        mNoServicesMessagePreference.setSelectable(false);
      }
      mServicesCategory.addPreference(mNoServicesMessagePreference);
    }
  }
  private void updateSystemPreferences() {
    float updateFontScale =
        Settings.System.getFloat(getContentResolver(), Settings.System.FONT_SCALE_EXTRALARGE, -1);
    // Large text.
    try {
      mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
    } catch (RemoteException re) {
      /* ignore */
    }
    if (updateFontScale == -1) {
      if (sIsScreenLarge) {
        mToggleLargeTextPreference.setChecked(mCurConfig.fontScale == LARGE_FONT_SCALE_TABLET);
      } else {
        mToggleLargeTextPreference.setChecked(mCurConfig.fontScale == LARGE_FONT_SCALE_PHONE);
      }
    } else {
      mToggleLargeTextPreference.setChecked(mCurConfig.fontScale == updateFontScale);
    }

    // Power button ends calls.
    if (KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_POWER)
        && Utils.isVoiceCapable(getActivity())) {
      final int incallPowerBehavior =
          Settings.Secure.getInt(
              getContentResolver(),
              Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
              Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT);
      final boolean powerButtonEndsCall =
          (incallPowerBehavior == Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP);
      mTogglePowerButtonEndsCallPreference.setChecked(powerButtonEndsCall);
    }

    updateRotationCheckbox();

    // Speak passwords.
    final boolean speakPasswordEnabled =
        Settings.Secure.getInt(
                getContentResolver(), Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0)
            != 0;
    mToggleSpeakPasswordPreference.setChecked(speakPasswordEnabled);

    // Touch exploration enabled.
    if (AccessibilityManager.getInstance(getActivity()).isEnabled()) {
      mSystemsCategory.addPreference(mToggleTouchExplorationPreference);
      final boolean touchExplorationEnabled =
          (Settings.Secure.getInt(
                  getContentResolver(), Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0)
              == 1);
      if (touchExplorationEnabled) {
        mToggleTouchExplorationPreference.setSummary(
            getString(R.string.accessibility_service_state_on));
        mToggleTouchExplorationPreference.getExtras().putBoolean(EXTRA_CHECKED, true);
      } else {
        mToggleTouchExplorationPreference.setSummary(
            getString(R.string.accessibility_service_state_off));
        mToggleTouchExplorationPreference.getExtras().putBoolean(EXTRA_CHECKED, false);
      }

    } else {
      mSystemsCategory.removePreference(mToggleTouchExplorationPreference);
    }

    // Long press timeout.
    final int longPressTimeout =
        Settings.Secure.getInt(
            getContentResolver(), Settings.Secure.LONG_PRESS_TIMEOUT, mLongPressTimeoutDefault);
    String value = String.valueOf(longPressTimeout);
    mSelectLongPressTimeoutPreference.setValue(value);
    mSelectLongPressTimeoutPreference.setSummary(mLongPressTimeoutValuetoTitleMap.get(value));

    // Script injection.
    final boolean scriptInjectionAllowed =
        (Settings.Secure.getInt(
                getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0)
            == 1);
    mToggleScriptInjectionPreference.setInjectionAllowed(scriptInjectionAllowed);

    // IPO Setting
    boolean ipoSettingEnabled =
        Settings.System.getInt(getContentResolver(), Settings.System.IPO_SETTING, 1) == 1;
    if (mIpoSetting != null) {
      mIpoSetting.setChecked(ipoSettingEnabled);
    }
  }
  @Override
  protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setResult(RESULT_CANCELED);

    Bundle extras = getIntent().getExtras();

    if (extras != null) {
      widgetId =
          extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
      finish();
    }
    addPreferencesFromResource(R.layout.widgetpreferences);
    setContentView(R.layout.widgetconfig);

    final ListPreference entryCountPreference =
        (ListPreference) findPreference("widget.entrycount");

    final PreferenceCategory feedsPreferenceCategory =
        (PreferenceCategory) findPreference("widget.visiblefeeds");

    Cursor cursor =
        this.getContentResolver()
            .query(
                FeedData.FeedColumns.CONTENT_URI,
                new String[] {FeedData.FeedColumns._ID, NAMECOLUMN},
                null,
                null,
                null);

    if (cursor.moveToFirst()) {
      int[] ids = new int[cursor.getCount() + 1];

      CheckBoxPreference checkboxPreference = new CheckBoxPreference(this);

      checkboxPreference.setTitle(R.string.all_feeds);
      feedsPreferenceCategory.addPreference(checkboxPreference);
      checkboxPreference.setKey(ZERO);
      checkboxPreference.setDisableDependentsState(true);
      ids[0] = 0;
      for (int n = 1; !cursor.isAfterLast(); cursor.moveToNext(), n++) {
        checkboxPreference = new CheckBoxPreference(this);
        checkboxPreference.setTitle(cursor.getString(1));
        ids[n] = cursor.getInt(0);
        checkboxPreference.setKey(Integer.toString(ids[n]));
        feedsPreferenceCategory.addPreference(checkboxPreference);
        checkboxPreference.setDependency(ZERO);
      }
      cursor.close();

      findViewById(R.id.save_button)
          .setOnClickListener(
              new OnClickListener() {
                public void onClick(View view) {
                  SharedPreferences.Editor preferences =
                      getSharedPreferences(SparseRSSAppWidgetProvider.class.getName(), 0).edit();

                  boolean hideRead =
                      false; // ((CheckBoxPreference)
                             // getPreferenceManager().findPreference("widget.hideread")).isChecked();

                  preferences.putBoolean(widgetId + ".hideread", hideRead);

                  StringBuilder builder = new StringBuilder();

                  for (int n = 0, i = feedsPreferenceCategory.getPreferenceCount(); n < i; n++) {
                    CheckBoxPreference preference =
                        (CheckBoxPreference) feedsPreferenceCategory.getPreference(n);

                    if (preference.isChecked()) {
                      if (n == 0) {
                        break;
                      } else {
                        if (builder.length() > 0) {
                          builder.append(',');
                        }
                        builder.append(preference.getKey());
                      }
                    }
                  }

                  String feedIds = builder.toString();

                  String entryCount = entryCountPreference.getValue();

                  preferences.putString(widgetId + ".feeds", feedIds);
                  preferences.putString(widgetId + ".entrycount", entryCount);

                  int color =
                      getPreferenceManager()
                          .getSharedPreferences()
                          .getInt(
                              "widget.background", SparseRSSAppWidgetProvider.STANDARD_BACKGROUND);

                  preferences.putInt(widgetId + ".background", color);
                  preferences.commit();

                  SparseRSSAppWidgetProvider.updateAppWidget(
                      WidgetConfigActivity.this, widgetId, hideRead, entryCount, feedIds, color);
                  setResult(
                      RESULT_OK,
                      new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId));
                  finish();
                }
              });
    } else {
      // no feeds found --> use all feeds, no dialog needed
      cursor.close();
      setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId));
    }
  }