티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to check if a service is running on Android?

안드로이드에서 서비스가 실행 중인지 확인하는 방법은?

 문제 내용 

How do I check if a background service is running?

백그라운드 서비스가 실행 중인지 확인하려면 어떻게 해야 합니까?

 

I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on.

서비스 상태를 토글하는 Android 액티비티가 필요합니다. 서비스가 꺼져 있으면 켤 수 있고 켜져 있으면 끌 수 있어야 합니다.

 

 

 

 높은 점수를 받은 Solution 

I use the following from inside an activity:

액티비티 내부에서 다음을 사용합니다.
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

 

And I call it using:

그리고 저는 그것을 다음과 같이 호출합니다:
isMyServiceRunning(MyService.class)

 

This works reliably, because it is based on the information about running services provided by the Android operating system through ActivityManager#getRunningServices.

이것은 ActivityManager#getRunningServices를 통해 안드로이드 운영 체제에서 제공하는 서비스 실행에 대한 정보를 기반으로 하기 때문에 안정적으로 작동합니다.

 

All the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill your process or which of the mentioned callbacks are called or not. Please note the "killable" column in the lifecycle events table in the Android documentation.

onDestroy 또는 onSometing 이벤트나 바인더 또는 정적 변수를 사용하는 모든 접근 방식은 Android가 프로세스를 종료하기로 결정할 때 또는 언급된 콜백 중 어느 것이 호출되는지 여부를 개발자로서 결코 알지 못하기 때문에 안정적으로 작동하지 않습니다. Android 설명서의 수명 주기 이벤트 표에 있는 "killable" 열에 유의하십시오.

 

 

 

 가장 최근 달린 Solution 

Another approach using kotlin. Inspired in other users answers

코틀린을 이용한 또 다른 접근법이 있습니다.. 다른 사용자의 답변에서 영감을 얻었습니다.
fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
    val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    return manager.getRunningServices(Integer.MAX_VALUE)
            .any { it.service.className == serviceClass.name }
}

 

As kotlin extension

코틀린으로 확장
fun Context.isMyServiceRunning(serviceClass: Class<*>): Boolean {
    val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    return manager.getRunningServices(Integer.MAX_VALUE)
            .any { it.service.className == serviceClass.name }
}

 

Usage

사용법
context.isMyServiceRunning(MyService::class.java)

 

 

출처 : https://stackoverflow.com/questions/600207/how-to-check-if-a-service-is-running-on-android

반응형
댓글
공지사항
최근에 올라온 글