开发者

How to get CheckBoxPreference value within the Receiver/Service in Android?

I use CheckBoxPreference in my PreferenceActivity to set a value. Later on, I want to check开发者_开发技巧 that value from Receiver and/or Service. findPreference() method is not available from that context. I know, that this preference value is stored in SharedPreferences anyway, but what is the key? How could I get the value of the checkbox?


I know, that this preference value is stored in SharedPreferences anyway, but what is the key?

Whatever value you have for android:key in your preference XML.

How could I get the value of the checkbox?

Call PreferenceManager.getDefaultSharedPreferences() to get the SharedPreferences, then call getBoolean() with the key you used in android:key.


In your preferences XML you'll have something like this:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:enabled="true"
    android:title="@string/s_pref" android:key="@string/pref"
    android:defaultValue="@string/d_pref"></CheckBoxPreference>
</PreferenceScreen>

Your strings.xml would have something like this:

<string name="pref">my.package.PREF</string>
<string name="s_pref">Prompt</string>
<string name="d_pref">true</string>

Your Activity's onCreate() would have something like this:

prefs = PreferenceManager.getDefaultSharedPreferences(this);
pref = prefs.getBoolean(getString(R.string.pref), true));

If you want to do something when someone changes the preferences, add an onActivityResult() to your activity and start the preferences activity with startActivityForResult(). When onActivityResult() is invoked with whatever result code you want to indicate a change in preferences, you can do another getDefaultSharedPreferences().

The shared preferences framework automatically persists the data... you don't have to actively deal with it yourself, though you can if you wish with an OnPreferenceChangeListener in the preferences activity


The only thing I would add to CommonsWare's answer is, since you mentioned a service, you can put whatever preferences the service needs to know about in its Intent extras. For example:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent intent = new Intent(this, MyService.class);
intent.putExtra("mypref", prefs.getString("mypref", ""));
startService(intent);


try to write this in your service

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplication());

and here specify the key that you have used in xml

 if(preferences.getBoolean(your key ,true))
            {

hope this help .

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