StartActivityForResult is deprecated from Activity 1.2.0-Alpha02 and Fragment 1.3.0-alpha02 on AndroidX, because there is a new method.
Create a new contract class of your own, ActivityResultContract, that inherits from ActivityResultContract and writes the parameters you pass in and the results you return.
class PersonalActivityResultContract : ActivityResultContract<String, UserInfo?>() {
override fun createIntent(context: Context, input: String): Intent {
val intent = Intent(context, HeaderPreviewActivity::class.java)
intent.putExtra("url", input)
return intent
}
override fun parseResult(resultCode: Int, intent: Intent?).: UserInfo? {
if (resultCode == Activity.RESULT_OK) {
if(intent? .hasExtra("userInfo") = =true) {
if (intent.getSerializableExtra("userInfo") != null) {
return intent.getSerializableExtra("userInfo") as UserInfo
}
}
}
return null}}Copy the code
Then use in fragments or the activity’s onCreate registerForActivityResult mActivityResultLauncher register, it is important to note that Fragments and fragments must be executed before onCreate, and activities must be executed before onStart.
private var mActivityResultLauncher: ActivityResultLauncher<String>? = null
override fun onCreate(savedInstanceState: Bundle?). {
mActivityResultLauncher = registerForActivityResult(PersonalActivityResultContract()) {
if(it ! =null) {
// Your own logic to deal with}}super.onCreate(savedInstanceState)
}
Copy the code
And then at the place you want to call it
mActivityResultLauncher? .launch("")
Copy the code
That will do. One benefit of this is better encapsulation, no need to write a lot of onActivityResult code, and easy decoupling and reuse. Of course, I just omit the startActivityForResult and onActivityResult. The rest is the same.
This is basically enough, but you can also define your own routes by implementing your own ActivityResultRegistry. Of course, you can also pass in your own ActivityOptionsCompat at launch.
If startActivityForResult is not required, use the original startActivity.
Reference links: developer. The android. Google. Cn/training/ba…