앱 종료를 감지하는 방법 (with. onTaskRemoved)

지프치프·2023년 5월 27일
0

Android

목록 보기
67/85
post-thumbnail

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


개요

앱이 종료될 때에 맞춰 코드를 호출하고 싶을 때가 있다.
보통 onDestroy()에서 호출을 하면 되겠다고 생각했지만
이는 한계가 있다.

onDestroy의 한계

Android Developer에서는 onDestroy()가 호출되는 경우를 아래와 같이 설명하고 있다.

  1. The activity is finishing, due to the user completely dismissing the activity or due to finish() being called on the activity.
  2. The system is temporarily destroying the activity due to a configuration change, such as device rotation or entering multi-window mode.

첫번째는 finish()를 호출하여 Activity가 종료될 때
두번째는 화면 회전 같은 configuration 변화가 일어날 때이다.

앱을 뒤로가기 버튼을 통해서 종료하면 정상적으로 onDestroy()가 호출이 되겠지만 TaskList(흔히 말하는 최근 앱 목록)에서 스와이프해서 앱을 닫는 경우는 onDestroy()가 호출되지 않는다.

onTaskRemoved

이때 앱의 종료를 감지하는 방법이 있다.
Servcie에서는 onTaskRemoved()라는 콜백 함수를 제공하는데
TaskList에서 앱이 종료되면 이 함수를 호출하므로
여기서 앱의 종료 시점에서 처리해야할 코드를 작성해주면 된다.

간단한 샘플 코드를 아래와 같이 작성해보자

Service 구현

먼저 Service를 아래와 같이 구현하자

class MyService : Service() {
    private val TAG = javaClass.simpleName
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private val receiver = MyReceiver()
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand()")

        return START_STICKY
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)

        Log.e(TAG, "onTaskRemoved()")
        Log.e(TAG, "This task removed from task list!")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy()")
    }
}

그리고 Activity에서 아래와 같이 Service를 호출해주면 된다.

startService(Intent(this, MyService::class.java))

그리고 나서 실행해서 Service를 호출 한 뒤
TaskList에서 앱을 쓸어올려서 종료해보면
아래와 같이 log가 출력되는 것을 확인할 수 있다.

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

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

0개의 댓글