Android 是否可以检查通知是否可见或已取消?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12654820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:21:13  来源:igfitidea点击:

Is it possible to check if a notification is visible or canceled?

androidnotifications

提问by Asaf Pinhassi

I would like to update notification data, but the only way I found is to launch a new one with the same Id.

我想更新通知数据,但我找到的唯一方法是使用相同的 ID 启动一个新的。

The problem is that I don't want to raise a new one if the original has beed canceled. Is there a way to tell if a notification is visible or canceled? Or a way to update a notification only if it exists?

问题是,如果原来的被取消了,我不想再提出一个新的。有没有办法判断通知是否可见或已取消?或者只有在通知存在时才更新通知的方法?

采纳答案by Asaf Pinhassi

This is how I solved it:

我是这样解决的:

    private boolean isNotificationVisible() {
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent test = PendingIntent.getActivity(context, MY_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
    return test != null;
}

This is how I generate the notification:

这就是我生成通知的方式:

    /**
 * Issues a notification to inform the user that server has sent a message.
 */
private void generateNotification(String text) {

    int icon = R.drawable.notifiaction_icon;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, text, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MainActivity.class);

    // set intent so it does not start a new activity
    //notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, MY_ID, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, text, intent);

    notification.flags |= Notification.FLAG_AUTO_CANCEL; //PendingIntent.FLAG_ONE_SHOT

    notificationManager.notify(MY_ID, notification);
}

回答by Sayed Abolfazl Fatemi

If you're app has a minimum API >= 23can use this method to get active notification:

如果您的应用程序具有最低限度,则API >= 23可以使用此方法获取活动通知:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
StatusBarNotification[] notifications = mNotificationManager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
  if (notification.getId() == 100) {
    // Do something.
  }
}

回答by Vishal Vyas

I think you can use deleteIntentof Notificationclass.

我想你可以使用deleteIntentNotification类。

I remember in one of my application I use use to fire a Broadcast (custom Broadcast) when a notification is cancelled or the Notification tray was cleared.

我记得在我的一个应用程序中,当通知被取消或通知托盘被清除时,我用来触发广播(自定义广播)。

回答by stemadsen

An alternative to the deleteIntentis the following which has proved beneficial in my own app:

deleteIntent以下是在我自己的应用程序中证明有益的替代方案:

Basically, you create an intent with your notification that starts an IntentService(or any other service) and in onHandleIntentyou can set a flag indicating whether the notification is active.
You can set this intent to be fired when the user taps the notification (contentIntent) and/or when the user clears it from the list (deleteIntent).

基本上,您使用启动IntentService(或任何其他服务)的通知创建一个意图,并在其中onHandleIntent设置一个标志,指示通知是否处于活动状态。
当用户点击的通知(您可以将此意图被解雇contentIntent)和/或当用户从列表中清除(deleteIntent)。

To illustrate it, here is what I do in my own app. When building the notification I set

为了说明这一点,这是我在自己的应用程序中所做的。在构建我设置的通知时

Intent intent = new Intent(this, CleanupIntentService.class);
Notification n = NotificationCompat.Builder(context).setContentIntent(
        PendingIntent.getActivity(this, 0, intent, 0)).build();

When the notification is tapped, my CleanupIntentServiceis launched, setting a flag (in the service that created the notification):

当通知被点击时,myCleanupIntentService被启动,设置一个标志(在创建通知的服务中):

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onCreate(); // If removed, onHandleIntent is not called
    return super.onStartCommand(intent, flags, startId);
}


@Override
protected void onHandleIntent(Intent intent) {
    OtherService.setNotificationFlag(false);
}

回答by EdgeDev

In my situation, I wanted to check if a Notification was already shown before showing another. And it turns out there's a simple way to do it without listening to when the Notification was deleted or dismissed with .setAutoCancel(true)on NotificationManagerCompat.Builder.

在我的情况下,我想在显示另一个通知之前检查是否已经显示了通知。事实证明,有一种简单的方法可以做到这一点,而无需监听通知何时被删除或解除.setAutoCancel(true)on NotificationManagerCompat.Builder

 private val NOTIF_ID = 80085
 private val CHANNEL_ID = "com.package.name.ClassName.WhatNotifycationDoes"  
 private lateinit var mNotificationManagerCompat: NotificationManagerCompat
 private lateinit var mNotificationManager: NotificationManager // this is for creating Notification Channel in newer APIs

override fun onCreate() {
    super.onCreate()

    mNotificationManagerCompat = NotificationManagerCompat.from(this)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
       mNotificationManager = getSystemService(NotificationManager::class.java)

    showNotification()
    startWatching()
}

private fun showNotification() {
        val contentIntent = Intent(this, MainActivity::class.java)
                .apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }
        val contentPendingIntent = PendingIntent.getActivity(this, 1, contentIntent, 0)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = getString(R.string.app_name)
        val importance = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel(CHANNEL_ID, name, importance)
        channel.description = getString(R.string.your_custom_description)
        mNotificationManager.createNotificationChannel(channel)
    }

    val mNewStatusNotificationBuilder = NotificationCompat.from(this)
    mNewStatusNotificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.simple_text))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(contentPendingIntent)
            .setAutoCancel(true) // This dismisses the Notification when it is clicked
            .setOnlyAlertOnce(true) //this is very important, it pops up the notification only once. Subsequent notify updates are muted. unless it is loaded again    

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
        mNewStatusNotificationBuilder.setSmallIcon(R.drawable.ic_notification)

    notification = mNewStatusNotificationBuilder.build()

    mNotificationManagerCompat.notify(NOTIF_ID, notification)
}