从服务更新“RecyclerView”数据集

Update `RecyclerView` dataset from a service

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

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

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

绑定和回调

我认为绑定和回调是官方方式。
Communication between Activity and Service
Example: Communication between Activity and Service using Messaging

事件总线

我认为 EventBus 是简单的方法。
https://github.com/greenrobot/EventBus

在Activity(或任何地方):

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

希望对您有所帮助。