代码之家  ›  专栏  ›  技术社区  ›  Manuel

如何无意中撤销通知?

  •  -1
  • Manuel  · 技术社区  · 5 年前

    我想在应用程序中显示一个通知,当点击通知而不启动活动时,该通知将消失。

    我使用的是一个空的意图,它起作用:

    Intent intent = new Intent();
    PendingIntent contentIntent = PendingIntent.getActivity(context, (int)System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "")
                    .setSmallIcon(R.drawable.icon)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setAutoCancel(true)
                    .setTicker(text);
                    .setContentIntent(contentIntent);
    

    但是,也有一些崩溃:

    java.lang.RuntimeException: bad array lengths
        at android.os.Parcel.readIntArray(Parcel.java:789)
        at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:339)
        at android.app.NotificationManager.notify(NotificationManager.java:139)
        at android.app.NotificationManager.notify(NotificationManager.java:112)
        ...
    

    根据 this SO answer 车祸似乎是因为 intent 没有开始活动。

    通知可以通过其ID取消,但当没有活动启动和调用取消方法时,我不能取消它。

    在不使用空意图的情况下,如何在应用程序内关闭点击通知?


    更新:

    根据 this SO questions 这似乎是Android的问题。我得到的报告也发生在Android 4.3上。

    更新2:

    根据 this SO answer 这似乎是由于使用 setLargeIcon . 所以我现在用glide减小位图的大小。

    3 回复  |  直到 5 年前
        1
  •  1
  •   oemel09    5 年前

    您可以创建一个调用 BroadcastReceiver 然后取消通知。

    你的 PendingIntent 可以这样创建:

    private PendingIntent getCancelNotificationIntent() {
        Intent cancelIntent = new Intent(context, CancelNotification.class);
        return PendingIntent.getBroadcast(context, 0, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    

    这个 CancelNotification.java 类的外观类似于:

    public class CancelNotification extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            notificationManager.cancel(NOTIFICATION_ID);
        }
    }
    
        2
  •  1
  •   Link182    5 年前

    如果您不想在用户点击通知时启动活动,您可以构建一个发送广播或启动服务的待定意图。

    下面是一个例子:

    PendingIntent.getBroadcast(context, 12, new Intent("any intent action"), PendingIntent.FLAG_UPDATE_CURRENT)
    
        3
  •  1
  •   Marcin Orlowski    5 年前

    但是,是什么阻止了您的活动具有这样的实现:

    @Override
    public void onCreate(Bundle savedInstanceState) {}
    

    使用清单中的其他节点显示主题:

    android:theme="@android:style/Theme.NoDisplay"
    

    只是一个 no-op 一个。