Follow my official account “Ananzhuo” to learn more

What is ActivityResultContract

Simply put, ActivityResultContract is the official API used to replace startActivityForResult and onActivityResult in most scenarios.

ActivityResultContract provides a type-safe way to get a return value, such as a generically specified Bitmap from an API that takes a photo. This prevents us from having to handle the onActivityResult callback manually.

Of course, I think the best part of ActivityResultContract is worry free, especially for the centralized ActivityResultContract preset by the system, only two steps of template code can realize the function.

Customize an ActivityResultContract

To implement custom behavior you need to define an ActivityResultContract class as follows:

  1. Integrated ActivityResultContract class

There are two generics in the ActivityResultContract class. The first one is I, and the second one is O. I represents the input, which is what we need to putExtra to launch the activity, and O represents the input, which is the data returned by onActivityResult

ActivityResultContract has two methods

  • createIntentCreate startactivitytheIntent, where the second parameter of the method can be passed to be startedactivityThe parameters of the
  • parseResultRepresents the parsing of the returned data. The return value of the method isregisterForActivityResultThe data that is called in the
class CustomResultContracts : ActivityResultContract<Int, String>() {
    override fun createIntent(context: Context, input: Int?).: Intent {
        return Intent(context, DestinishActivity::class.java).putExtra("input",input)
    }

    override fun parseResult(resultCode: Int, intent: Intent?).: String {
        returnintent? .getStringExtra("data") ?: "No data returned"}}Copy the code
  1. Register to monitor
 private val customContract = registerForActivityResult(CustomResultContracts()){
        getData(14).content="Custom Contracts returns data:$it"
        getData(14).notifyDataSetChange()
    }
Copy the code
  1. Start the activity
customContract.launch(1)
Copy the code

Officially provided preset ActivityResultContract

StartActivityForResult Starts an activity and returns a result

This example calls a method that starts an activity, and the new activity clicks return data to return the data to the list for display

  1. code

Registration code

// Register result listening
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == 3) {
                showResult(it.data? .getStringExtra("data"))}}Copy the code

Startup code

// Start the activity with intent
startForResult.launch(Intent(this@MainActivity, DestinishActivity::class.java))
Copy the code
  1. The effect

TakePicturePreview jumps to the photo taking page

Jump to the Photo page, and the photos taken will be saved to the gallery

  1. code
    registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
            getData(1).let {
                it.notifyDataSetChange()
            }
        }
Copy the code

The simulator recording remains unchanged, and there is no effect picture yet

TakePicture photo preview

The TakePicture method jumps to the system camera and takes a picture, returning the Bitmap, but does not save the picture to the gallery

  1. code
private val takePreviewPic = registerForActivityResult(ActivityResultContracts.TakePicture()) {
        logEE("Successful preview.")}Copy the code

CaptureVideo Videos

In the shooting code, it should be noted that it will take a long time to wait for the mobile phone to finish processing the video storage after the video is shot

 private val captureVideo = registerForActivityResult(ActivityResultContracts.CaptureVideo()) {
        logEE("Successful video shooting:$it")}Copy the code

The simulator recording remains unchanged, and there is no effect picture yet

RequestPermission RequestPermission

Very concise way to achieve permission application

  1. Application permission code
cameraPermission.launch(Manifest.permission.CAMERA)
Copy the code
  1. Register for permission monitoring
private val cameraPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            getData(3).apply {
                content = "Request camera permissions result$it"
                notifyDataSetChange()
            }
        }
Copy the code
  1. The effect

More than RequestMultiplePermissions request permissions

  1. Call request multiple permission code
mutlePermission.launch(
                    arrayOf(
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                )
Copy the code
  1. Register code for multiple permissions
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { var result = "" it.forEach { gaint -> ${if (gaint. Value) "success" else "failure "}"} getData(4).content = result +=" obtain ${gaint getData(4).notifyDataSetChange() }Copy the code
  1. The effect

PickContact Gets the contact

  1. Request to open the contact selection page
pickContact.launch(null)// Pass null parameters
Copy the code
  1. Listen for contact results
private val pickContact = registerForActivityResult(ActivityResultContracts.PickContact()) {
        logEE(it.toString())
        getData(8).apply {
            content = it.toString()
            notifyDataSetChange()
        }
    }
Copy the code
  1. Implementation effect

GetContent Opens the file browser

Realize the use of file browser to select pictures

  1. Open the file browser
getContent.launch("image/*")
Copy the code
  1. Processing return result
 private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) {
        logEE(it.toString())
    }
Copy the code
  1. Implementation effect

Because the simulator has no images to choose from, there is no content to display