简体   繁体   中英

How to get most recent sharedPreferences

I have a background service that reads cpu usage and frequency and displays it on notification bar

In application settings(Preferences) i have a option to chose to display only frequency only load or both

But method for getting shared preferences wont get most recent SharedPreference

it get SharedPreference only first time service starts and if i chose diferent option in Preference screen it wont update in service

Here is the code

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    Runnable runnable = new Runnable() {@Override
        public void run() {
            while (thread) {

                sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
                items = sharedPrefs.getString("notif", "freq");
                System.out.println(items); //this keeps displaying the same value even if i go to Preference screen and change to something else
                if (items.equals("freq") || items.equals("both")) {

                }
                if (items.equals("load") || items.equals("both")) {

                } //reading frequency and load depending on what is selected
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.post(new Runnable() {@Override
                    public void run() {
                        if (thread) {
                            createNotification(); //create notification
                        }
                    }
                });
            }
        }
    };
    new Thread(runnable).start();

    return START_STICKY;
}

SOLVED

Because my service was running in separate process i had to add this flag when accesing shared preference

private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;

and change like this

sharedPrefs = this.getSharedPreferences("preference name", PREFERENCES_MODE);

Ensure you write your data to shared preferences correctly, specifically you commit() your changes, as docs say :

All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()

Here is example code:

SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean( key, value );
editor.commit();

I think the error is on the line

sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

where you are passing 'this' from inside a thread? Can you change it with the application context?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM