2011-09-09 77 views
0

我想添加一個列表作爲參數傳入意圖,然後從廣播監聽器接收它,但我遇到了一些麻煩。我無法弄清楚如何將這個List作爲額外的Intent,或者從中檢索列表。我可以進入廣播接收器。將Wifi的掃描結果列表添加到意圖中並從廣播接收器中檢索?

//In my Main File: Everthing is registered and working. 
IntentFilter startUsingScanResults = new IntentFilter("StartUsingScanResults"); 
c.registerReceiver(serviceConsume.ScanResultReceiver, startUsingScanResults); 

List<ScanResult> scanResults = Some values; 
Intent intent = new Intent(); 
intent.setAction("StartUsingScanResults"); 

// Then Need to put the List<ScanResults> into the intent. 
// ie: intent.putExtra("MyResults", scanResults); 

Context.sendBroadcast(intent); 

//我的廣播接收機應該有它的列表裏面。

public BroadcastReceiver ScanResultReceiver = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context context, Intent intent) { 

      Bundle extras = intent.getExtras(); 

      // Need something here to get the list 
      // ie: List<ScanResult> scanResults = extras.getBundle("MyResults"); 
} 
}; 

希望我很清楚這個問題。我只需要將列表放入並從包(或意圖)中獲取列表。

如果有幫助,ScanResult格式爲[「」,「」,「」,「」,「」,「」,「」]。所以我想它可能類似於多維數組。

任何幫助表示讚賞!謝謝

+0

看看這些線: [傳遞ArrayList和parcelable活性] [1] [1]:http://stackoverflow.com/questions/5819238/help-with-passing-數組列表和-parcelable活動 – motiver

回答

0

我已經想通了。我喜歡簡單的解決方案,而且它非常簡單。

intent.putParcelableArrayListExtra(「ScanResults」,(ArrayList)scanResults);

這添加到廣播接收機

的ArrayList scanResults = extras.getParcelableArrayList( 「ScanResults」);

所以最終的結果是:

//In my Main File: 
IntentFilter startUsingScanResults = new IntentFilter("StartUsingScanResults"); 
c.registerReceiver(serviceConsume.ScanResultReceiver, startUsingScanResults); 

List<ScanResult> scanResults = Some values; 
Intent intent = new Intent(); 
intent.setAction("StartUsingScanResults"); 

intent.putParcelableArrayListExtra("ScanResults", (ArrayList<? extends Parcelable>) scanResults); 

Context.sendBroadcast(intent); 

// And my broadcast receiver 
    public BroadcastReceiver ScanResultReceiver = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context context, Intent intent) { 

      Bundle extras = intent.getExtras(); 
    ArrayList<ScanResult> scanResults = extras.getParcelableArrayList("ScanResults"); 
} 
}; 

希望這幫助了別人了類似的情況。