我正在尝试使用我的应用程序连接到蓝牙设备(BLE HC05模块),以执行某些IOT功能
下面的代码片段显示了当用户单击特定的设备以进行连接时用于进行新活动的代码。
这在BluetoothActivity.java中
lvPairedDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Intent intent = new Intent(BluetoothActivity.this, TemperatureActivity.class);
intent.putExtra("Bluetooth Device Address", mBTPairedDevices.get(position).getAddress());
startActivity(intent);
}
});
如上所述,我正在发送蓝牙设备的MAC地址。使用它尝试连接到设备。
这是在TemperatureActivity.java中的
Intent intent = getIntent();
Bundle extras = intent.getExtras();
deviceAddress = extras.getString("Bluetooth Device Address");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
device = bluetoothAdapter.getRemoteDevice(deviceAddress);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID);
bluetoothAdapter.cancelDiscovery();
btSocket.connect();
if(btSocket.isConnected())
Toast.makeText(TemperatureActivity.this,"Connected to " + device.getName() + " successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(TemperatureActivity.this,"Couldn\'t connect to " + device.getName() + " properly", Toast.LENGTH_SHORT).show();
outStream = btSocket.getOutputStream();
connectedThread = new ConnectedThread(btSocket);
connectedThread.start();
} catch (IOException e) {
Log.d(TAG, "onResume: Bluetooth device could not be connected using RFCOMM");
Toast.makeText(TemperatureActivity.this, "Connection to device " + device.getName() + " using RFCOMM has failed", Toast.LENGTH_SHORT).show();
finish();
}
根据上面的代码,如果设备离线或拒绝连接,则会出现异常。
在当前情况下,是否有可能在TemperatureActivity.java中使用BluetoothActivity.java中的“进度”对话框并在两种情况下都将其停止(蓝牙连接是否成功建立)
我将使用设备的MAC地址转到TemperatureActivity,如果它成功连接到设备,则应保留在该页面(TemperatureActivity)中,否则,请返回原始页面(BluetoothActivity),并说“无法连接至设备”
我搜索了很多,找不到答案。预先感谢。