Recently I am learning how to use Jetpack and Kotlin. Compared with onActivityResult, Androidx-activity 1.2.0-Alpha02 and Fragment 1.3.0-Alpha02 add API ActivityResultContract

Environment configuration

To use ActivityResultContract, we need to add dependencies to the Gradle file, and here I’m using version Alpha03

implementation "Androidx. Activity: activity - KTX: 1.2.0 - alpha03"
implementation 'androidx. Fragments: fragments - KTX: 1.3.0 - alpha03'
Copy the code

Method of use

ActivityResultContract and fragments can be registerForActivityResult () function creates the launcher, Then through a call to the launcher. The launch (intent) to use Because of version or other force majeure, I found in the use process registerForActivityResult () do not use, access to information found that RegisterForActivityResult () is prepareCall rename (), so can only temporarily use prepareCall ()


Read the pictures

Set up the launcher

private val launcher = prepareCall(ActivityResultContracts.GetContent()) { uri ->
       Toast.makeText(context,"uri:$uri",Toast.LENGTH_SHORT).show()
   }
Copy the code

The launcher calls to launch

launcher.launch("image/*")
Copy the code

RequestPermission

The premise

To obtain permissions dynamically, fill in the corresponding statement in the AndroidManifest, for example, WRITE_EXTERNAL_STORAGE

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Copy the code

Set up the launcher

    val requestPermissionLauncher =
        prepareCall(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                Toast.makeText(context, "result: granted", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(context, "result:fail", Toast.LENGTH_LONG).show()
            }
        }
Copy the code

The launcher calls to launch

requestPermissionLauncher.launch(WRITE_EXTERNAL_STORAGE)
Copy the code

conclusion

I spent the afternoon looking at the permissions for Jetpack. Write an article about the holes you’ve stomped on. It’s true that using Jetpack makes your code a lot cleaner