For Kotlin in Android::
override fun onBackPressed() {
confirmToCancel()
}
private fun confirmToCancel() {
AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you want to cancel?")
.setCancelable(false)
.setPositiveButton("Yes") {
dialog: DialogInterface, _: Int ->
dialog.dismiss()
// for sending data to previous activity use
// setResult(response code, data)
finish()
}
.setNegativeButton("No") {
dialog: DialogInterface, _: Int ->
dialog.dismiss()
}
.show()
}