我使用来自Android的蓝牙指南此示例code,发现这里的 developer.android/guide/topics/connectivity/bluetooth.html 作为连接客户端之下。
I am using this sample code from the Android Bluetooth guide, found here developer.android/guide/topics/connectivity/bluetooth.html under "Connecting as a Client".
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,我称之为
In my onCreate, I call
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); connectionManager= new ConnectionManager(this); connectionManager.start();本的ConnectionManager启动一个ConnectThread和连接线成功地连接到另一台蓝牙设备。然而,布局不会呈现直到ConnectThread回报率(确切地说,当mmSocket.connect()停止阻塞)。我怎样才能获得的布局首先显示?
The connectionManager launches a ConnectThread and the connect thread successfully connects to another bluetooth device. However, the layout isn't rendered until the ConnectThread returns (exactly, when mmSocket.connect() stops blocking). How can I get the layout to display first?
推荐答案记住,的setContentView()只需要一次行动的onCreate()方法返回。考虑到这一点,你应该运行在另一个线程,而不是在UI线程code。
Remember, setContentView() only takes action once the onCreate() method returns. Taking this into account, you should run the code in another thread and not in the UI thread.
您code应该是这个样子:
Your code should look something like this:
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); new Thread(new Runnable() { @Override public void run() { connectionManager= new ConnectionManager(this); connectionManager.start(); } }).start(); }更多推荐
线程阻塞在Android的UI
发布评论