Решение:
- Добавьте разрешения в AndroidManifest.xml:
Код: Выделить всё
- Запрос разрешения BLUETOOTH_CONNECT во время выполнения:
Код: Выделить всё
private void bluetoothOn() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_ENABLE_BT);
return;
}
if (!mBTAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
bluetoothLauncher.launch(enableBtIntent);
} else {
Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
}
- Обработка результата запроса разрешения:
Код: Выделить всё
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ENABLE_BT) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
bluetoothOn();
} else {
Toast.makeText(this, "Permission denied to access Bluetooth", Toast.LENGTH_SHORT).show();
}
}
}
- Замените startActivityForResult на ActivityResultLauncher:
Код: Выделить всё
ActivityResultLauncher bluetoothLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
mBluetoothStatus.setText("Enabled");
} else {
mBluetoothStatus.setText("Disabled");
}
}
);
Подробнее здесь: https://stackoverflow.com/questions/736 ... android-12
Мобильная версия