In terms of onActivityResult, we are already familiar with starting ACTIVITY B in Activity A and passing in data to ACTIVITY B, and then receiving data from B in ACTIVITY A via onActivityResult. In the latest activity-KTX beta, Google has scrapped onActivityResult.
@SuppressWarnings("deprecation")
@Override
@CallSuper
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
mFragments.noteStateNotSaved();
super.onActivityResult(requestCode, resultCode, data);
}
Copy the code
Use of the Activity Results API
In the latest beta, Google recommends using the Activity Results API to handle page data processing. With the new Activity Result API, we can handle Result callbacks in a separate class, truly a single responsibility.
1. Add dependencies to build.gradle in app:
Implementation 'androidx. Activity: activity - KTX: 1.2.0 - beta01' implementation 'androidx. Fragments: fragments - KTX: 1.3.0 - beta01'Copy the code
2. Customize ActivityResultContract
Custom ActivityResultContract to handle data transfer between two activities. Instead of the onActivityResult method, where ActivityResultContract<String, String> the first generic parameter represents the input parameter type, the data type to be carried to the next Activity, and the second generic parameter represents the output parameter type, That is, the second Activity returns the data type of the first Activity.
class CustomActivityResultContract : ActivityResultContract<String, String>() { override fun createIntent(context: Context, input: String?) Intent {// Data to be transmitted to the next activity, from A activity to B activity. return Intent(context, SecondActivity::class.java).putExtra("name", input) } override fun parseResult(resultCode: Int, intent: Intent?) : String {// Data sent back from the activity val result = intent? .getStringExtra("result") // Data returned from B activity. if (resultCode == Activity.RESULT_OK && result ! = null) { return "$result" } return "" } }Copy the code
3. Register the ActivityResult protocol
Registered in A activity ActivityResult agreement, use CustomActivityResultContract we just defined. RegisterForActivityResult method has two parameters, the first parameter is introduced to the corresponding Contract, the second parameter is the callback results callback.
Private val activityLauncher = registerForActivityResult (CustomActivityResultContract ()) {/ / the second page is turned off back to the first page of the callback methods tvName.text = it }Copy the code
4. Invoke the launch method to jump to the interface
Launch the interface jump using the launch method of the launcher object we generated in step 3. The launch method takes an input parameter that needs to be carried to the next page, which can be any object:
BtnStartSecond. SetOnClickListener {/ / click to jump to SecondActivity activityLauncher. Launch (" I passed is the first page parameters ")}Copy the code
5. Use Google’s built-in ActivityResultContract to jump to pages
You can also call Google’s built-in Contract for us with the ActivityResultContracts class, which contains various commonly used contracts
- StartActivityForResult: a generic Contract that does no conversion, with the Intent as the input and ActivityResult as the output. This is the most common Contract.
- @ RequestMultiplePermissions: used to request a set of permissions
- @requestPermission: Used to request a single permission
- TakePicturePreview: Call mediastore. ACTION_IMAGE_CAPTURE to take a picture and return a Bitmap image
- @takepicture: Call mediastore.action_image_capture to take a photo and save the image to the given Uri address. Return true if the photo was saved successfully.
- @takeVideo: Call mediastore.action_video_capture to capture the video, save it to the given Uri address, and return a thumbnail image.
- PickContact: Get the contact from the contacts APP
- @getcontent: prompts you to select a piece of content and returns a Uri address (content:// form) that accesses native data via ContentResolver#openInputStream(Uri). By default, it adds Intent#CATEGORY_OPENABLE, which returns the content that can represent the stream.
- @createDocument: Prompts the user to select a document and returns a Uri starting with file:/ HTTP :/content:.
- OpenMultipleDocuments: Prompts the user to select documents (you can select multiple documents) and returns their URIs as a List.
- OpenDocumentTree: Prompts the user to select a directory and returns the one the user chooses as a Uri. The application can fully manage the documents in the returned directory.
In general, StartActivityForResult will do most of the job.
private val activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == RESULT_OK) { val result = intent? TvName getStringExtra (" result "). The text = the result.}} btnStartSecond setOnClickListener {/ / click to jump to SecondActivity val intent = Intent(this, SecondActivity::class.java) intent.putExtra("name", "I passed is the first page parameters") activityResultLauncher. Launch (intent)}Copy the code
Using the built-in ActivityResultContract makes it easy to transfer values between pages, which can also be decouple.