【发布时间】:2016-11-25 01:25:13
【问题描述】:
如何从后台服务更新RecyclerView Dataset。
该服务与服务器保持一个套接字连接,当服务器响应数据时,service 必须在 recyclerview(即 MainActivity 中)中更新它。
【问题讨论】:
-
具体一点,展示你解决问题的尝试
标签: android broadcastreceiver android-service
如何从后台服务更新RecyclerView Dataset。
该服务与服务器保持一个套接字连接,当服务器响应数据时,service 必须在 recyclerview(即 MainActivity 中)中更新它。
【问题讨论】:
标签: android broadcastreceiver android-service
有很多方法可以将事件从 Serivce 发送到 Activity。
我向你推荐以下方式。
绑定和回调
我认为绑定和回调是官方的方式。
Communication between Activity and Service
Example: Communication between Activity and Service using Messaging
EventBus
我认为 EventBus 很简单。
https://github.com/greenrobot/EventBus
在活动中(或任何地方):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
@Override
protected void onResume() {
super.onResume();
BusHolder.getInstnace().register(this);
}
@Override
protected void onPause() {
super.onPause();
BusHolder.getInstnace().unregister(this);
}
@Subscribe
public void onDatasetUpdated(DataSetUpdatedEvent event) {
//Update RecyclerView
}
}
BusHolder 持有 BusEvent 实例:
public class BusHolder {
private static EventBus eventBus;
public static EventBus getInstnace() {
if (eventBus == null) {
eventBus = new EventBus();
}
return eventBus;
}
private BusHolder() {
}
}
发布的活动:
public class DataSetUpdatedEvent {
//It is better to use database and share the key of record of database.
//But for simplicity, I share the dataset directly.
List<Data> dataset;
public DataSetUpdatedEvent(List<Data> dataset) {
this.dataset = dataset;
}
}
从您的服务发送消息。
BusHolder.getInstnace().post(new DataSetUpdatedEvent(dataset));
我希望这会有所帮助。
【讨论】:
您可能应该使用类似数据库的东西来存储临时数据,因为我认为代表服务组件将数据存储在对象中并不是一件好事。将整个列表数据存储到对象中是多余的,因为无论用户是否返回应用程序,您的对象都会覆盖内存,我们应该在整个开发过程中避免这种情况。祝你好运。
【讨论】: