Search in sources :

Example 21 with PreferenceCategory

use of android.preference.PreferenceCategory in project routerkeygenAndroid by routerkeygen.

the class Preferences method onCreate.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    findPreference("download").setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            if (isDictionaryServiceRunning()) {
                Toast.makeText(getBaseContext(), getString(R.string.pref_msg_download_running), Toast.LENGTH_SHORT).show();
                return true;
            }
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
                Toast.makeText(getBaseContext(), getString(R.string.pref_msg_no_network), Toast.LENGTH_SHORT).show();
                return true;
            }
            // wifi connection
            if ((((WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE))).getConnectionInfo().getSSID() != null) {
                try {
                    checkCurrentDictionary();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(DIALOG_ASK_DOWNLOAD);
            return true;
        }
    });
    boolean app_installed = AdsUtils.checkDonation(this);
    final PreferenceCategory mCategory = (PreferenceCategory) findPreference("2section");
    if (!app_installed) {
        mCategory.removePreference(findPreference("analytics_enabled"));
        // If you haven't the donate app installed remove the paypal donate
        // link.
        mCategory.removePreference(findPreference("donate_paypal"));
        findPreference("donate_playstore").setOnPreferenceClickListener(new OnPreferenceClickListener() {

            public boolean onPreferenceClick(Preference preference) {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + GOOGLE_PLAY_DOWNLOADER)));
                } catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + GOOGLE_PLAY_DOWNLOADER)));
                }
                Toast.makeText(getApplicationContext(), R.string.msg_donation, Toast.LENGTH_LONG).show();
                return true;
            }
        });
    } else {
        // If you have the donate app installed no need to link to it.
        mCategory.removePreference(findPreference("donate_playstore"));
        if (BuildConfig.APPLICATION_ID.equals("io.github.routerkeygen")) {
            //Play Store is quite restrictive nowadays
            mCategory.removePreference(findPreference("donate_paypal"));
        } else {
            findPreference("donate_paypal").setOnPreferenceClickListener(new OnPreferenceClickListener() {

                public boolean onPreferenceClick(Preference preference) {
                    final String donateLink = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V3FFBTRTTV5DN";
                    Uri uri = Uri.parse(donateLink);
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    return true;
                }
            });
        }
    }
    if (BuildConfig.APPLICATION_ID.equals("io.github.routerkeygen")) {
        mCategory.removePreference(findPreference("update"));
    } else {
        findPreference("update").setOnPreferenceClickListener(new OnPreferenceClickListener() {

            public boolean onPreferenceClick(Preference preference) {
                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

                    protected void onPreExecute() {
                        showDialog(DIALOG_WAIT);
                    }

                    protected Void doInBackground(Void... params) {
                        lastVersion = UpdateCheckerService.getLatestVersion();
                        return null;
                    }

                    protected void onPostExecute(Void result) {
                        removeDialog(DIALOG_WAIT);
                        if (isFinishing())
                            return;
                        if (lastVersion == null) {
                            showDialog(DIALOG_ERROR);
                            return;
                        }
                        if (!Preferences.VERSION.equals(lastVersion.version)) {
                            showDialog(DIALOG_UPDATE_NEEDED);
                        } else {
                            Toast.makeText(Preferences.this, R.string.msg_app_updated, Toast.LENGTH_SHORT).show();
                        }
                    }
                };
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                    task.execute();
                } else {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
                // Checking for updates every week
                startService(new Intent(getApplicationContext(), UpdateCheckerService.class));
                return true;
            }
        });
    }
    findPreference("changelog").setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            showDialog(DIALOG_CHANGELOG);
            return true;
        }
    });
    findPreference("about").setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            showDialog(DIALOG_ABOUT);
            return true;
        }
    });
    findPreference(dicLocalPref).setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(new Intent(getApplicationContext(), FileChooserActivity.class), 0);
            return true;
        }
    });
    final CheckBoxPreference autoScan = (CheckBoxPreference) findPreference("autoScan");
    autoScan.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            findPreference("autoScanInterval").setEnabled(autoScan.isChecked());
            return true;
        }
    });
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    findPreference("autoScanInterval").setEnabled(prefs.getBoolean(Preferences.autoScanPref, getResources().getBoolean(R.bool.autoScanDefault)));
}
Also used : WifiManager(android.net.wifi.WifiManager) NetworkInfo(android.net.NetworkInfo) CheckBoxPreference(android.preference.CheckBoxPreference) SharedPreferences(android.content.SharedPreferences) ConnectivityManager(android.net.ConnectivityManager) FileNotFoundException(java.io.FileNotFoundException) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) Uri(android.net.Uri) OnPreferenceClickListener(android.preference.Preference.OnPreferenceClickListener) CheckBoxPreference(android.preference.CheckBoxPreference) Preference(android.preference.Preference) PreferenceCategory(android.preference.PreferenceCategory) TargetApi(android.annotation.TargetApi)

