Skip to content

Instantly share code, notes, and snippets.

@redhead1999
Created June 11, 2023 18:54
Show Gist options
  • Save redhead1999/add234fba65c2cfff7773622b8025092 to your computer and use it in GitHub Desktop.
Save redhead1999/add234fba65c2cfff7773622b8025092 to your computer and use it in GitHub Desktop.
Fixing Bluetooth-off crashing on Android 12 and higher
@RequiresApi(Build.VERSION_CODES.M)
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val bluetoothManager by lazy {
applicationContext.getSystemService(BluetoothManager::class.java)
}
private val bluetoothAdapter by lazy {
bluetoothManager?.adapter
}
private val isBluetoothEnabled: Boolean
get() = bluetoothAdapter?.isEnabled == true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val enableBluetoothLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { /* Not needed */ }
val permissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { perms ->
val canEnableBluetooth = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
perms[Manifest.permission.BLUETOOTH_CONNECT] == true
} else true
if(canEnableBluetooth && !isBluetoothEnabled) {
enableBluetoothLauncher.launch(
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
)
}
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
permissionLauncher.launch(
arrayOf(
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT,
)
)
}
setContent {
BLETutorialTheme() {
Navigation(
onBluetoothStateChanged = {
showBluetoothDialog()
}
)
}
}
}
override fun onStart() {
super.onStart()
showBluetoothDialog()
}
private var isBluetootDialogAlreadyShown = false
private fun showBluetoothDialog(){
if(!bluetoothAdapter?.isEnabled!!){
if(!isBluetootDialogAlreadyShown){
val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startBluetoothIntentForResult.launch(enableBluetoothIntent)
isBluetootDialogAlreadyShown = true
}
}
}
private val startBluetoothIntentForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
isBluetootDialogAlreadyShown = false
if(result.resultCode != Activity.RESULT_OK){
showBluetoothDialog()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment