Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startActivityForResult(android.content.Intent, int)' is deprecated

Tags:

android

kotlin

startActivityForResult(intent,3021) 

I am using this since long time, is this method is deprecated now?

like image 299
ice spirit Avatar asked Aug 16 '20 10:08

ice spirit


People also ask

Is startActivityForResult deprecated?

onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.

What is the replacement of startActivityForResult?

But recently startActivityForResult() method is deprecated in AndroidX. Android came up with ActivityResultCallback (also called Activity Results API) as an alternative for it.

What is startActivityForResult in Android?

By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).

What is registerForActivityResult?

registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you'll use to launch the other activity. An ActivityResultContract defines the input type needed to produce a result along with the output type of the result.


Video Answer


1 Answers

It is indeed deprecated. I tried to figure the new way out and thought I want to share it here.

Now instead of overriding onActivityResult for all callbacks and checking for our request code, we can register for each call back separately by using registerForActivityResult which takes in an ActivityResultContracts. IMO this is a way better approach than the previous way.

Here is an example of starting an activity for a result:

val previewRequest =
           registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    if (it.resultCode == RESULT_OK) {
        val list = it.data
        // do whatever with the data in the callback
    }
}

Now instead of StartActivityForResult we use

val intent = Intent(this, PreviewFullscreenActivity::class.java)
intent.putStringArrayListExtra(AppConstants.PARAMS.IMAGE_URIS, list)
previewRequest.launch(intent)
like image 120
hushed_voice Avatar answered Oct 17 '22 03:10

hushed_voice