Example 22 with PreferenceCategory

use of android.preference.PreferenceCategory in project qksms by moezbhatti.

the class SettingsFragment method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle args = getArguments();
    setHasOptionsMenu(true);
    mContext = (QKActivity) getActivity();
    mPrefs = mContext.getPrefs();
    mRes = mContext.getResources();
    mContext.setTitle(R.string.title_settings);
    mResource = args.getInt("category", R.xml.settings);
    addPreferencesFromResource(mResource);
    // Set `this` to be the preferences click/change listener for all the preferences.
    PreferenceScreen screen = getPreferenceScreen();
    for (int i = 0; i < screen.getPreferenceCount(); i++) {
        Preference pref = screen.getPreference(i);
        pref.setOnPreferenceClickListener(this);
        pref.setOnPreferenceChangeListener(this);
        // well.
        if (pref instanceof PreferenceCategory) {
            Stack<PreferenceCategory> stack = new Stack<>();
            stack.push((PreferenceCategory) pref);
            do {
                PreferenceCategory category = stack.pop();
                for (int j = 0; j < category.getPreferenceCount(); j++) {
                    Preference subPref = category.getPreference(j);
                    subPref.setOnPreferenceClickListener(this);
                    subPref.setOnPreferenceChangeListener(this);
                    if (subPref instanceof PreferenceCategory) {
                        stack.push((PreferenceCategory) subPref);
                    }
                }
            } while (!stack.isEmpty());
        }
    }
    Preference icon = findPreference(ICON);
    if (icon != null) {
        icon.setOnPreferenceClickListener(this);
    }
    mThemeLed = findPreference(NOTIFICATION_LED_COLOR);
    if (mThemeLed != null) {
        mLedColors = new int[] { mRes.getColor(R.color.blue_light), mRes.getColor(R.color.purple_light), mRes.getColor(R.color.green_light), mRes.getColor(R.color.yellow_light), mRes.getColor(R.color.red_light), mRes.getColor(R.color.white_pure) };
        mLedColorPickerDialog = new ColorPickerDialog();
        mLedColorPickerDialog.initialize(R.string.pref_theme_led, mLedColors, Integer.parseInt(mPrefs.getString(NOTIFICATION_LED_COLOR, "-48060")), 3, 2);
        mLedColorPickerDialog.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener() {

            @Override
            public void onColorSelected(int color) {
                mPrefs.edit().putString(mThemeLed.getKey(), "" + color).apply();
                onPreferenceChange(findPreference(mThemeLed.getKey()), color);
            }
        });
    }
    ListPreference font_family = (ListPreference) findPreference(FONT_FAMILY);
    if (font_family != null) {
        mFontFamilies = mRes.getStringArray(R.array.font_families);
        font_family.setSummary(mFontFamilies[Integer.parseInt(font_family.getValue())]);
    }
    ListPreference font_size = (ListPreference) findPreference(FONT_SIZE);
    if (font_size != null) {
        mFontSizes = mRes.getStringArray(R.array.font_sizes);
        font_size.setSummary(mFontSizes[Integer.parseInt(font_size.getValue())]);
    }
    ListPreference font_weight = (ListPreference) findPreference(FONT_WEIGHT);
    if (font_weight != null) {
        mFontWeights = mRes.getStringArray(R.array.font_weights);
        int i = Integer.parseInt(font_weight.getValue());
        font_weight.setSummary(mFontWeights[i == 2 ? 0 : 1]);
    }
    EditTextPreference deleteUnread = (EditTextPreference) findPreference(DELETE_UNREAD_MESSAGES);
    if (deleteUnread != null) {
        deleteUnread.setSummary(mContext.getString(R.string.pref_delete_old_messages_unread_summary, QKPreferences.getString(QKPreference.AUTO_DELETE_UNREAD)));
    }
    EditTextPreference deleteRead = (EditTextPreference) findPreference(DELETE_READ_MESSAGES);
    if (deleteRead != null) {
        deleteRead.setSummary(mContext.getString(R.string.pref_delete_old_messages_read_summary, QKPreferences.getString(QKPreference.AUTO_DELETE_READ)));
    }
    Preference day_start = findPreference(DAY_START);
    if (day_start != null) {
        day_start.setSummary(DateFormatter.getSummaryTimestamp(mContext, mPrefs.getString(DAY_START, "6:00")));
    }
    Preference night_start = findPreference(NIGHT_START);
    if (night_start != null) {
        night_start.setSummary(DateFormatter.getSummaryTimestamp(mContext, mPrefs.getString(NIGHT_START, "21:00")));
    }
    mMmscUrl = (EditTextPreference) findPreference(MMSC_URL);
    if (mMmscUrl != null) {
        mMmscUrl.setSummary(mMmscUrl.getText());
    }
    mMmsProxy = (EditTextPreference) findPreference(MMS_PROXY);
    if (mMmsProxy != null) {
        mMmsProxy.setSummary(mMmsProxy.getText());
    }
    mMmsPort = (EditTextPreference) findPreference(MMS_PORT);
    if (mMmsPort != null) {
        mMmsPort.setSummary(mMmsPort.getText());
    }
    mMaxMmsAttachmentSize = (ListPreference) findPreference(MAX_MMS_ATTACHMENT_SIZE);
    if (mMaxMmsAttachmentSize != null) {
        mMaxMmsAttachmentSizes = mRes.getStringArray(R.array.max_mms_attachment_sizes);
        String value = mMaxMmsAttachmentSize.getValue();
        String summary = mMaxMmsAttachmentSizes[mMaxMmsAttachmentSize.findIndexOfValue(value)];
        mMaxMmsAttachmentSize.setSummary(summary);
    }
    Preference version = findPreference(VERSION);
    if (version != null) {
        String v = "unknown";
        try {
            PackageInfo info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            v = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        version.setSummary(v);
    }
    // Status and nav bar tinting are only supported on kit kat or above.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        removePreference(CATEGORY_APPEARANCE_SYSTEM_BARS);
    }
}
Also used : PreferenceScreen(android.preference.PreferenceScreen) Bundle(android.os.Bundle) PackageInfo(android.content.pm.PackageInfo) ListPreference(android.preference.ListPreference) EditTextPreference(android.preference.EditTextPreference) Stack(java.util.Stack) ColorPickerDialog(com.moez.QKSMS.ui.view.colorpicker.ColorPickerDialog) PackageManager(android.content.pm.PackageManager) EditTextPreference(android.preference.EditTextPreference) ListPreference(android.preference.ListPreference) QKPreference(com.moez.QKSMS.enums.QKPreference) CheckBoxPreference(android.preference.CheckBoxPreference) Preference(android.preference.Preference) PreferenceCategory(android.preference.PreferenceCategory) ColorPickerSwatch(com.moez.QKSMS.ui.view.colorpicker.ColorPickerSwatch)

