将单个服务的结果传递给多个片段

时间:2015-04-02 06:36:27

标签: android android-fragments broadcastreceiver android-broadcast intentservice

我的Activity中有ViewPager,每个页面都包含很少的片段。现在一旦片段被加载我正在调用一个服务,他的工作是从webservices获取数据并将结果传递给具有ResultReceiver类的特定片段。更清楚:

FragmentA----->calls FetchDataService()

FragmentB----->calls FetchDataService()

现在FetchDataService没有将结果传递给正确的片段,而是我在FragmentB收到结果,因为它最后调用FetchDataService。在每个片段中获得正确结果的最佳方法是什么。

1 个答案:

答案 0 :(得分:2)

不要让Fragments轮询数据,让他们收听广播。 当FetchDataService从服务器接收到数据时,它必须发送带有数据的广播。每个片段都可以使用正确的intentFilter注册broadcastReceiver来监听FetchDataService的广播。

// Example function to send data with a broadcast
sendData(Context context, Data data) {
    Intent intent = new Intent();
    intent.setAction("fetchedData");
    intent.putExtra("data", data);
    context.sendBroadcast(intent);
}

// Register your reciever to listen to the correct actions (in this case "fetchedData")
BroadcastReceiver broadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("fetchedData") // use same string here as in sender
context.registerReceiver(broadcastReceiver, intentFilter);

// You can create multiple receivers (one for each fragment for example)
public class MyBroadcastReceiver extends android.content.BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if (action.equals("fetchedData")) {
            Data data = (Data)intent.getSerializableExtra("data");
            // Do something with data
        }
    }
}

我会使用字符串“fetchedData”和“data”来制作常量,以防止拼写错误。