pedja
pedja

Reputation: 3413

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;
}

Upvotes: 0

Views: 120

Answers (3)

pedja
pedja

Reputation: 3413

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);

Upvotes: 1

jithinroy
jithinroy

Reputation: 1885

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?

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

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();

Upvotes: 0

Related Questions