문제 상황

Foreground Service로 실행 중 Hilt Singletone Component로 선언한, 특정 클래스가 Service 에서 StopSelf를 호출하여도 클래스가 Service 생명주기의 onDestroy이후에도 Destory되지 않고, 살아있는 것을 발견 하였습니다.

 

Hilt - Singleton Component

  • SingletonComponent는 Application-OnCreate에 시작되어서 OnDestory에서 종료됨
  • Android Application은 foreground실행을 했을 경우에 Process가 언제 종료되는지 정확한 시점을 알 수 없음.
  • Foreground Service를 실행했을 때에는 Application 의 process는 어딘가에서 캐싱되어 핸드폰 리소스가 부족해 질때까지 살아있을 수 있다. 이와 관련된 부분은 아래 공식 문서 부분을 참고
  • 즉, SingletonComponent 스코프의 컴포넌트들은 죽지 않는 상태로 Process가 죽을때까지 계속 존재하게됨.
  • android 공식문서 Process Lifecycle에 관련된 부분
  • The Android system will attempt to keep the process hosting a service around as long as the service has been started or has clients bound to it. When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the higher of the following possibilities:
  • If the service is currently executing code in its onCreate()onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.

링크 process Lifecycle

 

ADB로 확인하기

현재 process가 살아있는지 확인하기 위해서

adb shell pidof com.google.android.youtube

위와 같은 adb 명령어를 실행해 줍니다. (com.google.android.youtube 대신 자신의 패키지명을 넣어주세요)

명령어 결과

13528 처럼 현재 pid가 출력됩니다. Hilt SingletonComponent를 Foreground Service에서 사용하면서 Foreground Service가 죽었는지 확인해보기 위해 위와 같이 해보았습니다 (Service를 새로운 process에서 실행시키지 않을때만 유효할것으로 판단됩니다)

 

Singleton Component는 그럼 memory leak을 일으킬까?

  • 아마 충분히 가능성이 있다고 생각합니다. Foreground Serivce에 주입하는 Hilt Component들은 service lifecycle에 맞게 클래스의 생명주기를 설정해주어야 합니다. (예를 들어 변수에 Null을 대입한다거나 WeakReference를 사용하는 것과 같은 방법이 존재할것 입니다.)
  • 그렇기에 Hilt의 Singleton Component는 foreground service에서 사용할때 주의해야 합니다.
728x90
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기