2012-04-14 65 views
0

我正在研究一種可以通過其他手機通過短信控制的Android應用程序。我使用PreferenceScreen作爲佈局(設置應用程序的一部分)。調用onResume()時更新佈局。動態更新接口

當通過其他手機發送命令(SMS)時,在後臺運行的服務窺探傳入的短信並更改保存在SharedPreferences中的設置。爲了查看這些更改,我的活動需要執行onResume中的代碼。如果我回到以前的活動並回來,我可以看到變化。

我想要通過運行服務更改SharedPreferences並儘快顯示更改。我該怎麼做才能做到這一點?

回答

1

事情是這樣的:

public class MyActivity extends Activity implements OnSharedPreferenceChangeListener 
{ 
    public static final String PREFS_NAME = "MyPrefsFile"; 

    @Override 
    protected void onCreate(Bundle state) 
    { 
     /* get shared preferences */ 
     SharedPreferences mySharedPreferences = getSharedPreferences(PREFS_NAME, 0); 

     /* register listener for changes to the values within the shared preferences */ 
     mySharedPreferences.registerOnSharedPreferenceChangeListener(this); 
    } 

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) 
    { 
     /* perform application processing */ 
     ... 

     /* update layout */ 
     View myView = findViewById(id.my_view); 

     /* invalidate the view causing it to be redrawn */ 
     myView.invalidate(); 
    } 
} 
+0

thanku快速響應。如果對與mySharedPreferences關聯的對象進行更改,則此代碼有效。在我的服務中,我創建了一個SharedPreferences的新實例。因此,如果在服務中進行更改,則不會調用當前Activity中的onSharedPreferenceChanged! – 2012-04-14 01:15:29

+0

請點擊這裏:[如何讓Android服務與活動進行通信](http://stackoverflow.com/questions/2463175/how-to-have-android-service-communicate-with-activity) – flukey 2012-04-14 02:15:53

+0

我用代碼解決了但是,這是問題http://stackoverflow.com/questions/10150480/registeronsharedpreferencechangelistener-not-working-for-changes-made-in-differe – 2012-04-14 02:26:01