gpt4 book ai didi

android - 蓝牙的线程或异步任务?

转载 作者:行者123 更新时间:2023-11-29 18:15:41 25 4
gpt4 key购买 nike

我正在编写一个程序,使用蓝牙在 2 个或更多设备之间进行连接。我以 BluetoothChat 为例。

问题是,当它到达“已连接”线程中的“读取”命令时,它似乎卡住了整个程序。

我认为这是正在发生的事情,因为未到达 myThread.run() 之后的命令,但线程内的命令已到达。

我做错了什么吗?

我应该切换到 AsyncTask 来代替 Thread 吗?

我尝试阅读有关该主题的其他一些帖子,但发现它们很难理解。具体来说,如果我应该使用 AsyncTask 那么为什么示例程序使用线程?

这是连接线程中的代码:

    public void run() {
byte[] buffer = new byte[1024];
int bytes;

// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
Log.d(TAG,"Server - BTConnectedThreadServer - run() - before read");
bytes = mmInStream.read(buffer);
Log.d(TAG,"Server - BTConnectedThreadServer - run() - after read");

// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothConstants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
Log.d(TAG,"Server - BTConnectedThreadServer - run() - after send");
} catch (IOException e) {
Log.d(TAG,"Server - BTConnectedThreadServer - run() - disconnected", e);
e.printStackTrace();
BluetoothConstants.connectionLost(mHandler);

break;
}
}
Log.d(TAG,"Server - BTConnectedThreadServer - run() - Exited Loop");
}

出现“阅读前”日志注释,但没有其他内容。它永远不会返回到主线程。

最佳答案

myThread.run() 仍将在同一个线程上运行,您需要 myThread.start(),如果不能解决问题,请显示一些代码

关于android - 蓝牙的线程或异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8261153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com