【发布时间】:2018-07-30 11:20:48
【问题描述】:
我有一个 ListView,我想用来自蓝牙套接字的消息来更新它。 ListView 在一个片段中,这无关紧要。
当我想监听来自套接字的传入消息(这是一个单独线程上的锁定机制)并使用接收到的消息更新 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(), android.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 线程,所以我猜那 runOnUiThread 它阻塞了 UI 线程。
如果我取出阻塞部分
String reply = bluetoothConnector.readSingleMessage(); 并用 String reply = "test" 替换它,它工作正常,用户界面已更新,似乎工作得很好。
那么,我的问题是,如何从套接字读取数据并使用其内容更新 ListView?
谢谢
【问题讨论】:
标签: java android multithreading listview