Example 23 with PreferenceCategory

use of android.preference.PreferenceCategory in project Conversations by siacs.

the class SettingsActivity method onStart.

@Override
public void onStart() {
    super.onStart();
    PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
    ListPreference resources = (ListPreference) mSettingsFragment.findPreference("resource");
    if (resources != null) {
        ArrayList<CharSequence> entries = new ArrayList<>(Arrays.asList(resources.getEntries()));
        if (!entries.contains(Build.MODEL)) {
            entries.add(0, Build.MODEL);
            resources.setEntries(entries.toArray(new CharSequence[entries.size()]));
            resources.setEntryValues(entries.toArray(new CharSequence[entries.size()]));
        }
    }
    if (Config.FORCE_ORBOT) {
        PreferenceCategory connectionOptions = (PreferenceCategory) mSettingsFragment.findPreference("connection_options");
        PreferenceScreen expert = (PreferenceScreen) mSettingsFragment.findPreference("expert");
        if (connectionOptions != null) {
            expert.removePreference(connectionOptions);
        }
    }
    boolean removeLocation = new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null;
    boolean removeVoice = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null;
    ListPreference quickAction = (ListPreference) mSettingsFragment.findPreference("quick_action");
    if (quickAction != null && (removeLocation || removeVoice)) {
        ArrayList<CharSequence> entries = new ArrayList<>(Arrays.asList(quickAction.getEntries()));
        ArrayList<CharSequence> entryValues = new ArrayList<>(Arrays.asList(quickAction.getEntryValues()));
        int index = entryValues.indexOf("location");
        if (index > 0 && removeLocation) {
            entries.remove(index);
            entryValues.remove(index);
        }
        index = entryValues.indexOf("voice");
        if (index > 0 && removeVoice) {
            entries.remove(index);
            entryValues.remove(index);
        }
        quickAction.setEntries(entries.toArray(new CharSequence[entries.size()]));
        quickAction.setEntryValues(entryValues.toArray(new CharSequence[entryValues.size()]));
    }
    final Preference removeCertsPreference = mSettingsFragment.findPreference("remove_trusted_certificates");
    removeCertsPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            final MemorizingTrustManager mtm = xmppConnectionService.getMemorizingTrustManager();
            final ArrayList<String> aliases = Collections.list(mtm.getCertificates());
            if (aliases.size() == 0) {
                displayToast(getString(R.string.toast_no_trusted_certs));
                return true;
            }
            final ArrayList selectedItems = new ArrayList<>();
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SettingsActivity.this);
            dialogBuilder.setTitle(getResources().getString(R.string.dialog_manage_certs_title));
            dialogBuilder.setMultiChoiceItems(aliases.toArray(new CharSequence[aliases.size()]), null, new DialogInterface.OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
                    if (isChecked) {
                        selectedItems.add(indexSelected);
                    } else if (selectedItems.contains(indexSelected)) {
                        selectedItems.remove(Integer.valueOf(indexSelected));
                    }
                    if (selectedItems.size() > 0)
                        ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
                    else {
                        ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
                    }
                }
            });
            dialogBuilder.setPositiveButton(getResources().getString(R.string.dialog_manage_certs_positivebutton), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int count = selectedItems.size();
                    if (count > 0) {
                        for (int i = 0; i < count; i++) {
                            try {
                                Integer item = Integer.valueOf(selectedItems.get(i).toString());
                                String alias = aliases.get(item);
                                mtm.deleteCertificate(alias);
                            } catch (KeyStoreException e) {
                                e.printStackTrace();
                                displayToast("Error: " + e.getLocalizedMessage());
                            }
                        }
                        if (xmppConnectionServiceBound) {
                            reconnectAccounts();
                        }
                        displayToast(getResources().getQuantityString(R.plurals.toast_delete_certificates, count, count));
                    }
                }
            });
            dialogBuilder.setNegativeButton(getResources().getString(R.string.dialog_manage_certs_negativebutton), null);
            AlertDialog removeCertsDialog = dialogBuilder.create();
            removeCertsDialog.show();
            removeCertsDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
            return true;
        }
    });
    final Preference exportLogsPreference = mSettingsFragment.findPreference("export_logs");
    exportLogsPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (hasStoragePermission(REQUEST_WRITE_LOGS)) {
                startExport();
            }
            return true;
        }
    });
    if (Config.ONLY_INTERNAL_STORAGE) {
        final Preference cleanCachePreference = mSettingsFragment.findPreference("clean_cache");
        cleanCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                cleanCache();
                return true;
            }
        });
        final Preference cleanPrivateStoragePreference = mSettingsFragment.findPreference("clean_private_storage");
        cleanPrivateStoragePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                cleanPrivateStorage();
                return true;
            }
        });
    }
    final Preference deleteOmemoPreference = mSettingsFragment.findPreference("delete_omemo_identities");
    deleteOmemoPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            deleteOmemoIdentities();
            return true;
        }
    });
}
Also used : AlertDialog(android.app.AlertDialog) PreferenceScreen(android.preference.PreferenceScreen) DialogInterface(android.content.DialogInterface) ArrayList(java.util.ArrayList) Intent(android.content.Intent) ListPreference(android.preference.ListPreference) KeyStoreException(java.security.KeyStoreException) MemorizingTrustManager(de.duenndns.ssl.MemorizingTrustManager) PreferenceCategory(android.preference.PreferenceCategory) ListPreference(android.preference.ListPreference) Preference(android.preference.Preference)

