我目前正在使用服務啓動時出現在通知欄中的通知創建前臺服務。如果服務停止,通知將被解除。我的問題是,有沒有辦法在「清除所有通知」或解除通知(刷卡)時停止服務?如何使用通知取消前臺服務(刷卡解除)或清除所有通知?
更新以包括執行通知:
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(CLASS, "onStartCommand service started.");
if (getString(R.string.service_start_action) == intent.getAction())
{
Intent intentForeground = new Intent(this, ServiceMain.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(getApplicationContext(), 0, intentForeground, 0);
Notification notification;
Notification.Builder builder = new Notification.Builder(getApplicationContext())
.setSmallIcon(android.R.drawable.btn_star)
.setTicker("Service started...")
.setContentIntent(pendIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setOngoing(false);
notification = builder.build();
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
startForeground(SERV_NOTIFY, notification);
player.start();
}
else
{
Log.d(CLASS, "onStartCommand unable to identify acition.");
}
return START_STICKY;
}
看看這個來自Google的示例:https://github.com/googlesamples/android-ActiveNotifications。它顯示瞭如何聆聽被駁回的通知以及整個通知組。 –
據我所知,如果不創建通知,您無法「創建」前臺服務。 Android需要這樣做,因爲他們不希望你在用戶不知道的情況下在場景後面運行服務。當您的活動被銷燬並且您的服務在前臺運行時,請刪除通知以通知您,您不能僅僅取消它。取消通知只能通過調用'.stopForeground(true)'取消前臺服務本身,布爾參數指示是否要隨通知一起停止前臺。 –