Skip to content

Start Acitvity, Request Permissions with coroutine

License

Notifications You must be signed in to change notification settings

skgmn/StartActivityX

Repository files navigation

Setup

dependencies {
    implementation "com.github.skgmn:startactivityx:1.2.0"
}

Features

startActivityForResult

lifecycleScope.launch {
    val activityResult = startActivityForResult(intent)
}

That's it. It provides some extension methods of ActivityResult for the convenience.

val ActivityResult.isOk: Boolean
val ActivityResult.isCanceled: Boolean
fun ActivityResult.getDataIfOk(): Intent?

So returned ActivityResult can be used like this in more kotlin way.

lifecycleScope.launch {
    startActivityForResult(intent).getDataIfOk()?.let { open(it) }
}

requestPermissions

lifecycleScope.launch {
    if (requestPermissions(Manifest.permission.CAMERA).granted) {
        // Permissions are granted here
        startCamera()
    }
}

Simple again. This single method also handles rationale dialog and do not ask again cases so there are no other things to acquire permissions.

There are some more features which are not documented yet. Please refer to source code and sample code to know about them.

PermissionStatus

Sometimes there needs to show or hide views according to whether permissions are granted or not. listenPermissionStatus() has been introduced to manage this case. It returns Flow<Boolean> which infinitely emits boolean values that indicate whether required permissions are granted.

lifecycleScope.launch {
    listenPermissonStatus(Manifest.permission.CAMERA).collect {
        binding.permissionsGranted = it.granted
    }
}
<Button
    android:text="Grant permissions"
    android:visibility="@{permissionsGranted ? View.GONE : View.VISIBLE}" />

Or getPermissionStatus() can be used to get PermissionStatus just once.

startActivityForInstance

This is some kind of bonus feature. It starts an Activity and returns its instance.

lifecycleScope.launch {
    val intent = ExplicitIntent(context, MyActivity::class.java)
    val activity = startActivityForInstance(intent)
}

About

Start Acitvity, Request Permissions with coroutine

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Languages