锁定机制锁定UI线程的片段中的java Update ListView
我有一个列表视图,我想用来自蓝牙插座的消息更新它。ListView是一个片段,这并不重要。
当我想要监听来自socket的传入消息(这是一个单独线程上的锁定机制)并用接收到的消息更新ListView时,就会出现问题
FChat。java
public class FChat extends Fragment {
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> itemsAdapter;
....
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setup list view
ListView messageContainer = (ListView) thisView.findViewById(R.id.btMessagesContainer);
itemsAdapter = new ArrayAdapter<String>(thisView.getContext(), 安卓.R.layout.simple_list_item_1, listItems);
currentAct = getActivity();
Thread test = new Thread() {
public void run() {
try {
currentAct.runOnUiThread(new Runnable() {
@Override
public void run() {
listItems.add("other:" + String.valueOf(times));
try {
String reply = bluetoothConnector.readSingleMessage();
listItems.add("other:" + reply);
itemsAdapter.notifyDataSetChanged();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
test.start();
}
}
所以,这感觉就像它完全阻塞了UI线程,所以我猜RunNuithread它阻塞了UI线程。
如果我取出阻挡部分
String reply = bluetoothConnector.readSingleMessage();
并将其替换为String reply = "test"
它运行良好,UI已更新,似乎运行良好。
所以,我的问题是,如何从socket读取数据并用其内容更新ListView?
谢谢
# 1 楼答案
显然,它阻止了
UI thread
您的代码在pseudo中的外观:
换句话说,由于您在UI线程中执行阻塞操作,所以当前线程几乎毫无用处
当然,它与
因为这不是阻塞操作
所以要解决问题,就行动吧
内部分开线程: