使用 registerForActivityResult 替代 startActivityForResult.md

以开启蓝牙为例:

private val openBLELauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        Log.d("test", ": $result")
        if (result.resultCode == RESULT_OK) {

        }
    }


private fun turnOnBLE() {
    val bluetoothManager =
        requireContext().getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    val bluetoothAdapter = bluetoothManager.adapter
    if (!bluetoothAdapter.isEnabled) {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        openBLELauncher.launch(enableBtIntent)
    }

}

你可能感兴趣的:(使用 registerForActivityResult 替代 startActivityForResult.md)