Skip to content

Instantly share code, notes, and snippets.

@antoniolg antoniolg/MainActivity.kt

Last active Jul 7, 2020
Embed
What would you like to do?
Shows how to use permissions with registerForActivityResult(). Code for https://devexperto.com/permisos-android-11
private fun Context.openSettings() {
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
addCategory(Intent.CATEGORY_DEFAULT)
data = Uri.parse("package:$packageName")
}.let(::startActivity)
}
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val coarseLocation = PermissionRequester(this, ACCESS_COARSE_LOCATION,
onDenied = { toast("Permission Denied") },
onShowRationale = { toast("Should show Rationale") })
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
coarseLocation.runWithPermission {
toast("Success")
}
}
}
}
class PermissionRequester(
activity: ComponentActivity,
private val permission: String,
onDenied: () -> Unit = {},
onShowRationale: () -> Unit = {}
) {
private var onGranted: () -> Unit = {}
private val launcher =
activity.registerForActivityResult(RequestPermission()) { isGranted ->
when {
isGranted -> onGranted()
activity.shouldShowRequestPermissionRationale(permission) -> onShowRationale()
else -> onDenied()
}
}
fun runWithPermission(onGranted: () -> Unit) {
this.onGranted = onGranted
launcher.launch(permission)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.