본문 바로가기
Android

[Doit 깡샘의 안드로이드 앱 프로그래밍 with 코틀린] 정리 13 - 액티비티 화면 되돌리기 ― ActivityResultLauncher

by 들풀민들레 2022. 2. 28.
본 글은 [Doit 깡샘의 안드로이드 앱 프로그래밍 with 코틀린 - 이지스퍼블리싱 (2022)] 의 내용을 발췌한 것입니다.

좀더 자세한 내용은 책 혹은 인강을 통해 확인해 주세요.

 

 

 

 

이번에는 최근 권장하는 방식을 살펴보겠습니다. 인텐트를 발생시켜 화면을 전환한 후 되돌아왔을 때 ActivityResultLauncher로 사후 처리하는 방법입니다. ActivityResultLauncher 는 이밖에도 액티비티에서 다양한 결과에 대한 사후 처리를 제공합니다.

 

Contract


ActivityResultLauncher를 이용하려면 먼저 Contract 객체가 필요합니다. Contract는 Activity ResultLauncher로 실행될 요청을 처리하는 역할을 합니다. 즉, ActivityResultLauncher로 인텐트를 발생시켜 액비티비를 실행할 때 실제 인텐트를 발생시키는 역할을 합니다. 만약 퍼미션 조정 요청을 할 때는 실제 퍼미션 조정 다이얼로그를 띄우는 역할을 합니다.
Contract는 ActivityResultContract를 상속받은 서브 클래스이며 직접 만들거나 API에서 제공하는 클래스를 이용해도 됩니다. 대표적인 Contract는 다음과 같습니다.


•PickContact: 선택한 연락처의 Uri 획득
•RequestPermission: 권한 요청, 허락 여부 파악
•RequestMultiplePermissions: 여러 권한을 동시에 요청
•StartActivityForResult: 인텐트 발생, 액티비티 실행 결과 획득
•TakePicturePreview: 사진 촬영 후 비트맵 획득
•TakePicture: 사진 촬영, 저장, 비트맵 획득


ActivityResultLauncher


ActivityResultLauncher는 registerForActivityResult() 함수로 만드는 객체이며 함수의 매개변수에 실제 작업자인 Contract 객체와 결과를 처리하는 Callback 객체를 등록해 줍니다.


launch


ActivityResultLauncher의 함수이며 launch 함수를 호출하는 순간 ActivityResult Launcher에 등록된 Contract 객체가 실행됩니다.

 

지금까지 설명한 내용을 바탕으로 실제 인텐트를 발생시켜 액티비티를 실행하고 결과를 처리하는 방법을 살펴보겠습니다.

 

val requestLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult())
    {
        val resultData = it.data?.getStringExtra("result")
        binding.mainResultView.text = "result : $resultData"
	}

ActivityResultLauncher를 이용하려면 먼저 registerForActivityResult() 함수로 ActivityResultLauncher 객체를 만들어야 합니다. registerForActivityResult() 함수에는 Contract와 Callback 객체를 등록해야 하며 여기서는 인텐트를 발생시키는 StartActivity ForResult 객체를 사용했습니다.
이렇게 만든 ActivityResultLauncher 객체를 launch() 함수로 실행해 주면 됩니다.

 

val intent: Intent = Intent(this, DetailActivity::class.java)
requestLauncher.launch(intent)