8

간단한 질문 :NotificationCompat.Builder 및 startForeground를 사용하는 방법?

서비스에 사용할 알림을 만들려면 NotificationCompat.Builder 클래스를 사용하려고하지만 어떤 이유로 알림이 표시되지 않거나 서비스가 파괴 될 때 (또는 포 그라운드에서 정지 할 때) 취소하십시오.

내 코드 :

@Override 
public int onStartCommand(final Intent intent, final int flags, final int startId) { 
    final String action = intent == null ? null : intent.getAction(); 
    Log.d("APP", "service action:" + action); 
    if (ACTION_ENABLE_STICKING.equals(action)) { 
     final NotificationCompat.Builder builder = new Builder(this); 
     builder.setSmallIcon(R.drawable.ic_launcher); 
     builder.setContentTitle("content title"); 
     builder.setTicker("ticker"); 
     builder.setContentText("content text"); 
     final Intent notificationIntent = new Intent(this, FakeActivity.class); 
     final PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
     builder.setContentIntent(pi); 
     final Notification notification = builder.build(); 
     // notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; 
     // notification.flags |= Notification.FLAG_NO_CLEAR; 
     // notification.flags |= Notification.FLAG_ONGOING_EVENT; 

     startForeground(NOTIFICATION_ID, notification); 
     // mNotificationManager.notify(NOTIFICATION_ID, notification); 

    } else if (ACTION_DISABLE_STICKING.equals(action)) { 
     stopForeground(true); 
     stopSelf(); 
     // mNotificationManager.cancel(NOTIFICATION_ID); 
    } 
    return super.onStartCommand(intent, flags, startId); 
} 

주석으로 명령이 작동하도록 내 시험이다. 어떤 이유로 든 아무도 일하지 않았습니다.

contentIntent를 원했기 때문에 가짜 활동을 추가하기는했지만 여전히 작동하지 않습니다.

아무도 도와 줄 수 있습니까?

+0

이 게시물이 있음을 명시하도록 업데이트 솔루션에 일 근무 후 내 문제가 해결되었습니다. –

답변

9

전 정확히 똑같은 문제가 있었는데 어떤 이유로 알림 ID 0이 startForeground()과 잘 작동하지 않는다는 것을 알게되었습니다. 코드에 NOTIFICATION_ID 값이 있습니까?


편집 : 이제 문서, 0은 허용 대답과 함께, 잘못된 ID

+0

예. 그것은. 나는 보통이 번호로 모든 것을 시작하기 때문에 그것을 바꿀 생각을하지 않았다. –

+0

나는 그곳에 대한 해답을 발견했다. (분명히 알고있다.) [there] (http://stackoverflow.com/questions/8725909/startforeground-does-not-show-my-notification) 그 게시물의 OP뿐만 아니라 나를 위해 그것을 고정, 그래서 당신의 문제를 해결한다. 가장 좋은 방법은 시도하는 것입니다 :) – Joffrey

+0

내가 안드로이드에 어떤 더 이상한 버그를 찾을 수 없다는 것을 나 자신에게 말할 때마다 ... –

관련 문제