본문 바로가기
Android Studio

[Android, Kotlin] 앱 강제종료시 Notification없애기(Service)

by 열정적인 이찬형 2022. 10. 2.

타이머를 진행중에 Notification을 띄운 후 타이머가 종료되면 없어지도록 하였습니다.

 

하지만 앱을 강제종료를 시킬 때 Notification이 사라지지 않아서 onDestory()에서 Notifiaction을 없어지도록 설정하였지만 Notification이 없어지지 않는 현상을 겪게 되었습니다.

 

정보를 찾아보고 해결한 방법을 정리하였습니다.


Service

Android Develops에서 Service를 살펴보면

 

Service  |  Android Developers

android.net.wifi.hotspot2.omadm

developer.android.com

 

A facility for the application to tell the system about something it wants to be doing in the background 

 

(백그라운드에서 수행하려는 작업에 대해 시스템에 알려주는 응용 프로그램 기능)

 

The service will at this point continue running until Context.stopService() or stopSelf() is called.

(서비스는 Context.stopService() 또는 stopSelf()가 호출될 때까지 계속 실행됩니다.)

 

services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

(서비스는 stopSelf(int) 메서드를 사용하여 시작 의도가 처리될 때까지 서비스가 중지되지 않도록 할 수 있습니다.)

 

onTaskRemoved에 설명에는

This is called if the service is currently running and the user has removed a task that comes from the service's application.

(서비스가 현재 실행 중이고 사용자가 서비스 응용 프로그램에서 가져온 작업을 제거한 경우 호출됩니다.)

 

요약

 

Service를 이용하여 강제종료되는 것을 감지하는 것이 가능합니다

감지한 뒤 어플에 onDestory()가 처리되고 종료되도록 할 것입니다.


사용법

 

Service를 구현한 뒤에 AndroidManifest에 추가 해주셔야 합니다.

 

Service

import android.app.Service
import android.content.Intent
import android.os.IBinder

class ForcedTerminationService : Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        stopSelf()		//Service도 종료
    }
}

 

AndroidManifest

<application
	....
    <service android:name=".service.ForcedTerminationService"
     		android:stopWithTask="false"/>
    //stopWithTask = false를 진행하여 백그라운드에서 종료되었을 때
    //Activity 종료되고 서비스는 onTaskRemoved()가 호출됩니다.
    ....
/>

 

Service는 중첩되기 시작하지 않아도 되기 때문에 실행되는 첫 Activity에서 실행시키면 됩니다.

import ....

class SplashActivity : AppCompatActivity() {
	....
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ....
        //App을 실행하였을 때 SplashActivity 실행되도록 설정해서
        //SplashActivity에서 Service를 실행하였습니다.
        startService(Intent(this, ForcedTerminationService::class.java))
        ....
    }
}

Notification을 띄우는 Activity

import ...

class DetailActivity : AppCompatActivity() {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
    }

    //종료되어 onDestroy()가 실행되어 현재 열려있는 Notifitication이 모두 종료되도록 합니다.
    override fun onDestroy() {
        super.onDestroy()
        NotificationManagerCompat.from(this).cancelAll()
    }
    ...
}

 

더 좋은 방법이 존재한다면 댓글로 남겨주시면 감사하겠습니다.

댓글