class SettingFragment : Fragment() {
...
private val permissionLauncher: ActivityResultLauncher<String> by lazy {
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
allowedCase()
} else {
deniedCase()
}
}
)
}
...
}
Fragment
에서 ActivityResultLauncher
를 lazy
를 이용해 늦은 초기화를 수행하는 코드를 작성했다. 변수 permissionLauncher
는 resume
상태에서 초기화가 이루어지는 로직을 가지고 있었고 예상하지 못한 오류가 발생했다.
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 callback
은 Activity
가 재생성된 이후에도 사용할 수 있어야 하고, Activity
가 created
되는 시점, 심지어 Activity
를 launching
하는 로직이 어떤 특정 비즈니스 로직에 의해서만 일어나도 callback
은 무조건 등록이 되어있어야 한다.
result callback
이 무조건적으로 등록되어 있다는 사실로써 activity
가 launching
되는 어떠한 경우에서도 result callback
에 의해 결과를 처리하는 것에 문제가 없다는 보장하는 것이 아닐까 생각한다.
참고: https://developer.android.com/training/basics/intents/result