3

I have checkbox in preferences. I want to keep screen on if checkbox is checked and not to keep screen on if checkbox is not checked.

I want something like this:

boolean keepScreen = sharedPrefs.getBoolean("chck_screen", false);

if (keepScreen.equals(false)) {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

}

Please, help.

Sabre
  • 4,131
  • 5
  • 36
  • 57

2 Answers2

13

If you are using a PreferenceActivity and have the checkbox declared in XML with the key "checkbox_preference" (rename it to whatever you have) you can do this:

CheckBoxPreference pref = (CheckBoxPreference) findPreference("checkbox_preference");

pref.isChecked(); returns if it is checked or not

Additionally, you can set a listener for whenever the value is changed

pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue)
            {
                boolean checked = Boolean.valueOf(newValue.toString());

                //set your shared preference value equal to checked

                return true;
            }
        });
dymmeh
  • 22,247
  • 5
  • 53
  • 60
  • Thanks. But how I should initialize something magic in other activity (for example, in main activity)? – Sabre Mar 20 '12 at 20:44
  • If I understand you correctly I should put it in PreferenceActivity. But may be I misunderstood how can I get the value of checkbox in not PrefActivity? – Sabre Mar 20 '12 at 20:48
  • Check my edited answer. Where i have the comment you can access your shared preferences and commit your value into them. Then in your main activity you can keep the code you originally posted where you retrieve the value from shared pereferences – dymmeh Mar 20 '12 at 20:48
  • Ok, I understand. But I new to coding, so can you give me full code, please. – Sabre Mar 20 '12 at 21:06
  • Take a look [at this answer](http://stackoverflow.com/questions/8407286/need-to-save-a-high-score-for-an-android-game/8407349#8407349) for a code example of how to set and retrieve shared preference values. When the checked value is changed you will have to set the shared preference value. When you return to your activity you will have to get the shared preference value in your onCreate – dymmeh Mar 20 '12 at 21:10
3

You can also use PreferenceManager.getSharedPreferences().getBoolean(String key, boolean defValue) for getting you preferences value

Alenka
  • 31
  • 3