728x90
[1] Intent(Activity - Launcher)
- 어제 했던 intent 사용 방식은 최신 버전에서는 사용하지 않는 방식
1. Intent의 달라진 부분
1) ActivityResultLauncher객체 생성
2) ActivityResultLauncher객체 내부에서 registerForActivityResult를 생성하며 실행할 코드를 작성
=> 액티비티를 실행하고 되돌아올 때 콜백이 실행되도록 설정
- registerForActivityResult 함수를 이용해서 작업
- registerForActivityResult 함수의 매개변수로 ActivityResultContracts 객체의 Static 함수들을 명시
[ActivityResultContracts종류]
- StartActivityForResult( ) : 요청한 인텐트를 통해서 액티비티를 실행하고 액티비티 실행한 후 결과를 다시 받아서 처리하는 경우
- GetContent( ) : 사용자가 ContentProvider를 작업하며 선택한 콘텐트의 Uri를 반환하는 경우
- TakePicture( ) : 사진촬영 후 지정 경로에 저장하고 Bitmap을 반환하는 경우
................... 외 다양한 Static 함수들이 있다.
- 구버전에서 onActivityResult에 정의하던 작업을 콜백메소드 안에 정의한다.
3) ActivityResultLauncher객체의 launch 메소드를 이용하여 인텐트 의뢰
2. Launcher 사용 예제
- activity 파일은 upgradeversion이라는 패키지에 별도로 담았음
1) 메인 화면
first2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/intent_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="첫 번째 액티비티"/>
<Button
android:text="기본 액티비티 호출"
android:id="@+id/call1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="result Value 액티비티 호출1"
android:id="@+id/call2"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="result Value 액티비티 호출2"
android:id="@+id/call3"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="종료"
android:id="@+id/btnExit"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
LauncherFirstActivity.kt
package com.example.intent.upgradeversion
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.example.intent.R
import kotlinx.android.synthetic.main.first2.*
class LauncherFirstActivity : AppCompatActivity(), View.OnClickListener {
// lateinit를 객체를 정의하면서 초기화하지 않고, 뒤에서 초기화할 때 사용한느 키워드, var로 선언된 경우에만 가능
// 1. ActivityResultLauncher 객체를 정의
private lateinit var resultLauncher1:ActivityResultLauncher<Intent>
private lateinit var resultLauncher2:ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.first2)
call1.setOnClickListener(this)
call2.setOnClickListener(this)
call3.setOnClickListener(this)
btnExit.setOnClickListener(this)
// 인텐트에 명시한 액티비티를 실행하고 되돌아오는 경우 자동으로 호출된다.
resultLauncher1 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result->
// result 매개변수 - onActivityResult 메소드의 매개변수로 전달되던 모든 값들을 가지고 있다.
if(result.resultCode == Activity.RESULT_OK){
intent_info.text = result.data?.getStringExtra("second")
}
}
resultLauncher2 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result->
// result 매개변수 - onActivityResult 메소드의 매개변수로 전달되던 모든 값들을 가지고 있다.
if(result.resultCode == Activity.RESULT_OK){
Toast.makeText(this, result.data?.getStringExtra("second"), Toast.LENGTH_LONG).show()
}
}
}
override fun onClick(v: View?) {
when(v?.id){
R.id.btnExit -> finish()
R.id.call1 -> {
val intent = Intent(this, LauncherSecondActivity::class.java).apply{
putExtra("info", "첫 번째 액티비티가 넘기는 메시지")
}
startActivity(intent) // 실행되는 액티비티가 넘겨주는 데이터를 가지고 올 수 없다. 오직 액티비티를 실행할 목적
}
R.id.call2 -> {
val intent = Intent(this, LauncherSecondActivity::class.java).apply{
putExtra("code", "call2")
putExtra("data", "첫 번째 액티비티가 넘기는 메시지-call2")
}
resultLauncher1.launch(intent)
}
R.id.call3 -> {
val intent = Intent(this, LauncherSecondActivity::class.java).apply{
putExtra("code", "call3")
putExtra("data", "첫 번째 액티비티가 넘기는 메시지-call3")
}
resultLauncher2.launch(intent)
}
}
}
}
2) 두 번째 화면
second2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/secondTxt"
android:text="호출된 액티비티"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="액티비티 닫기"
android:id="@+id/btnClose1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
LauncherSecondActivity.kt
package com.example.intent.upgradeversion
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.intent.R
import kotlinx.android.synthetic.main.second2.*
class LauncherSecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second2)
val intent = intent
val code = intent.getStringExtra("code")
val data = intent.getStringExtra("data")
btnClose1.setOnClickListener {
secondTxt.text = data
// intent.putExtra("second", "두 번째 액티비티에서 실행완료")
when(code){
"call2" -> {
intent.putExtra("second", "첫 번째 액티비티 두 번째 버튼:$code - $data")
}
"call3" -> {
intent.putExtra("second", "첫 번째 액티비티 세 번째 버튼:$code - $data")
}
}
// ReturnDataSecondActivity를 호출했던 ReturnDataFirstActivity로 되돌아갈 때, 값을 공유하기 위해서 intent 객체를 다시 넘긴다. - setResult 메소드를 이용해서 처리하기
// Activity.RESULT_OK 는 정상 완료라는 의미를 담은 액티비티의 상수
setResult(Activity.RESULT_OK, intent)
finish()
}
}
}
- 끝 -
728x90
'프로젝트형 IoT 서비스 개발 4회차 > 3. 게이트웨이 디바이스 제어' 카테고리의 다른 글
[Day72] 2022-05-09(월) Android11 - Fragment2 - 김서연 강사님 (0) | 2022.05.09 |
---|---|
[Day71] 2022-05-07(토) Android10 - Fragment1 - 김서연 강사님 (0) | 2022.05.09 |
[Day70] 2022-05-06(금) Android8 - Intent1(Activity1) - 김서연 강사님 (0) | 2022.05.06 |
[Day70] 2022-05-06(금) Android7 - MQTT 통신(Subscribe) - 김서연 강사님 (0) | 2022.05.06 |
[Day69] 2022-05-04(수) Android6 - MQTT 통신(세팅, Publish) - 김서연 강사님 (0) | 2022.05.04 |