Q1: is it necessary to unregister this call back when the activity is going to destroy?
Ans: NO
Q2: this call back is lifeCycle aware?
Ans: Yes
Q3: When you use it ActivityResultContracts.StartActivityForResult()?
Ans: it will be used when you creating a custom contract, more info: https://developer.android.com/training/basics/intents/result#custom
Q4:What is the best approach for handling different request codes from one activity?
Ans:
Example: for one activity
->launch the second activity from the first activity:
val intent = Intent(this, SecondActivity::class.java)
startActivityForResult(intent,101)
->in the first activity you must override onActivityResult():
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
101 -> {
when (resultCode) {
Activity.RESULT_OK -> {
data!!.getStringExtra("keySecond")
}
Activity.RESULT_CANCELED -> {
//if there's no result
}
}
}
}
-> in second activity send the result back to the first activity as follow:
val intent = Intent()
intent.putExtra("keySecond","dataFromSecondActivity")
setResult(Activity.RESULT_OK,intent)
finish()
Example: for multiple activities
-> if you handling different request codes from one activity:
val intent = Intent(this, ThirdActivity::class.java)
startActivityForResult(intent,210)
-> in third activity send the result back
val intent = Intent()
intent.putExtra("keyThird","dataFromThirdActivity")
setResult(Activity.RESULT_OK,intent)
finish()
->then your onActivityResult() function in first activity should look like:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
101 -> { //result from second activity
when (resultCode) {
Activity.RESULT_OK -> {
data!!.getStringExtra("keySecond")
}
Activity.RESULT_CANCELED -> {
//if there's no result
}
}
}
210 -> { //result from third activity
when (resultCode) {
Activity.RESULT_OK -> {
data!!.getStringExtra("keyThird")
}
Activity.RESULT_CANCELED -> {
//if there's no result
}
}
}
}
}