// intent 객체 생성
val secondIntent = Intent(this@MainActivity, SecondActivity::class.java)
val resultIntent = Intent()
startActivity(secondIntent)
setResult(RESULT_OK)
setResult(RESULT_OK, secondIntent)
finish()
// requestCode 설정
val SECOND_ACTIVITY = 0
startActivityForResult(secondIntent,SECOND_ACTIVITY)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
SECOND_ACTIVITY -> {
activityMainBinding.textView.text = "SecondActivity 실행 후 복귀"
when(resultCode){
RESULT_OK -> {
activityMainBinding.textView.append("작업 성공")
}
RESULT_CANCELED -> {
activityMainBinding.textView.append("작업 취소")
}
}
}
THIRD_ACTIVITY -> {
activityMainBinding.textView.text = "ThirdActivity 실행 후 복귀"
}
}
}
val c1 = ActivityResultContracts.StartActivityForResult()
val secondActivityLauncher = registerForActivityResult(c1){
if(it.resultCode == RESULT_OK){
val data1 = it.data?.getIntExtra("data1", 0)
val data2 = it.data?.getDoubleExtra("data2", 0.0)
}
}
}
activityMainBinding.run {
button.run {
val secondIntent = Intent(this@MainActivity, SecondActivity::class.java)
secondIntent.putExtra("data1", 100)
secondIntent.putExtra("data2", 11.11)
secondActivityLauncher.launch(fourthIntent)
}
}
val secondIntent = Intent(this@MainActivity,SecondActivity::class.java)
secondIntent.putExtra("data1", 100)
secondIntent.putExtra("data2", 11.11)
secondIntent.putExtra("data3", true)
secondIntent.putExtra("data4", "데이터")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(data != null){
val data1 = data.getIntExtra("data1", 0)
val data2 = data.getDoubleExtra("data2", 0.0)
val data3 = data.getBooleanExtra("data3", false)
val data4 = data.getStringExtra("data4")
activityMainBinding.run {
textView.append("${data1}")
textView.append("${data2}")
textView.append("${data3}")
textView.append("${data4}")
}
}
}
객채의 값을 parcel에 객체 이용하여 intent에 저장한 후 사용 → 객체 자체를 intent에 저장 X
* parcel에 객체의 값 저장 → intent에 저장 → 객체 생성 후 값 저장 (저장된 parcel 객체 값 추출)
서로 다른 4대 구성요소에 객체를 전달하기 위한 객체 직렬화 수행
class TestClass() : Parcelable {
lateinit var name:String
lateinit var age:Int
constructor(parcel: Parcel) : this() {
name = parcel.readString()!!
age = parcel.readInt()!!
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeInt(age)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<TestClass> {
override fun createFromParcel(parcel: Parcel): TestClass {
return TestClass(parcel)
}
override fun newArray(size: Int): Array<TestClass?> {
return arrayOfNulls(size)
}
}
}
val t1 = TestClass()
t1.name = "pujin"
t1.age = 100
secondIntent.putExtra("data1", t1)
val data1 = intent.getParcelableExtra<TestClass>("data1")
textView.append("name : ${data1?.name}")
textView.append("age : ${data1?.age}")