[英]How to get most recent sharedPreferences
我有一個后台服務,可以讀取cpu的使用情況和頻率並將其顯示在通知欄上
在應用程序設置(首選項)中,我可以選擇僅顯示僅頻率負載,或同時顯示兩個負載
但是獲取共享首選項的方法不會獲取最新的SharedPreference
它只有在第一次服務啟動時才獲得SharedPreference,如果我在“首選項”屏幕中選擇了不同的選項,它將不會在服務中更新
這是代碼
@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;
}
解決了
因為我的服務在單獨的進程中運行,所以在訪問共享首選項時必須添加此標志
private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;
像這樣改變
sharedPrefs = this.getSharedPreferences("preference name", PREFERENCES_MODE);
確保正確地將數據寫入共享的首選項,特別是按照文檔說 , commit()
更改:
您在編輯器中所做的所有更改都將被分批處理,並且直到您調用commit()或apply()時,才將其復制回到原始的SharedPreferences中。
這是示例代碼:
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean( key, value );
editor.commit();
我認為錯誤就在網上
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
您從線程內部傳遞“ this”在哪里? 您可以使用應用程序上下文進行更改嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.