因图中startActivityForResult此方法已过时,故可采用下面两种方法打开蓝牙:
一、可以直接使用enable来打开蓝牙
public void openBluetooth() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Toast.makeText(getApplicationContext(),"蓝牙已打开",Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(getApplicationContext(),"该设备不支持蓝牙",Toast.LENGTH_SHORT).show();
}
二、可以使用ActivityResultLauncher来调用打开蓝牙
ActivityResultLauncher<Intent> startBlueTooth = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result)
{
if (result==null)
{
Toast.makeText(getApplicationContext(),"打开失败",Toast.LENGTH_SHORT).show();
}
else
{
if (result.getResultCode() == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(),"用户取消",Toast.LENGTH_SHORT).show();
}
}
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 如果设备不支持蓝牙
if (bluetoothAdapter == null)
{
Toast.makeText(getApplicationContext(),"该设备不支持蓝牙",Toast.LENGTH_SHORT).show();
return;
}
// 设备支持蓝牙功能,启动蓝牙
if (!bluetoothAdapter.isEnabled())
{
startBlueTooth.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
}