开发者

Using checkbox to enable receivers

开发者 https://www.devze.com 2023-02-15 05:32 出处:网络
I would like to add a checkbox to my preference activity that would either enable or disable receivers.This is for a service which will run in the background, at boot completed, and will depend on two

I would like to add a checkbox to my preference activity that would either enable or disable receivers. This is for a service which will run in the background, at boot completed, and will depend on two things 1)is the preference true and 2) is wifi enabled.

So it would work something like this;

  1. user turns on phone
  2. boot completed checks if receivers are enabled (set by checkbox开发者_如何学Pythonpreference)
    • if checkboxpreference is true - looks for wifi
    • if wifi is true - registers receivers

Also required would be if wifi or checkboxpreference goes "false", unregister receivers.


I kind of had the same question a few days ago, and I ended up using a CheckBoxPreference in a if statement.

I did it with this code:

prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);

Then when I had to use the CheckBoxPreference I did it like this:

if(prefs.getBoolean("degrees", true)) {

} else {

}


Tim's answer is correct, but not well-explained. You would need to implement the OnSharedPreferenceChangeListener in your class:

class Prefs extends PreferenceActivity implements OnSharedPreferenceChangeListener {

Doing so will 'force' you to implement public void onSharedPreferenceChanged(). Here is where you can react to any changes made by the user:

public void onSharedPreferenceChanged( SharedPreferences pref, String key) {

    if ( key == "receiversToggle" ){

        if ( pref.getBoolean( "receiversToggle", false ) ) enableReceivers();
        else disableReceivers();
    }
}

Once you have these methods set up, you can register the listener as Tim explained in your onCreate() method:

getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
0

精彩评论

暂无评论...
验证码 换一张
取 消