[Android] Error from registerForActivityResult()

boogi-woogi·2023년 4월 30일
0
post-thumbnail

Fragment에서의 registerForActivityResult() 호출 시점

class SettingFragment : Fragment() {
	...
    private val permissionLauncher: ActivityResultLauncher<String> by lazy {
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            	if (isGranted) {
                	allowedCase()
            	} else {
                	deniedCase()
            	}
        	}
    	)
    }
	...
}

Fragment에서 ActivityResultLauncherlazy를 이용해 늦은 초기화를 수행하는 코드를 작성했다. 변수 permissionLauncherresume상태에서 초기화가 이루어지는 로직을 가지고 있었고 예상하지 못한 오류가 발생했다.

ERROR : is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).


registerForActivityResult()created되기 전에 호출해야하는 이유?

the result callback needs to be available when your process and activity are recreated, the callback must be unconditionally registered every time your activity is created, even if the logic of launching the other activity only happens based on user input or other business logic.

Note: You must call registerForActivityResult() before the fragment or activity is created, but you can't launch the ActivityResultLauncher until the fragment or activity's Lifecycle has reached CREATED.

공식 문서에 따르면 result callbackActivity가 재생성된 이후에도 사용할 수 있어야 하고, Activitycreated되는 시점, 심지어 Activitylaunching하는 로직이 어떤 특정 비즈니스 로직에 의해서만 일어나도 callback은 무조건 등록이 되어있어야 한다.

result callback이 무조건적으로 등록되어 있다는 사실로써 activitylaunching되는 어떠한 경우에서도 result callback에 의해 결과를 처리하는 것에 문제가 없다는 보장하는 것이 아닐까 생각한다.

참고: https://developer.android.com/training/basics/intents/result

profile
https://github.com/boogi-woogi

0개의 댓글