Kotlin - Bluetooth をオンにする

Kotlin で Bluetooth 開発を試した。

前言

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

Kotlin - アプリの権限を取得する

startForResult ランチャーを作る

1
2
3
4
5
6
7
8
9
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 の初期化

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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)
    }
}

Hugo で構築されています。
テーマ StackJimmy によって設計されています。