Example 24 with PreferenceCategory

use of android.preference.PreferenceCategory in project android_packages_apps_DSPManager by CyanogenMod.

the class WM8994 method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.wm8994_preferences);
    PreferenceScreen prefSet = getPreferenceScreen();
    for (int i = 0; i < OPTION_CONTROLS.length; i++) {
        String fileName = OPTION_CONTROLS[i][0];
        mPreferences[i] = (CheckBoxPreference) prefSet.findPreference(OPTION_CONTROLS[i][1]);
        if (Utils.fileExists(fileName)) {
            mPreferences[i].setChecked(PREF_ENABLED.equals(Utils.readOneLine(fileName)));
            mPreferences[i].setOnPreferenceChangeListener(this);
        } else {
            mPreferences[i].setSummary(R.string.pref_unavailable);
            mPreferences[i].setEnabled(false);
        }
    }
    if (Utils.fileExists(HeadsetAmplifierPreference.FILE_PATH)) {
        prefSet.findPreference("headphone_amp").setOnPreferenceChangeListener(this);
    } else {
        Preference category = prefSet.findPreference("wm8994_headphone_amp_category");
        prefSet.removePreference(category);
    }
    if (Utils.fileExists(MIC_REC_PRESET[0][0])) {
        prefSet.findPreference(MIC_REC_PRESET[0][1]).setOnPreferenceChangeListener(this);
    } else {
        Preference category = prefSet.findPreference("wm8994_microphone_recording_category");
        prefSet.removePreference(category);
    }
    Preference bassBoostPreset = prefSet.findPreference(BASS_BOOST_PRESET_PREF);
    Preference bassBoostGainRange = prefSet.findPreference(BASS_BOOST_GAIN_RANGE_PREF);
    if (Utils.fileExists(BASS_BOOST_ENABLE_FILE)) {
        bassBoostPreset.setOnPreferenceChangeListener(this);
        bassBoostGainRange.setOnPreferenceChangeListener(this);
    } else {
        PreferenceCategory bassBoostCategory = (PreferenceCategory) prefSet.findPreference("wm8994_signal_processing_category");
        bassBoostCategory.removePreference(bassBoostPreset);
        bassBoostCategory.removePreference(bassBoostGainRange);
    }
}
Also used : PreferenceScreen(android.preference.PreferenceScreen) CheckBoxPreference(android.preference.CheckBoxPreference) BassBoostPreference(com.bel.android.dspmanager.preference.BassBoostPreference) Preference(android.preference.Preference) HeadsetAmplifierPreference(com.bel.android.dspmanager.preference.HeadsetAmplifierPreference) PreferenceCategory(android.preference.PreferenceCategory)

