0

我目前正在尝试解决我在使用需要蓝牙连接的 Android 应用时遇到的问题。有那么一刻,一切似乎都正常,但是当我要连接的从属蓝牙设备未通电时,我注意到一些奇怪的事情。这是我的代码:

private void connectDevice() {
    mBluetoothAdapter.cancelDiscovery();
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "Socket create failed: " + e.getMessage() + ".");
    }


    //Try to establish the connection.  This will block until it connects.
    Log.d(TAG, "...Connecting...");
    try {
      btSocket.connect();
      Log.d(TAG, "....Connection ok...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "Unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }

    //Create a data stream so we can talk to server.
    Log.d(TAG, "...Create Socket...");
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();
    mActionBar.setSubtitle("Connected");

    return;
    }  

这里是我调用这个方法的地方:

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode){
    case REQUEST_ENABLE_BT:
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, R.string.bt_enabled, Toast.LENGTH_SHORT).show();
            setupCom();
            break;
        }
        else {
            // User did not enable Bluetooth or an error occurred
            if(D)   Log.d(TAG, "BT not enabled");
            Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
            finish();
            break;
        }
    case REQUEST_CONNECT_DEVICE:
        if (resultCode == RESULT_OK){
            retrieveAddresse(data);
            connectDevice();
        }
        break;
    }
    return;
}

我的问题是,当我不在范围内或我要连接的设备未打开电源时,即使由于 Android 操作系统不想要而无法连接,connectDevice() 方法似乎也会执行所有代码被连接进程阻塞。我注意到这个问题是因为 mActionBar.setSubtitle("Connected"); 被执行,因为当我在范围内或从属蓝牙模块打开时尝试重新连接时。除非我重新启动我的应用程序,否则我无法连接到它。

4

1 回答 1

0

把这些行:

mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
mActionBar.setSubtitle("Connecté");

第一次尝试里面。这样,只有在设备建立连接时才会执行它们。实际上它们在 try/catch 之外,即使没有连接,它们也将始终执行。

于 2013-03-05T03:19:24.373 回答