2017-04-24 1 views
0

사용자가 음악을 시작/중지 할 수있는 음악 제어 알림이 있습니다. Google Play 뮤직 앱 알림보다 정확히 같은 행동을 원합니다. 음악이 재생 중일 때 서비스는 포 그라운드에 있고 알림은 취소 할 수 없으며 음악이 재생되지 않을 때 서비스는 더 이상 전경이 아니며 알림이 될 수 있습니다. 제거되었습니다. 그것은 잘 작동하지만 내 서비스의 포 그라운드를 취소하면 알림은 즉시 사라지기 전에 신속하게 제거됩니다. 여기 서비스가 포 그라운드에 없을 때 취소 할 수있는 포 그라운드 서비스로부터의 알림

내가 알림 구축 첫 번째 방법, 내 코드입니다 :

NotificationCompat.Builder notifBuilder = 
      new android.support.v7.app.NotificationCompat.Builder(getApplicationContext()) 
        .setStyle(new android.support.v7.app.NotificationCompat.MediaStyle() 
          .setShowActionsInCompactView(1, 2, 3) 
          .setShowCancelButton(true) 
          .setCancelButtonIntent(deletePendingIntent))) 
        .setSmallIcon(R.drawable.notif_logo) 
        .setColor(ResourcesCompat.getColor(getResources(), R.color.blue, getTheme())) 
        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) 
        .setShowWhen(false); 

    notifBuilder.setContentIntent(pendingIntent); 
    notifBuilder.setDeleteIntent(deletePendingIntent); 

을 그리고 여기에 내가 시작하고 내 알림 업데이트하는 방법입니다

private void showNotification(NotificationCompat.Builder notifBuilder, boolean foreground) { 
    if (foreground) { 
     startForeground(NOTIFICATION_ID, notifBuilder.build()); 
    } else { 
     stopForeground(false); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(NOTIFICATION_ID, notifBuilder.build()); 
    } 
} 

I (false)를 stopForeground를 사용하는 경우

, 통지를 그것을 실행 한 후에도 취소 할 수 없습니다. stopForeground (true)를 사용하면 알림이 빠르게 제거 된 다음 다시 추가되어 이상한 깜박임을줍니다.

서비스를 제거한 후 알림을 다시 추가하지 않고 서비스가 포 그라운드에서 종료 된 후에 취소 할 수있는 방법은 무엇입니까? Using MediaStyle notifications with a foreground service documentation

답변

1

:

안드로이드 5.0 (API 레벨 21) 이상이 서비스가 더 이상 포 그라운드에서 실행되면 플레이어를 멈추지하는 통지를 와이프 수에서

. 이전 버전에서는이 작업을 수행 할 수 없습니다. 사용자가 Android 5.0 (API 수준 21) 전에 알림을 제거하고 재생을 중지 할 수 있도록하려면 setShowCancelButton(true)setCancelButtonIntent()을 호출하여 알림의 오른쪽 상단에 취소 버튼을 추가 할 수 있습니다.

당신은이 서비스가 전경 현재의 여부에 의해 제어 될 때 setOngoing(false)/setOngoing(true)를 호출 할 필요는 없습니다.

음악이 일시 중지되면 stopForeground(false)으로 전화해야합니다. 그러면 전경 우선 순위가 제거되고 사용자가 API 21 이상의 기기에서 알림을 스 와이프 할 수 있습니다.

+0

안녕하세요, 귀하의 회신에 감사드립니다. stopForeground (false)가 시도한 첫 번째 작업이지만 작동하지 않습니다. 알림을 취소 할 수 없거나 실행 한 후에 스 와이프 할 수 없습니다. API 25 기기에서 테스트 중입니다. 코드와 마지막 질문을 업데이트했습니다. – MickaelG

+0

에뮬레이터 또는 Nexus/Pixel 기기에서 동일한 문제가 발생합니까? – ianhanniballake

+0

마지막으로 버그를 발견했습니다! stopForeground (false)가 의도 한대로 작동하려면 버전 21 이상을 대상으로해야합니다. 버전 20을 목표로했습니다. 버그를 재현하는 미니멀 프로젝트를 만들었습니다 : https://github.com/MickaelGuilbeaud/AndroidForegroundNotification NotificationCompat를 사용할 때 targetSdkVersion 21이 필수라고 기대하지 않았습니다. – MickaelG

관련 문제