티스토리 뷰

안드로이드 서비스 동작 중인지 파악하기


아래의 코드를 사용하면 된다.


나는 보통 static으로 선언하여 service 안에 넣는다.


예를 들어 service 이름이 'JHService' 라면

JHService.isServiceRunning(); 하면 여부가 나온다.


public static boolean isServiceRunning(Context context) {
		ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		
		for (RunningServiceInfo rsi : am.getRunningServices(Integer.MAX_VALUE)) {
			if ([서비스이름].class.getName().equals(rsi.service.getClassName())) //[서비스이름]에 본인 것을 넣는다.
				return true;
		}
		
		return false;
	}



이거 구현하면서 햇깔렸던게, String 비교 부분에서 .equals() 말고 == 을 해줬더니 계속 실패했다는 점...

문자열이 일치하는지 아닌지 비교하려면 .equals() 쓰는 것 잊지 말자. == 는 객체의 instance가 같은지 다른지 보는 연산자이다.


class.getName() 하는 것이나 service.getClassName() 하는 것이나 

kr.jhb.testapp.ServieName

위와 같이 package name + class name 으로 나온다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함