Start/Stop service by checking/unchecking CheckBoxPreference

╄→гoц情女王★ 提交于 2019-12-05 21:25:37
moDev
CheckBoxPreference checkboxPref = (CheckBoxPreference)getPreferenceManager().findPreference("service_toggle");

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            

    public boolean onPreferenceChange(Preference preference, Object newValue) {

        boolean myValue = (Boolean) newValue;

        if(myValue)
            startService(new Intent(Settings.this, TouchDetectService.class));
        else
            stopService(new Intent(Settings.this, TouchDetectService.class));

        return true;
    }
}); 
public class Settings extends SherlockPreferenceActivity implements OnPreferenceClickListener, OnPreferenceChangeListener {

      @SuppressWarnings("deprecation")
      @Override
      public void onCreate(Bundle savedInstanceState) {
        .........

        CheckBoxPreference chkServiceToogle = (CheckBoxPreference)findPreference("service_toggle");
        chkServiceToogle.setOnPreferenceChangeListener(this);
    }

    @Override
    public boolean onPreferenceChange(Preference preference, String key)
    {
        if (key.equals("service_toggle")) {
            if(sharedPreferences.getBoolean(key, false)) {
                Intent intent = new Intent(getApplicationContext(), TouchDetectService.class);
                startService(intent);
            } else {
                Intent intent = new Intent(getApplicationContext(), TouchDetectService.class);
                stopService(intent);
            }
        }
    }
........
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!