繁体   English   中英

如何取消前台服务使用通知(滑动关闭)或清除所有通知?

[英]How to cancel a foreground service from using the notification (swipe dismiss) or clear all notifications?

我目前正在创建一个前台服务,当服务启动时,该服务会出现在通知栏中。 如果服务停止,通知将消失。 我的问题是,有没有办法在“清除所有通知”或取消通知(滑动)时停止服务?

更新以包括通知的实施:

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;        
}

不允许用户刷掉由正在进行的前台服务生成的通知。

因此, stopForeground(false) ,这允许用户随后将通知stopForeground(false)至少在 Lollipop+ 上)。 对于前棒棒糖,您可能需要stopForeground(true) ,它停止前台并删除通知,然后使用notificationManager.notify(yourNotificationID, yourNotificationObject)重新发出通知,以便您的通知可见但可滑动。

至关重要的是,使用删除意图设置通知对象,当用户将其滑开时会触发该意图。

(new NotificationCompat.builder(this).setDeleteIntent(deletePendingIntent)).build()

其中deletePendingIntent类似于

Intent deleteIntent = new Intent(this, YourService.class);
deleteIntent.putExtra(someKey, someIntValue);
PendingIntent deletePendingIntent = PendingIntent.getService(this,
someIntValue, 
deleteIntent, 
PendingIntent.FLAG_CANCEL_CURRENT);

当用户将其滑开时,带有额外内容的 Intent 将传递给服务。 onStartCommand处理传递的额外onStartCommand ,即检查intent != nullintent.getExtras() != null ,然后从给定someKey的 extras 包中提取值,如果它匹配someIntValue ,则调用stopSelf()

这段代码对我有用:

this.stopForeground(false);
mNotificationManager.cancel(NOTIFY_ID);

并且您应该设置 onStartCommand 的返回值,STRAT_STICKY 将重新启动您的服务。

无法清除前台服务的通知。 唯一的办法就是停止服务。

所以我相信你想解决的问题永远不会发生。

我的问题是,有没有办法在“清除所有通知”或取消通知(滑动)时停止服务?

假设您的Notification设置为允许清除,则应在清除时调用deleteIntent 您可以将其设置为getBroadcast() PendingIntent ,指向调用stopService()的清单注册BroadcastReceiver

您可以在您创建的通知中设置一个dismissIntent,但我认为前台服务通知无法清除?

我做了以下工作,它对我有用:

  1. 我在调用前台服务之前创建了一个通知,使用相同的 id 和通知通道与前台服务的通知一起使用

  2. 我通过通知 id 取消了通知

  3. 我用您所需的结构创建了另一个通知

  4. 您可以在不停止前台服务的情况下关闭或滑动最后一条通知

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM