A lightweight library for requesting and consuming Activity Results using coroutines, it's usage is as simple as:
val uri = ActivityResultManager.getInstance().requestResult(
contract = GetContent(),
input = "image/*"
)
or using the built-in extensions:
val uri = ActivityResultManager.getInstance().getContent("image/*")
For more information, check the articles: Part 1 and Part 2
The library offers a utility class for requesting runtime permissions with access to the shouldShowRequestPermissionRationale's value:
val result = PermissionManager.getInstance()
.requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
when (result) {
PermissionGranted -> {
// TODO
}
is PermissionDenied -> {
if (result.shouldShowRationale) {
// TODO
} else {
// TODO
}
}
}
This class uses internally ActivityResultManager.getInstance().requestPermission()
, so everything
below applies to it as well.
implementation 'dev.hichamboushaba.suspendactivityresult:suspendactivityresult:0.1.5'
The default artifact uses App Startup for the initialization.
If you don't want this dependency added, you can use the other variant:
implementation 'dev.hichamboushaba.suspendactivityresult:suspendactivityresult-no-startup:0.1.5'
And initialize the library manually
class App : Application() {
fun onCreate() {
super.onCreate()
ActivityResultManager.init(this)
}
}
ActivityResultManager
is an interface, so for better testability, it's recommended to
inject ActivityResultManager.getInstance()
into your components, for easier swapping to a fake or mocked implementation for tests.
The implementation of requestResult
takes into account process-death scenarios, and keeps track of
the pending operation using the
Activity's SavedStateRegistry
, which means calling requestResult
after a process-death, will not re-launch the activity result
caller, and instead, it will only register the callback to allow receiving the result. And to make
this work as expected, the application need to keep the screen's state across this process-death, to
call requestResult
afterwards, check
the example app for
how we can implement this
using SavedStateHandle
.