gpt4 book ai didi

安卓蓝牙 : A thread started from UI thread blocks the UI thread

转载 作者:行者123 更新时间:2023-11-29 01:20:12 26 4
gpt4 key购买 nike

我正在学习安卓蓝牙编程。我从 Google 的 Android 开发者网站上复制了大部分代码以供学习。这个想法是监听服务器上的连接是在一个新线程中完成的,而不会阻塞 UI 线程。当收到连接请求时,连接在另一个线程上完成,最后通信在另一个线程上完成。

问题是当我从 UI 线程启动监听线程时,它会自动阻塞并且不显示任何 UI(卡住)。这是示例代码:

public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
...

badapter = BluetoothAdapter.getDefaultAdapter();
if (badapter == null) {
Toast.makeText(this, "No bluetooth device.", Toast.LENGTH_SHORT).show();
return;
}

if (!badapter.isEnabled()) {
Toast.makeText(this, "Bluetooth is disabled.", Toast.LENGTH_SHORT).show();
return;
}

pairedDevices = new HashMap<String, String>();
discoveredDevices = new HashMap<String, String>();

showDevices();
registerBroadcastReceiver();

//this thread blocks UI thread
ListenThread listen = new ListenThread();
listen.run();
}

监听线程:

public class ListenThread extends Thread {
MainActivity main;
CommunicateThread communicateThread;
private final BluetoothServerSocket serverSocket;

public ListenThread() {
main = MainActivity.getInstance();

BluetoothServerSocket tmp = null;
try {
tmp = main.badapter.listenUsingRfcommWithServiceRecord(main.NAME, main.MYUUID);
} catch (final IOException e) {
main.handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(main, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
serverSocket = tmp;
}

public void run() {
BluetoothSocket socket = null;

//keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = serverSocket.accept();
} catch (final IOException e) {
main.handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(main, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
break;
}

// If a connection was accepted
if (socket != null) {
//call communication thread once connection is established
communicateThread = new CommunicateThread(socket);
communicateThread.run();

try {
serverSocket.close();
} catch (final IOException e) {
main.handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(main, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
break;
}
}
}
}

最佳答案

您在主线程上调用 listen.run() 使其在主线程上运行。您应该调用 listen.start(),这将产生一个单独的线程,其中将执行 run() 方法。

尽管 Handler 是针对主线程的,但提供给处理程序的 Runnable 将在主线程上执行。

关于安卓蓝牙 : A thread started from UI thread blocks the UI thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292125/

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