마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

startForeground notification문의

0 추천
안드로이드 4.3이후에는 startForeground를 사용할시 notification이 뜨는데

카톡도 동이라게사용하고 있다고 하던데 카톡은 notification이 뜨지 않습니다.

 

 @SuppressWarnings("deprecation")
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.i(TAG, " +++ onStartCommand Service +++");
  
  startForeground(startId,new Notification());

        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification notification;  
  
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            notification = new Notification.Builder(getApplicationContext())
                    .setContentTitle("")
                    .setContentText("")
                    .build();
 
        }else{
            notification = new Notification(0, "", System.currentTimeMillis());
            notification.setLatestEventInfo(getApplicationContext(), "", "", null);
        }
       
        nm.notify(startId, notification);    
        nm.cancel(startId);

        return super.onStartCommand(intent, flags, startId);
 }
 

이 방법을 통해서 notification이 cancel이 되기는 한데 가끔씩 cancel이 안 될때가 있습니다.

onDestory에서도

        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        nm.cancelall();
 해보았지만 가끔씩 cancel되지 않습니다.

혹시 이 문제를 해결하는 방안을 아시는 분은 제발 알려주시면 감사하겠습니다.

부탁드립니다.
쿠쿠부다스 (6,470 포인트) 님이 2015년 12월 30일 질문

1개의 답변

0 추천
 
채택된 답변
startForground 로 실행 시 Foreground에서 해당 서비스를 내리려면 stopForeground를 호출하셔야 합니다.

카카오톡이 항시 알람이 떠있는 상태가 아니기 때문에 (판별하시려면 알림을 스와이프했을 때 취소가 되는지 안되는지 확인하는 것이 빠릅니다) 아마 서비스가 죽으면 재시작하는 방식으로 구현했을 듯 합니다.
ShakeJ (6,320 포인트) 님이 2015년 12월 31일 답변
쿠쿠부다스님이 2015년 12월 31일 채택됨
즉 서비스가 꼭 살아있어야 하는 경우에만 startForeground를 사용하며, 만약 백그라운드에서만 처리가 되는 경우에는 startForeground가 아닌 사용하신 nm.notify만 사용하시면 됩니다 :)
(서비스가 항상 떠있어야 한다면, 서비스의 onDestroy 에서 alarmmanager 로 재시작하는 방법이 있습니다 zombie service 로 구글링해보시면 도움 되실겁니다)
startForeground 사용안할 경우에는 taskkill 했을 경우 프로세스가 다시 살아나는 동안 서비스 작동되지를 않네요. 서비스 살릴때는 알람매니저를 사용했고요..
...