Android ListView表示在非UI线程库API设计中频繁更改的数据

Android ListView表示在非UI线程库API设计中频繁更改的数据,android,android-listview,android-adapter,Android,Android Listview,Android Adapter,我有一个场景,ListView需要表示一个可以在非UI线程上随时修改的数据数组 我已经了解了确保适配器的备份数据不会被非UI线程同时修改的技术,而列表视图通过适配器重新绘制自身。本质上,这些技术都可以归结为确保适配器拥有自己的数据副本,该副本只在UI线程上被触及。各种选项,如runOnUiThread()或AsyncTask的onpostexcute()提供了确保仅在UI线程上修改UI线程“复制”的方法 我的问题更多的是一个设计问题。我的应用程序涉及通过TCP套接字连接从硬件设备收集的数据的表示

我有一个场景,
ListView
需要表示一个可以在非UI线程上随时修改的数据数组

我已经了解了确保
适配器
的备份数据不会被非UI线程同时修改的技术,而
列表视图
通过
适配器
重新绘制自身。本质上,这些技术都可以归结为确保
适配器
拥有自己的数据副本,该副本只在UI线程上被触及。各种选项,如
runOnUiThread()
AsyncTask
onpostexcute()
提供了确保仅在UI线程上修改UI线程“复制”的方法

我的问题更多的是一个设计问题。我的应用程序涉及通过TCP套接字连接从硬件设备收集的数据的表示。我希望将该硬件设备表示为一个库,以便通过一组API方法观察和访问其中的数据。设备将被表示为一个对象,该对象表示设备状态的本地缓存。在库中,数据将根据套接字读取线程上的套接字
read()
调用进行更改。由于该库需要在桌面PC应用程序中使用,因此我无法在其中使用Android框架组件来导致UI线程上发生数据更改。因此,当库从硬件获取新数据时,数据更改和后续的观察者回调将发生在非UI线程上

让Android应用程序在不需要维护应用程序中所有数据的(浅层)副本的情况下,对库中的数据保持UI线程安全的直接查看,哪种优雅的方式

到目前为止,我的一个想法是设计这个库,让用户应用程序可以选择“截获”TCP消息处理,这样就可以在UI线程上进行。例如,Android应用程序可能会使用如下库:

// HardwareDevice is my library - an abstracty representation of 
// networked hardware box that spits out lots of state data.

HardwareDevice mDevice = new HardwareDevice(); // Create abstraction of the device

// As standard, the library will do its JSON message parsing and 
// subsequent data modifications on the socket read thread. 
// This is an optional way to change intercept that behaviour so that the
// processing happens on the UI thread.
mDevice.setMessagePreprocessor(new MessagePreprocessor(){
    void processMessage(String message){
        runOnUiThread(new Runnable() {
            public void run() {
                mDevice.processMessage(message);
            }
        }
    });
})
mDevice.getArrayListOfStuff()
未测试代码,因此可能存在语法错误,但关键是:这是一种让库在Android应用程序中使用时在Android UI线程上执行回调和数据更改的方法,而不必让库本身特定于Android。据我所见,这将使应用程序的其余部分更容易创建,因为它可以最大限度地减少对大量数据的同步/复制

换句话说,从现在开始,我可以非常安全地获取如下数据列表:

// HardwareDevice is my library - an abstracty representation of 
// networked hardware box that spits out lots of state data.

HardwareDevice mDevice = new HardwareDevice(); // Create abstraction of the device

// As standard, the library will do its JSON message parsing and 
// subsequent data modifications on the socket read thread. 
// This is an optional way to change intercept that behaviour so that the
// processing happens on the UI thread.
mDevice.setMessagePreprocessor(new MessagePreprocessor(){
    void processMessage(String message){
        runOnUiThread(new Runnable() {
            public void run() {
                mDevice.processMessage(message);
            }
        }
    });
})
mDevice.getArrayListOfStuff()
…并安全地使用它直接支持
适配器
,即使底层数据经常发生异步更改


这是一个好策略吗?我是否错过了一个更明显的选择

您知道如何在非UI线程中操作ArrayList吗?