2017-04-24 87 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()); 
    } 
} 

如果我使用stopForeground(假),通知運行後仍不能取消。如果我使用stopForeground(true),通知會很快刪除,然後再次添加,這會產生奇怪的閃爍。

如何在服務退出前臺後取消通知,而不必刪除然後再次添加通知?

回答

1

Using MediaStyle notifications with a foreground service documentation

在的是Android 5.0(API等級21),以後你可以刷卡離開的通知,停止播放器,一旦該服務不再在前臺運行。您不能在早期版本中執行此操作。要允許用戶刪除通知並在Android 5.0(API級別21)之前停止播放,您可以通過調用setShowCancelButton(true)setCancelButtonIntent()在通知的右上角添加取消按鈕。

你永遠不需要調用setOngoing(false)/setOngoing(true)爲您的服務目前是否在前臺控制。

根據Media Session Callbacks docs,當您的音樂暫停時您應該被稱爲stopForeground(false) - 這會刪除前臺優先級,並允許用戶在API 21+設備上將通知刷除。

+0

嗨,謝謝你的回覆。 stopForeground(false)是我嘗試的第一件事,但它不起作用,通知仍然不可取消/運行後無法刷新。我正在API 25設備上進行測試。我更新了代碼和我的問題的最後一部分。 – MickaelG

+0

您是否在仿真器或Nexus/Pixel設備上看到相同的行爲? – ianhanniballake

+0

終於找到了bug!對於stopForeground(false)按預期工作,我需要瞄準版本21或更多。我的目標是版本20. 我創建了一個重現該bug的極簡主義項目:https://github.com/MickaelGuilbeaud/AndroidForegroundNotification 當我使用NotificationCompat時,我並不認爲targetSdkVersion 21是強制性的。 – MickaelG