안드로이드 개발 질문/답변
(글 수 45,052)
안녕하세요.
서비스에서 통지를 해서, 액티비티를 실행할 수 있게 만들려고 하는데..
거기 까지는 쉬우니까 구현 했구요,
문제는 액티비티가 구동중인 상태일 때도 통지가 계속 뜨더라구요.
그래서 그러는데, 액티비티가 구동중일때는 서비스에서 통지가 안 가게 하려고 하는데, 서비스에서 자기 패키지의 특정 액티비티 클래스가 실행중인지 아닌지 판별하는 방법이 있나요?
2012.02.22 20:38:44
public static boolean isForegroundActivity(Context context, Class<?> cls) {
if(cls == null)
return false;
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> info = activityManager.getRunningTasks(1);
RunningTaskInfo running = info.get(0);
ComponentName componentName = running.topActivity;
return cls.getName().equals(componentName.getClassName());
}
2012.02.22 20:38:33
http://api5.forcert.com/bbs/board.php?bo_table=B49&wr_id=54779
여기도 괜찮은 글들이 많네요. 훗날 검색으로 참고할 분들에게 도움이 되시기를!




private boolean getServiceTaskName() {
boolean checked = false;
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> info;
info = am.getRunningServices(30);
for(Iterator iterator = info.iterator(); iterator.hasNext();) {
RunningServiceInfo runningTaskInfo = (RunningServiceInfo) iterator.next();
Log.i(TAG, "Service name :runningTaskInfo.service.getClassName());
if (runningTaskInfo.service.getClassName().equals("내 패키지명")) {
checked = true;
Log.i(TAG2, "Service is.... : " + checked);
}
}
return checked;
}
하지만 디바이스내 실행되는 서비스 목록이 많다면... 다소 시간이 걸릴수도 있겠으며...
토나올수도 있을것이다.
두번째 방법은 아래코드 처럼 더더욱 간단히 구현 가능하다.
static 형태로 저장한다면, 서비스를 중지 시킬때도 꽤 유익하게 사용할 수 있을것이다.
ComponentName serviceName = startService(serviceIntent);
Intent i = new Intent();
i.setComponent(serviceName);
stopService(i);
또 한가지, 모든 Service를 한 Activity 내에서 종료하지는 않을 것이다...대게는??
Service 를 구현하고 있는 class 내에 stopSelf(); 함수로 종료시켜주자.