我有一個擴展了BroadcastReceiver的類,用於顯示wifi連接是否連接或丟失。我正嘗試使用SharedPreferences將此信息傳遞給另一個活動,但它不起作用。有沒有在BroadcastReceiver類中設置SharedPreferences的特殊方法?請參閱我下面的代碼:如何在BroadcastReceiver中使用SharedPreferences
public class NetworkChangeReceiver extends BroadcastReceiver {
protected SharedPreferences mPrefs;
public static final String PREF_WIFI = "wifi";
@Override
public void onReceive(final Context context, final Intent intent) {
SharedPreferences mPrefs =
PreferenceManager.getDefaultSharedPreferences(
context.getApplicationContext());
String status = NetworkUtil.getConnectivityStatusString(context);
mPrefs.edit().putString(PREF_WIFI, status).commit();
}
}
我甚至試圖建立mPrefs像下面,但仍然沒有運氣
mPrefs = context.getSharedPreferences(PREF_WIFI, Context.MODE_PRIVATE);`
請考慮Receiver的生命期如此短暫,以至於這可能會導致您的問題! – Pavlos
@Pavlos:BroadcastReceiver和Activity都在UI線程上執行。如果在執行廣播接收器之前啓動活動,則可能會出現此問題。 @ cv82:爲什麼不從調用''onCreate''方法調用'NetworkUtil.getConnectivityStatusString(context);'而不是從廣播接收器傳遞這個信息? – gunar