如何在没有意图的情况下关闭通知?

Man*_*uel 3 notifications android android-notifications

我想在应用程序内显示一个通知,当在不启动活动的情况下点击通知时该通知会消失。

我使用一个空的意图,它的工作原理:

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);
Run Code Online (Sandbox Code Playgroud)

但是,有一些崩溃:

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)
    ...
Run Code Online (Sandbox Code Playgroud)

根据this SO answer,崩溃似乎是因为intent没有开始活动。

通知可以通过其 ID 解除,但是当没有活动要启动并调用解除方法时,我无法解除通知。

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


更新:

根据这个SO问题,它似乎是一个Android问题。我收到的崩溃报告也发生在 Android 4.3 上。

更新 2:

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

oem*_*l09 7

您可以创建一个调用 a 的意图BroadcastReceiver,然后取消通知。

您PendingIntent可以像这样创建:

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

该CancelNotification.java班将类似于此:

public class CancelNotification extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        notificationManager.cancel(NOTIFICATION_ID);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:
NOTIFICATION_ID是您定义并传递给NotificationManager这样的常量:

notificationManager.notify(NOTIFICATION_ID, yourNotificationObject);
Run Code Online (Sandbox Code Playgroud)

注意:不要忘记在您的清单文件中注册接收器,如下所示:

<receiver android:name="com.example.package.CancelNotification" />
Run Code Online (Sandbox Code Playgroud)