gpt4 book ai didi

android - Android 中的线程阻塞 UI

转载 作者:行者123 更新时间:2023-11-30 03:28:32 25 4
gpt4 key购买 nike

我正在使用 Android 蓝牙指南中的示例代码,可在此处找到 http://developer.android.com/guide/topics/connectivity/bluetooth.html在“作为客户端连接”下。

private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;

// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}

public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();

try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}

// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}

/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}

在我的 onCreate 中,我调用

protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
connectionManager= new ConnectionManager(this);
connectionManager.start();

connectionManager 启动一个 ConnectThread 并且连接线程成功连接到另一个蓝牙设备。但是,直到 ConnectThread 返回时才会呈现布局(确切地说,当 mmSocket.connect() 停止阻塞时)。我怎样才能让布局首先显示?

最佳答案

与其从 UI 线程创建连接管理器,不如在工作线程中创建它,如下所示:

protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
new Thread(new Runnable() {

@Override
public void run() {
connectionManager= new ConnectionManager(YourActivity.this);
connectionManager.start();
}
}).start();

这样您就永远不会阻塞 UI 线程,希望这对您有所帮助...

问候!

关于android - Android 中的线程阻塞 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17845388/

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