Skip to content

Instantly share code, notes, and snippets.

@rajendhirandev
Created September 22, 2022 13:06
Show Gist options
  • Save rajendhirandev/ed483e7aecbd873ed5450a91b1350641 to your computer and use it in GitHub Desktop.
Save rajendhirandev/ed483e7aecbd873ed5450a91b1350641 to your computer and use it in GitHub Desktop.
//Earlier Approach:
// Receiver
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE){
val dataStr = data?.getStringExtra("Value") ?:"NO Value"
println(dataStr)
}
}
// Caller
val intent = Intent(context, SecondActivity::class.java)
startActivityForResult(intent,REQUEST_CODE)
//New Approach:
//-------------------------------------- Explicit Calls ------------------------------------------------
// Receiver is lambda i.e. ActivityResultCallback
private val secondActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if(it.resultCode== Activity.RESULT_OK){
val dataStr = it.data?.getStringExtra("Value") ?:"NO Value"
println(dataStr)
}
}
//Caller
secondActivityLauncher.launch(Intent(this,SecondActivity::class.java))
//------------------------------------- Implicit Calls -------------------------------------------------
//Receivers
private val launchCamera = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
binding.ivLogo.setImageBitmap(it)
}
private val launchGallery = registerForActivityResult(ActivityResultContracts.GetContent()) {
binding.ivLogo.setImageURI(it)
}
//Caller
launchCamera.launch(null)
launchCamera.launch("image/*")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment