Introduction #
You must obtain Bluetooth permission in advance.
Creating a startForResult Launcher #
private val startForResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val intent: Intent? = result.data
Toast.makeText(this, "RESULT_OK", Toast.LENGTH_LONG).show()
// Handle the Intent
}
}Initializing Bluetooth #
private fun bluetoothInit() {
// Bluetooth initialization
val bluetoothManager: BluetoothManager = getSystemService(BluetoothManager::class.java)
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter
// Check bluetoothAdapter
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(this, "Device doesn't support Bluetooth.", Toast.LENGTH_LONG).show()
}
// Check Bluetooth status
if (bluetoothAdapter?.isEnabled == false) {
Toast.makeText(this, "Bluetooth is not enabled", Toast.LENGTH_LONG).show ()
// Enable Bluetooth
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startForResult.launch(intent)
}
}Conclusion #
The results are as follows.
