I am working on app that capture video from screen. previously I was use the startActivityForResult method to send intent for permission dialog. But now is deprecated. It is the old code:
mProjectionManager?.createScreenCaptureIntent()
?.let { startActivityForResult(it, REQUEST_CODE) };
Now developer.android give this code for alternative of it:
mProjectionManager = getSystemService(MediaProjectionManager::class.java)
val startMediaProjection = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
mMediaProjection = mProjectionManager?.getMediaProjection(result.resultCode, result.data!!)
}
}
startMediaProjection.launch(mProjectionManager?.createScreenCaptureIntent())
Although the old code is working good but the new code has this error:
java.lang.illegalStateException: lifecycleOwner com.cafedabestan.whateboard.MyActivity@beb74c9 is attemping to register while current state is RESUMED. lifecycleOwners must call register before they are started.
I put this code the same place of old code. error is causing by try catch
As per the [Get a result from an activity documentation:
When starting an activity for a result, it is possible—and, in cases of memory-intensive operations such as camera usage, almost certain—that your process and your activity will be destroyed due to low memory.
For this reason, the Activity Result APIs decouple the result callback from the place in your code where you launch the other activity.Because the result callback needs to be available when your process and activity are recreated, the callback must be unconditionally registered every time your activity is created, even if the logic of launching the other activity only happens based on user input or other business logic.
So you need to call registerForActivityResult
unconditionally as part of the creation of your Activity / Fragment (whatever the it
is in your code), then call only launch
when you actually want to trigger it.