Skip to content

Instantly share code, notes, and snippets.

@antoniolg
Last active March 2, 2023 08:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save antoniolg/edac2587da74668776c4838666102079 to your computer and use it in GitHub Desktop.
Save antoniolg/edac2587da74668776c4838666102079 to your computer and use it in GitHub Desktop.
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)
}
}
@Drjacky
Copy link

Drjacky commented Oct 26, 2021

In a fragment,
https://gist.github.com/antoniolg/edac2587da74668776c4838666102079#file-mainactivity-kt-L15
this is not ready yet and you get:

FragBlah not attached to an activity.

@zakrodionov
Copy link

zakrodionov commented Mar 2, 2023

@Drjacky use fragment.registerForActivityResult(...) not fragment.requestActivity().registerForActivityResult(...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment