androidservicepreferencescreen

Starting a service via a SwitchPreference


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.


Solution

  • 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));