2012-11-19 78 views
0

我有一個後臺服務讀取CPU使用率和頻率,並顯示通知欄如何獲得最新sharedPreferences

在應用程序設置(首),我有一個選項可以選擇只顯示頻率只有負載或兩者上

但方法得到共享偏好不會得到最新SharedPreference

它得到SharedPreference只有第一次服務啓動,如果我選擇了diferent選項偏好屏幕它的服務不會更新

下面是代碼

@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; 
} 
+0

你叫' commit()'在sharedPref的編輯器上? –

+0

不要給標的添加標籤 –

+0

我不需要。我使用PreferenceActivity。如果我看起來像/data/data/myapp/shared_prefs/sharedPrefs_file.xml中的manualy值是新鮮的,但在服務中,它始終顯示舊值 – pedja

回答

0

確保你正確撰寫你的數據共享偏好,特別是你commit()更改,as docs say

你做出的所有更改在編輯器中是成批的,而不是複製回到 原來SharedPreferences直到調用commit()或應用()

下面是示例代碼:

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

我使用PreferenceActivity。這一切都是自動完成的 – pedja

0

我認爲錯誤就行

sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); 

你在哪裏傳遞「這個」線程裏面?你可以用應用程序上下文來改變它嗎?

1

解決

因爲我的服務是在單獨的進程中運行,我不得不accesing共享時添加這個標誌偏好

private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS; 

,改變這樣

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