Kotlin startActivityForResult mit launch

  • Antworten:0
  • Forum-Beiträge: 537

24.04.2022, 11:55:00 via Website

Hallo zusammen

Ich habe ein Beispiel welches den Bluetoothsensor abfragt. In diesem Beispiel wird noch mit "startActivityForResult" eine Activity gestartet. Da dies veraltet ist, habe ich es auf einen Launcher umgestellt.

package ch.robbisoft.bluetoothscannerdemo

import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.app.Activity
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import ch.robbisoft.bluetoothscannerdemo.databinding.ActivityMainBinding

private const val REQUEST_ENABLE_BLUETOOTH = 123
private const val REQUEST_FINE_LOCATION = 321

private enum class BluetoothState {
NotAvailable, Disabled, Enabled
}

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
private var started = false

private val adapter = BluetoothAdapter.getDefaultAdapter()
private val receiver = object : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        if( intent != null ) {
            if (BluetoothDevice.ACTION_FOUND == intent.action) {
                val device =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                binding.tv.append(getString(R.string.template, device?.name, device?.address, device?.type))
            }
        }
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)

    val fileter = IntentFilter(BluetoothDevice.ACTION_FOUND)
    registerReceiver(receiver, fileter)
}

override fun onDestroy() {
    super.onDestroy()
    unregisterReceiver(receiver)
}

override fun onStart() {
    super.onStart()
    started = false
    if( getBluetoothState() == BluetoothState.NotAvailable ){
        binding.tv.text = getString(R.string.not_available)
    }else{
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) {
                requestPermissions(arrayOf(ACCESS_FINE_LOCATION), REQUEST_FINE_LOCATION)
            } else {
                showDevices()
            }
        }
    }
}

override fun onPause() {
    super.onPause()
    if( started ){
        adapter?.cancelDiscovery()
        started = false
    }
}

override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if(requestCode == REQUEST_FINE_LOCATION && grantResults.isNotEmpty() && grantResults[0] == PERMISSION_GRANTED){
        showDevices()
    }
}

private fun getBluetoothState() : BluetoothState {
    val state = if( adapter != null ){
        if(adapter.isEnabled){
            BluetoothState.Enabled
        }else{
            BluetoothState.Disabled
        }
    }else{
        BluetoothState.NotAvailable
    }
    if(state == BluetoothState.Disabled){
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)

// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLUETOOTH)
getactivityresult.launch(enableBtIntent)
}
return state
}

private fun showDevices(){
    val sb = StringBuilder()
    sb.append(getString(R.string.paired))
    adapter?.bondedDevices?.forEach{
        sb.append(getString(R.string.template, it.name, it.address, it.type))
    }
    sb.append("\n")
    if( started ){
        adapter?.cancelDiscovery()
    }
    started = adapter?.startDiscovery() ?: false
    if( started ){
        sb.append(getString(R.string.others))
    }
    binding.tv.text = sb.toString()
}

val getactivityresult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result : ActivityResult? ->
    if( result != null ) {
        if (result.resultCode == Activity.RESULT_OK) {

// result.data
}
}
}
}

Der Aufruf der Activity erfolgt über den Befehl "startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLUETOOTH)". Nun weiss ich nicht was ich mit dem "REQUEST_ENABLE_BLUETOOTH" machen soll. Muss ich den im Launcher abfragen oder was mache ich damit?

Gruss Renato

Beantworte die Frage als Erster