Ich will den Permission Check von der MainAktivity in ein Objekt auslagern, dabei geht der context verloren. Wie krieg ich das wieder hin?
HIer ist die MainActivity.kt
Code
package com.example.bluetoothdemo2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.example.bluetoothdemo2.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var B: ActivityMainBinding
private val myPermissions = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) {
result -> permissionResultCallback(result) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
B = ActivityMainBinding.inflate(layoutInflater)
setContentView(B.root)
}
override fun onStart() {
super.onStart()
if (Permissions.get(myPermissions)) {
} else {
}
}
private fun permissionResultCallback(map: Map<String,Boolean>) {
if (map.filterValues { it == false }.isEmpty()) {
} else {
}
}
}
Alles anzeigen
Und hier Permission.kt und für this@MainActivity folgt die Fehlermeldung: unresolved Reference.
Code
package com.example.bluetoothdemo2
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.result.ActivityResultLauncher
import androidx.core.app.ActivityCompat
object Permissions {
fun get(myPermissions: ActivityResultLauncher<Array<String>> ) : Boolean {
val rightsArray = if (Build.VERSION.SDK_INT < 31) arrayOf(
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION) else arrayOf(
Manifest.permission.BLUETOOTH_CONNECT)
for (right in rightsArray) {
if (ActivityCompat.checkSelfPermission(
this@MainActivity, right) != PackageManager.PERMISSION_GRANTED) {
myPermissions.launch(rightsArray)
return false
}
}
return true
}
fun check() : Boolean {
return (Build.VERSION.SDK_INT < 31 ||
ActivityCompat.checkSelfPermission( this@MainActivity,
Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED)
}
}
Alles anzeigen