Example 25 with PreferenceCategory

use of android.preference.PreferenceCategory in project Gadgetbridge by Freeyourgadget.

the class SettingsActivity method onPostCreate.

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    Preference pref = findPreference("notifications_generic");
    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            Intent enableIntent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(enableIntent);
            return true;
        }
    });
    pref = findPreference("pref_key_miband");
    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            Intent enableIntent = new Intent(SettingsActivity.this, MiBandPreferencesActivity.class);
            startActivity(enableIntent);
            return true;
        }
    });
    pref = findPreference("pref_key_blacklist");
    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            Intent enableIntent = new Intent(SettingsActivity.this, AppBlacklistActivity.class);
            startActivity(enableIntent);
            return true;
        }
    });
    pref = findPreference("pebble_emu_addr");
    pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newVal) {
            Intent refreshIntent = new Intent(DeviceManager.ACTION_REFRESH_DEVICELIST);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(refreshIntent);
            preference.setSummary(newVal.toString());
            return true;
        }
    });
    pref = findPreference("pebble_emu_port");
    pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newVal) {
            Intent refreshIntent = new Intent(DeviceManager.ACTION_REFRESH_DEVICELIST);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(refreshIntent);
            preference.setSummary(newVal.toString());
            return true;
        }
    });
    pref = findPreference("log_to_file");
    pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newVal) {
            boolean doEnable = Boolean.TRUE.equals(newVal);
            try {
                if (doEnable) {
                    // ensures that it is created
                    FileUtils.getExternalFilesDir();
                }
                GBApplication.setupLogging(doEnable);
            } catch (IOException ex) {
                GB.toast(getApplicationContext(), getString(R.string.error_creating_directory_for_logfiles, ex.getLocalizedMessage()), Toast.LENGTH_LONG, GB.ERROR, ex);
            }
            return true;
        }
    });
    if (!GBApplication.isRunningMarshmallowOrLater()) {
        pref = findPreference("notification_filter");
        PreferenceCategory category = (PreferenceCategory) findPreference("pref_key_notifications");
        category.removePreference(pref);
    }
    pref = findPreference("location_aquire");
    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(SettingsActivity.this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, 0);
            }
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String provider = locationManager.getBestProvider(criteria, false);
            if (provider != null) {
                Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    setLocationPreferences(location);
                } else {
                    locationManager.requestSingleUpdate(provider, new LocationListener() {

                        @Override
                        public void onLocationChanged(Location location) {
                            setLocationPreferences(location);
                        }

                        @Override
                        public void onStatusChanged(String provider, int status, Bundle extras) {
                            LOG.info("provider status changed to " + status + " (" + provider + ")");
                        }

                        @Override
                        public void onProviderEnabled(String provider) {
                            LOG.info("provider enabled (" + provider + ")");
                        }

                        @Override
                        public void onProviderDisabled(String provider) {
                            LOG.info("provider disabled (" + provider + ")");
                            GB.toast(SettingsActivity.this, getString(R.string.toast_enable_networklocationprovider), 3000, 0);
                        }
                    }, null);
                }
            } else {
                LOG.warn("No location provider found, did you deny location permission?");
            }
            return true;
        }
    });
    pref = findPreference("canned_messages_dismisscall_send");
    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            Prefs prefs = GBApplication.getPrefs();
            ArrayList<String> messages = new ArrayList<>();
            for (int i = 1; i <= 16; i++) {
                String message = prefs.getString("canned_message_dismisscall_" + i, null);
                if (message != null && !message.equals("")) {
                    messages.add(message);
                }
            }
            CannedMessagesSpec cannedMessagesSpec = new CannedMessagesSpec();
            cannedMessagesSpec.type = CannedMessagesSpec.TYPE_MISSEDCALLS;
            cannedMessagesSpec.cannedMessages = messages.toArray(new String[messages.size()]);
            GBApplication.deviceService().onSetCannedMessages(cannedMessagesSpec);
            return true;
        }
    });
    // Get all receivers of Media Buttons
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    PackageManager pm = getPackageManager();
    List<ResolveInfo> mediaReceivers = pm.queryBroadcastReceivers(mediaButtonIntent, PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RESOLVED_FILTER);
    CharSequence[] newEntries = new CharSequence[mediaReceivers.size() + 1];
    CharSequence[] newValues = new CharSequence[mediaReceivers.size() + 1];
    newEntries[0] = getString(R.string.pref_default);
    newValues[0] = "default";
    int i = 1;
    for (ResolveInfo resolveInfo : mediaReceivers) {
        newEntries[i] = resolveInfo.activityInfo.loadLabel(pm);
        newValues[i] = resolveInfo.activityInfo.packageName;
        i++;
    }
    final ListPreference audioPlayer = (ListPreference) findPreference("audio_player");
    audioPlayer.setEntries(newEntries);
    audioPlayer.setEntryValues(newValues);
    audioPlayer.setDefaultValue(newValues[0]);
}
Also used : MiBandPreferencesActivity(nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandPreferencesActivity) ArrayList(java.util.ArrayList) Criteria(android.location.Criteria) Prefs(nodomain.freeyourgadget.gadgetbridge.util.Prefs) ResolveInfo(android.content.pm.ResolveInfo) PackageManager(android.content.pm.PackageManager) LocationListener(android.location.LocationListener) LocationManager(android.location.LocationManager) Bundle(android.os.Bundle) Intent(android.content.Intent) IOException(java.io.IOException) ListPreference(android.preference.ListPreference) EditTextPreference(android.preference.EditTextPreference) ListPreference(android.preference.ListPreference) Preference(android.preference.Preference) PreferenceCategory(android.preference.PreferenceCategory) CannedMessagesSpec(nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec) Location(android.location.Location)

Aggregations

PreferenceCategory (android.preference.PreferenceCategory)34 Preference (android.preference.Preference)22 PreferenceScreen (android.preference.PreferenceScreen)17 CheckBoxPreference (android.preference.CheckBoxPreference)12 ListPreference (android.preference.ListPreference)11 Intent (android.content.Intent)7 EditTextPreference (android.preference.EditTextPreference)6 Bundle (android.os.Bundle)4 OnPreferenceClickListener (android.preference.Preference.OnPreferenceClickListener)4 ArrayList (java.util.ArrayList)4 SharedPreferences (android.content.SharedPreferences)3 Uri (android.net.Uri)3 Activity (android.app.Activity)2 AlertDialog (android.app.AlertDialog)2 Context (android.content.Context)2 DialogInterface (android.content.DialogInterface)2 PackageInfo (android.content.pm.PackageInfo)2 PackageManager (android.content.pm.PackageManager)2 SpannableString (android.text.SpannableString)2 View (android.view.View)2