0

我有一个后台服务,可以读取 cpu 使用情况和频率并将其显示在通知栏上

在应用程序设置(首选项)中,我可以选择仅显示频率负载或两者

但是获取共享首选项的方法不会获得最新的 SharedPreference

它仅在第一次服务启动时获得 SharedPreference,如果我在 Preference 屏幕中选择了不同的选项,它不会在服务中更新

这是代码

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

3 回答 3

1

解决了

因为我的服务在单独的进程中运行,所以在访问共享首选项时我必须添加这个标志

private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;

像这样改变

sharedPrefs = this.getSharedPreferences("preference name", PREFERENCES_MODE);
于 2012-11-19T12:05:36.310 回答
0

确保您正确地将数据写入共享首选项,特别是您commit()的更改,正如文档所说

您在编辑器中所做的所有更改都是批处理的,并且在您调用 commit() 或 apply() 之前不会复制回原始 SharedPreferences

这是示例代码:

SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean( key, value );
editor.commit();
于 2012-11-19T11:29:40.150 回答
0

我认为错误在线

sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

您从线程内部传递“this”的位置在哪里?您可以使用应用程序上下文更改它吗?

于 2012-11-19T12:03:20.577 回答