Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 尝试打开蓝牙功能的捕获方法_Android_Bluetooth - Fatal编程技术网

Android 尝试打开蓝牙功能的捕获方法

Android 尝试打开蓝牙功能的捕获方法,android,bluetooth,Android,Bluetooth,我制作了一个简单的android应用程序,用于连接蓝牙串行设备,我想添加closeBT,如果android未连接,可能由于崩溃,设备超出范围 我该怎么做?这个代码正确吗 protected void onStart() { super.onStart(); findBT(); //Check if bluettoth enable and paired devices try { openBT(); //open sockets,streams

我制作了一个简单的android应用程序,用于连接蓝牙串行设备,我想添加
closeBT
,如果android未连接,可能由于崩溃,设备超出范围

我该怎么做?这个代码正确吗

protected void onStart() {
    super.onStart();
    findBT(); //Check if bluettoth enable and paired devices

    try {
        openBT(); //open sockets,streams
    } catch (IOException e) {
        e.printStackTrace();
        closeBT();
    }
}

Try catch
不适用于应用程序逻辑!这是为了在事情出错时做一些事情!您想在此处使用
if-else
,如

if (findBT() != null) { // I don't know what findBT does, but maybe it returns BT-devices
    try {
        openBT(); //open sockets,streams
    } catch (IOException e) {
        e.printStackTrace();
        // inform the user that a connection could not be established or something similar
    }
} else {
    // inform the user, that no BT-device was found.
}

例如,当用户或您的应用程序决定断开BT设备时,您需要使用
closeBT()

如果您想通知用户,可以使用Toast或对话框。