- Result 를 얻기 위해 Activity 을 시작할 때, 메모리 부족으로 인해 프로세스와 활동이 소멸될 수 있습니다.
What
Activity Result API
다른 Activity 을 실행하는 Code 위치에서Result Callback 분리
Result Callback 은 Process 와 Actvity 을 다시 생성할 때, 사용할 수 있어야 하므로 다른 Activity 을 실행하는 로직이 사용자 입력 또는 비즈니스 로직을 기반으로 발생하더라도 Activity 이 생성될 때마다 Callback 을 무조건 등록해야 함.
- 사진 촬영, 권한 요청 등과 같은 기본 인텐트 작업의 *1 Default Contacts을 제공 ( CaptureVideo, CreasteDocument ... )
- custom constract 정의할 수도 있다.
ActivityResultLauncher
다른 Activity 을 실행하거나 Result 요청 작업
GetContent.launch( I input )
Result 를 생성하는 프로세스가 시작.
- ActivityResultContract 유형과 일치하느입력을 가져옴
1. Result 을 위한 Activity 실행
val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
// Handle the returned Uri
// 2. Result Callback
}
override fun onCreate(savedInstanceState: Bundle?) {
// ...
val selectButton = findViewById<Button>(R.id.select_button)
selectButton.setOnClickListener {
// Pass in the mime type you'd like to allow the user to select
// as the input
getContent.launch("image/*") // 1. Result 결과를 생성하는 프로세스가 시작.
}
}
class MyLifecycleObserver(private val registry : ActivityResultRegistry)
: DefaultLifecycleObserver {
lateinit var getContent : ActivityResultLauncher<String>
override fun onCreate(owner: LifecycleOwner) {
getContent = registry.register("key", owner, GetContent()) { uri ->
// Handle the returned Uri
}
}
fun selectImage() {
getContent.launch("image/*")
}
}
class MyFragment : Fragment() {
lateinit var observer : MyLifecycleObserver
override fun onCreate(savedInstanceState: Bundle?) {
// ...
observer = MyLifecycleObserver(requireActivity().activityResultRegistry)
lifecycle.addObserver(observer)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val selectButton = view.findViewById<Button>(R.id.select_button)
selectButton.setOnClickListener {
// Open the activity to select an image
observer.selectImage()
}
}
}