Android & Kotlin・Bluetooth をオンにする

前言

この操作をする前に Bluetooth 権限を取得する必要がある。

startForResult ランチャーを作る

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
    }
}

Bluetooth の初期化

private fun bluetoothInit() {
    // bluetooth init
    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()
    }

    // get bluetooth
    if (bluetoothAdapter?.isEnabled == false) {
        Toast.makeText(this, "bluetoothAdapter is not enable", Toast.LENGTH_LONG).show()

        // Bluetooth を有効する
        val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startForResult.launch(intent)
    }
}