2013-08-25 46 views
1

我有一個擴展了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);` 
+0

請考慮Receiver的生命期如此短暫,以至於這可能會導致您的問題! – Pavlos

+1

@Pavlos:BroadcastReceiver和Activity都在UI線程上執行。如果在執行廣播接收器之前啓動活動,則可能會出現此問題。 @ cv82:爲什麼不從調用''onCreate''方法調用'NetworkUtil.getConnectivityStatusString(context);'而不是從廣播接收器傳遞這個信息? – gunar

回答

0

如果該活動是相同的應用程序作爲接收器的一部分,它可能是更容易繼承的活動中:

class MyActivity extends Activity { 
    private BroadcastReceiver wifiBR = null; 
    // All the usual things 

    // And add in 
    @Override 
    public void onCreate() { 
     // EVerything else 

     wifiBR = new BroadcastReceiver() { 
      @Override 
      public void onReceive(final Context context, final Intent intent) { 
       String status = NetworkUtil.getConnectivityStatusString(context); 
       wifiChanged(status); 
      } 
     }; 

    IntentFilter filter = new IntentFilter(); 
    filter.addAction(Intent.ACTION_THE_ONE_YOU_WANT); 
    filter.addAction(Intent.ACTION_THE_OTHER_ONE_YOU_WANT); 
    filter.addAction(Intent.ACTION_AND_SO_ON); 
    this.registerReceiver(wifiBR, filter); 
    } 

    // And add in 
    @Override 
    public void onDestroy() { 
     if (wifiBR != null) this.unregisterReceiver(wifiBR); 
    } 

    private void wifiChanged(String status) { 
     // Does something based on status 
    } 
} 

如果有多個活動,這將是更清楚我們對這些每一個活動,創建和刪除的接收器onResume和,並且還將這些信息置於onResume中的共享偏好中。或者只需查詢onResume中的wifi狀態,然後設置一個接收器。

如果存在多個應用程序,那麼您不僅需要更改某些首選項(它是公開可見的),還需要告知其他App的活動已做出更改。這將是更容易的應用程序。擁有自己的廣播接收器。

+0

感謝這工作 – DMC

相關問題