Android 尝试打开蓝牙功能的捕获方法
我制作了一个简单的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
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或对话框。