SharedPreference는 onDestroy()에서 작동하지 않는다.

지프치프·2022년 3월 21일
0

Android

목록 보기
47/85
post-thumbnail

“Android 로봇은 Google에서 제작하여 공유한 저작물을 복제하거나 수정한 것으로 Creative Commons 3.0 저작자 표시 라이선스의 약관에 따라 사용되었습니다.”


개인 프로젝트를 만들고 있던 도중
앱이 종료되면 현재의 상태를 SharedPreference에 저장하고
앱이 실행되면 저장된 값에 따라 일련의 처리를 하도록 만들고 있는데
종료될 때 저장이 안된다 (..)

    override fun onDestroy() {
        super.onDestroy()
        Pref.getInstance(this)?.setValue(Pref.RESUME, binding.wvWebView.url.toString())
    }

처음에 이렇게 코드를 작성했었는데
별 짓을 다해봐도 저장이 안되는 거 같았다.
그래서 Preference xml파일까지 찾아서 직접 까봤더니
진짜 저장이 안되고 있었다.
염병..

스택오버플로우에 나와 똑같은 상황인 글이 있길래 참고했다.
답변은 이러했다.

As per the docs, don't rely on the onDestroy() method to persist your data. Use onPause() instead.

onDestroy() 쓰지말고 onPause()를 쓰라고한다.
그래서 바로 바꿔주고 실행했더니 작동이 잘되는 것을 확인할 수 있었다.

스택오버플로우에서 제시한 원인은 아래와 같다.

Note: do not count on this method being called as a place for saving data!
For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running.
There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

외계어인가
대충 해석해보자면..
onDestroy()는 데이터를 저장하는 것이 아니고
리소스를 해제하기 위한 목적을 가지고 있으며
때로는 호출이 이뤄지지 않고 Activity가 종료될 수도 있기때문에
데이터를 저장을 비롯한 편집 등을 위해 사용하기엔 적합하지 않다.

결론은 SharedPreference를 비롯하여
앱 종료 전에 데이터를 다루는 작업은 onDestroy()가 아니고
onPause()에서 이루어져야한다.

개인적으로 공부했던 것을 바탕으로 작성하다보니
잘못된 정보가 있을수도 있습니다.
인지하게 되면 추후 수정하겠습니다.
피드백은 언제나 환영합니다.
읽어주셔서 감사합니다.

profile
지프처럼 거침없는 개발을 하고싶은 개발자

0개의 댓글