can anyone tell me how can I start/stop a location service (or any other service) when a SwitchPreference in a PreferenceScreen is toggled on/of? I'm using a settingsFragemnt (extending PreferenceFragemntCompat), which is hosted in my settings activity.
Asked
Active
Viewed 37 times
-1
-
Could you please add your fragment code? – Volodymyr Bereziuk Feb 12 '20 at 12:04
2 Answers
0
You should add OnPreferenceChangeListener which will allow you to listen switch changes:
final SwitchPreference onOffRandomColor = (SwitchPreference) findPreference(this.getResources()
.getString(R.string.sp_key_on_off_random_color));
onOffRandomColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
if(onOffRandomColor.isChecked()){
}else {
}
return false;
}
});
Next step is to run service:
startService(new Intent(this, LocationService.class));

Volodymyr Bereziuk
- 182
- 1
- 8
-
yeah I know, my point is how can I start the service inside the listener? because what i did seems not to work – Mohammad Feb 12 '20 at 12:16
-
Is Location service your custom service ? You can start custom service via startService(new Intent(this, LocationService.class)); In your case @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Settings.setBoolean(Settings.DO_NOT_LOCATE, true); startService(new Intent(this, LocationService.class)); return false; } – Volodymyr Bereziuk Feb 12 '20 at 12:19
0
my fragment looks like this:
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(@Nullable Bundle savedInstanceState, String rootKey){
setPreferencesFromResource(R.xml.prefs, rootKey);
// setting summaries for both list preferences ---------------------------------------------
ListPreference photo_quality = findPreference("photo_quality");
if (photo_quality != null){
photo_quality.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
}
ListPreference uploads = findPreference("upload_options");
if (uploads != null) {
uploads.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
}
// setting the visibility for location service ---------------------------------------------
if (!Auth.getCanDeactiveGps()){
Objects.requireNonNull(getPreferenceScreen()
.findPreference("location_category")).setVisible(false);
}
// handling locationSwitchPreference change ------------------------------------------------
SwitchPreference locationSwitch = findPreference("location");
if (locationSwitch != null){
locationSwitch.setChecked(Settings.getBoolean(Settings.DO_NOT_LOCATE,
false));
locationSwitch.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Settings.setBoolean(Settings.DO_NOT_LOCATE, true);
return false;
}
});
}
}

Mohammad
- 11
- 2