从服务更新“RecyclerView”数据集



如何从后台服务更新RecyclerView Dataset。服务与服务器保持套接字连接,当服务器用数据响应时,service必须更新recyclerview(即MainActivity)中的数据。

有很多方法可以将事件从Serivce发送到Activity
我向你推荐以下方法。

绑定和回调

我认为绑定和回调是正式的方式
活动和服务之间的通信
示例:使用消息在活动和服务之间进行通信

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));

我希望这能有所帮助。

可能应该使用一些类似数据库的东西来存储临时数据,因为我认为代表服务组件将数据存储在对象中不是一件好事。将整个列表数据存储到对象中是多余的,因为无论用户是否返回应用程序,您的对象都将覆盖内存,而在整个开发过程中我们都应该避免这种情况。祝你好运。

最新更新