I am struggling with figure out how to close a dialog launched to explain denied permissions.
Using accompanist to ask for permissions:
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(key1 = lifecycleOwner, effect = {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) {
locationPermissionState.launchPermissionRequest()
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
})
In the same composable I launch a dialog depending on denied permissions:
when {
locationPermissionState.status.shouldShowRationale -> {
AlertDialog(
// Dialog to explain to users the permission
)
}
!locationPermissionState.status.isGranted && !locationPermissionState.status.shouldShowRationale -> {
AlertDialog(
// dialog to tell user they need to go to settings to enable
)
}
}
I am stuck figuring out how to close on the dialog when the user click an OK button.
I have tried to use another state that survives recomposition:
val openDialog by remember { mutableStateOf(false) }
....
// if permission state denied
openDialog = true
....
// then in dialog ok
openDialog = false
However when doing that and changing the state of openDialog the function is recomposed. Which just means when I check the permissions state again its still the same and my dialog opens again.
For a general solution handling location permissions requests in Compose you need to keep track of performed permissions requests. Android's permissions request system works in an iterative fashion, and at certain points in this iteration there is no state change to observe and to act upon besides the iteration count. The current Accompanist 0.24.12-rc has a permissions request callback that you can use to do this. Then you can structure your declarative Compose code to take action based on previously observed and saved iteration counts and the current iteration count. (And you could try to abstract it further, creating dedicated states based on iteration count values and differences, but that's not really necessary to make it work; my hope would be that someone will add this in Accompanist at some point.)
For example:
val locationPermissions: List<String> = listOf(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION)
#Stable
interface LocationPermissionsState : MultiplePermissionsState {
/**
* Supplies a well-defined measure of time/progression
*/
val requestCount: UInt
}
#Composable
fun rememberLocationPermissionsState(): LocationPermissionsState {
val requestCountState: MutableState<UInt> = remember { mutableStateOf(0u) }
val multiplePermissionsState: MultiplePermissionsState =
rememberMultiplePermissionsState(locationPermissions) {
if (it.isEmpty()) {
// BUG in accompanist-permissions library upon configuration change
return#rememberMultiplePermissionsState
}
requestCountState.value++
}
return object : LocationPermissionsState, MultiplePermissionsState by multiplePermissionsState {
override val requestCount: UInt by requestCountState
}
}
You can see this solution with a little more context at https://github.com/google/accompanist/issues/819
I'm working on a library that has a couple of ready-made activities.
So far i have my activities in the library, and in the main app, i call it normally with registerForActivityResult to start it.
this means whoever is using my library would be able to see the whole activity.
what i would like to do, is to have the developer call a method in the library class and ask it to do an action, and in the library that method would on its own start the activity, register it for result, and return the result to the calling class through an interface.
the below is what i tried but it gives me error LifecycleOwner is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED
private fun launchScannerActivity(activity: FragmentActivity, callback: ScannerCallback) {
val scanResult =
activity.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode == Activity.RESULT_OK) {
callback.onResult(it.data?.getStringExtra("Some Key") ?: "")
} else {
callback.onFail()
}
}
val intent = Intent(activity, ScannerActivity::class.java)
scanResult.launch(intent);
}
why do i need this:
This library would be an SDK for a SAAS product, so we would like to abstract and obfuscate as much of the implementation as possible from our clients.
You can't really communicate between Activities using interfaces, at least not in a way that is somewhat concise and isn't very prone to leaking. What you can do is expose your own Activity result contract. Then your API could be as simple as some of the ones in ActivityResultContracts. You can look at the source code there to see how to implement it.
Maybe something like this:
class ScannerResultContract : ActivityResultContract<Unit, String?>() {
override fun createIntent(context: Context, input: Unit?): Intent {
return Intent(context, ScannerActivity::class.java)
}
override fun parseResult(resultCode: Int, intent: Intent?): String? {
return if (resultCode == Activity.RESULT_OK) {
intent?.getStringExtra("Some Key")
} else {
null
}
}
}
Client usage:
// In activity or fragment:
val getScannerResult = registerForActivityResult(ScannerResultContract()) { resultString ->
if (resultString != null) {
// use it
} else {
// log no result returned
}
}
//elsewhere:
someListener.setOnClickListener {
getScannerResult.launch()
}
Is there a way to get current activity in compose function?
#Composable
fun CameraPreviewScreen() {
val context = ContextAmbient.current
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this, MainActivity.REQUIRED_PERMISSIONS, MainActivity.REQUEST_CODE_PERMISSIONS // get activity for `this`
)
return
}
}
While the previous answer (which is ContextWrapper-aware) is indeed the correct one,
I'd like to provide a more idiomatic implementation to copy-paste.
fun Context.getActivity(): AppCompatActivity? = when (this) {
is AppCompatActivity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
}
As ContextWrappers can't possibly wrap each other significant number of times, recursion is fine here.
You can get the activity from your composables casting the context (I haven't found a single case where the context wasn't the activity). However, has Jim mentioned, is not a good practice to do so.
val activity = LocalContext.current as Activity
Personally I use it when I'm just playing around some code that requires the activity (permissions is a good example) but once I've got it working, I simply move it to the activity and use parameters/callback.
Edit: As mentioned in the comments, using this in production code can be dangerous, as it can crash because current is a context wrapper, my suggestion is mostly for testing code.
To get the context
val context = LocalContext.current
Then get activity using the context. Create an extension function, and call this extension function with your context like context.getActivity().
fun Context.getActivity(): AppCompatActivity? {
var currentContext = this
while (currentContext is ContextWrapper) {
if (currentContext is AppCompatActivity) {
return currentContext
}
currentContext = currentContext.baseContext
}
return null
}
Rather than casting the Context to an Activity, you can safely use it by creating a LocalActivity.
val LocalActivity = staticCompositionLocalOf<ComponentActivity> {
noLocalProvidedFor("LocalActivity")
}
private fun noLocalProvidedFor(name: String): Nothing {
error("CompositionLocal $name not present")
}
Usage:
CompositionLocalProvider(LocalActivity provides this) {
val activity = LocalActivity.current
// your content
}
For requesting runtime permission in Jetpack Compose use Accompanist library: https://github.com/google/accompanist/tree/main/permissions
Usage example from docs:
#Composable
private fun FeatureThatRequiresCameraPermission(
navigateToSettingsScreen: () -> Unit
) {
// Track if the user doesn't want to see the rationale any more.
var doNotShowRationale by rememberSaveable { mutableStateOf(false) }
val cameraPermissionState = rememberPermissionState(android.Manifest.permission.CAMERA)
PermissionRequired(
permissionState = cameraPermissionState,
permissionNotGrantedContent = {
if (doNotShowRationale) {
Text("Feature not available")
} else {
Column {
Text("The camera is important for this app. Please grant the permission.")
Spacer(modifier = Modifier.height(8.dp))
Row {
Button(onClick = { cameraPermissionState.launchPermissionRequest() }) {
Text("Ok!")
}
Spacer(Modifier.width(8.dp))
Button(onClick = { doNotShowRationale = true }) {
Text("Nope")
}
}
}
}
},
permissionNotAvailableContent = {
Column {
Text(
"Camera permission denied. See this FAQ with information about why we " +
"need this permission. Please, grant us access on the Settings screen."
)
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = navigateToSettingsScreen) {
Text("Open Settings")
}
}
}
) {
Text("Camera permission Granted")
}
}
Also, if you check the source, you will find out, that Google uses same workaround as provided by Rajeev answer, so Jim's answer about bad practice is somewhat disputable.
This extention function allows you to specify activity you want to get:
inline fun <reified Activity : ComponentActivity> Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
else -> {
var context = this
while (context is ContextWrapper) {
context = context.baseContext
if (context is Activity) return context
}
null
}
}
}
Example:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { HomeScreen() }
}
}
#Composable
fun HomeScreen() {
val activity = LocalContext.current.getActivity<MainActivity>()
}
Getting an activity from within a Composable function is considered a bad practice, as your composables should not be tightly coupled with the rest of your app. Among other things, a tight coupling will prevent you from unit-testing your composable and generally make reuse harder.
Looking at your code, it looks like you are requesting permissions from within the composable. Again, this is not something you want to be doing inside your composable, as composable functions can run as often as every frame, which means you would keep calling that function every frame.
Instead, setup your camera permissions in your activity, and pass down (via parameters) any information that is needed by your composable in order to render pixels.
Below is a slight modification to #Jeffset answer since Compose activities are based off of ComponentActivity and not AppCompatActivity.
fun Context.getActivity(): ComponentActivity? = when (this) {
is ComponentActivity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
I actually found this really cool extension function inside the accompanist
library to do this:
internal fun Context.findActivity(): Activity {
var context = this
while (context is ContextWrapper) {
if (context is Activity) return context
context = context.baseContext
}
throw IllegalStateException("Permissions should be called in the context of an Activity")
}
which gets used inside a composable function like this:
#Composable
fun composableFunc(){
val context = LocalContext.current
val activity = context.findActivity()
}
Let's say I have a component that needs to be initialized and destroyed depending on the lifecycle of the activity. However, this component needs to be granted permissions from the user first. What is the best way to do that?
Do I have to subscribe to the same observer in two different positions or there is a better way to do it without code duplication?
You can implement life cycle aware class encapsulates permission sensitive work:
class MyLifecycleAware {
private var blObject: Any? = null
/**
* Manually call this method when permission granted
*/
#OnLifecycleEvent(Lifecycle.Event.ON_START)
fun init() = withPermission {
// code will be invoked only if permission was granted
blObject = TODO("Initialize business logic")
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun destroy() {
blObject?.destroy()
blObject = null
}
/**
* Wrap any permission sensitive actions with this check
*/
private inline fun withPermission(action: () -> Unit) {
val permissionGranted = TODO("Check permission granted")
if (permissionGranted)
action()
}
}
I am quite new in android programming. I would like to ask about startActivityForResult() and ActivityCompat.requestPermissions() function and their design. I understand that result of those functions is handled by another Activity functions (onActivityResult() and onRequestPermissionsResult() respectively). But I don't understand why is it designed this way.
Especially with ActivityCompat.requestPermissions(). Why do I have to control if I have permission (ContextCompat.checkSelfPermission()), if I don't then ask for it (ActivityCompat.requestPermissions()). And then handle in completely different function if I got this permission or not?
I would expect somethink like:
askPermission(Context context, String permission, Runnable permissionGranted, Runnable permissionDenied)
which would call permissionGranted if I already have permission or if I got it from user. With this function I would have to care just if I have permission or I don't have it.
Now I have to distunguish if I have permission and then do synchronous task or I don't have it and then do "asynchronous" task in onRequestPermissionsResult() where I very often do the same, as I do if I already have permission.
My question is: Is there some reason, why are permissions designed this way? Is there some funtion as I wrote above to allow me just say what to do if I have and what to do if i don't have permission (in functional way)? Or is there some desing pattern to easy handle permissions and starting activities for result?
Thanks for your time and some explanation if you know why is this design good.
Definitely Not a good way!
If we use inheritence concept we may solve this problem a little
we can make it synchronous like this :
//Kotlin
askForPermissions(permissionList, onPermissionsGranted = {
//If permissions given
}, onPermissionFailed = {
//If permissions not given
})
buy using inheritence :
//Kotlin
open class PermissionActivity : AppCompatActivity() {
private val PERM_REQ_CODE = 1457
private lateinit var onPermissionsGranted: () -> Unit;
private lateinit var onPermissionFailed: () -> Unit;
private lateinit var perms: Array<String>
internal fun askForPermissions(perms: Array<String>, onPermissionsGranted: () -> Unit, onPermissionFailed: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkIfOneNotHasPermission(perms)) {
//Dont have permissions
this.perms = perms
this.onPermissionsGranted = onPermissionsGranted
this.onPermissionFailed = onPermissionFailed
requestPermissions(perms, PERM_REQ_CODE)
}
} else {
onPermissionsGranted.invoke()
}
}
#RequiresApi(Build.VERSION_CODES.M)
private fun checkIfOneNotHasPermission(perms: Array<String>): Boolean {
perms.forEach {
if (checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED) {
return true
}
}
return false
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
PERM_REQ_CODE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkIfOneNotHasPermission(perms)) {
onPermissionFailed.invoke()
} else {
onPermissionsGranted.invoke()
}
} else {
onPermissionsGranted.invoke()
}
}
else -> {
onPermissionFailed.invoke()
}
}
}
}