J'ai une notification de contrôle de musique qui permet à l'utilisateur de démarrer/arrêter la musique. Je veux exactement le même comportement que la notification de l'application Google Play Musique: quand la musique joue, le service est en premier plan et la notification n'est pas annulable, et quand la musique ne joue plus, le service n'est plus au premier plan et la notification peut être enlevé. Cela fonctionne bien mais quand j'annule le premier plan de mon service, la notification est rapidement enlevée avant de réapparaître juste après.Annulation d'une notification d'un service d'avant-plan une fois que le service n'est plus en avant-plan
Voici mon code, d'abord comment je construis la notification:
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);
Et voici comment je commence et mettre à jour ma notification:
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());
}
}
Si je stopForeground (false), la notification n'est toujours pas annulable après l'avoir exécuté. Si j'utilise stopForeground (true), la notification est rapidement supprimée puis ajoutée à nouveau ce qui donne un clignotement bizarre.
Comment puis-je avoir une notification annulable après la fermeture d'un service au premier plan, sans avoir à supprimer puis à rajouter la notification?
Salut, merci pour votre réponse. stopForeground (false) est la première chose que j'ai essayée mais cela ne fonctionne pas, la notification n'est toujours pas annulable/ne peut pas être balayée après l'avoir exécutée. Je suis en train de tester sur un périphérique API 25. J'ai mis à jour le code et la dernière partie de ma question. – MickaelG
Voyez-vous le même comportement sur un émulateur ou un appareil Nexus/Pixel? – ianhanniballake
Enfin trouvé le bug! Pour que stopForeground (false) fonctionne comme prévu, je dois cibler la version 21 ou plus. Je ciblais la version 20. J'ai créé un projet minimaliste qui reproduit le bogue: https://github.com/MickaelGuilbeaud/AndroidForegroundNotification Je ne m'attendais pas à ce que targetSdkVersion 21 soit obligatoire lorsque j'utilise NotificationCompat. – MickaelG