Search code examples
sharedpreferencesandroid-preferencespreferencesapplication-settings

How to call CheckBoxPreference key to SettingsPreferences.java file


I have created WebView app with MainActivity.java file on some knowledge of android java. My question is I want to display Screen ON always on selection of ChackBoxPreference when my app opens by users. I have coded as given below:

setting_preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:title="@string/screen_on_off"
        android:summary="@string/keep_screen_on_selection"
        android:key="@string/display_screen"
        android:defaultValue="false" />
</PreferenceScreen>

When user selects this box then screen should be display always in my MainActivity.java code or else default settings.

SettingsActivity.java:

public class SettingsActivity extends PreferenceActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    addPreferencesFromResource(R.xml.setting_preferences);
    PreferenceManager preferenceManager = getPreferenceManager();
    if (preferenceManager.getSharedPreferences().getBoolean("display_screen", true)){
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    } 
    else {
    //nothing to do as default value by phone display time
    }
}

How should I call FLAG_KEEP_SCREEN_ON to my MainActivity.java file. When I'm launching my emulator/debug app and opening settings screen, getting dialog box with app closing like "Unfortunately, App has stopped"

Hope, I get a better solutions for this and thanks in advance.


Solution

  • Find solution by myself.

    By using SharedPreferences where we want to activate the key that given in .xml file can be used in any .java file by SharedPreferences as per our requirement.