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

3
我希望在应用程序内显示通知,当通知被点击而不启动活动时,通知会消失。
我使用一个空意图,它可以正常工作:
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)
    ...

根据这个SO回答,崩溃似乎是因为intent未启动活动而发生的。
可以通过ID关闭通知,但当没有活动可启动并调用dismiss方法时,无法关闭它。
如何在应用程序内部轻敲时关闭通知而不使用空意图?

更新:

根据这个SO问题,似乎是Android的一个问题。 我得到的报告中出现了崩溃,也发生在Android 4.3上。

更新2:

根据这个SO回答,似乎是由于使用setLargeIcon设置的位图过大造成的。 因此,我现在正在使用Glide缩小位图大小。
3个回答

7
您可以创建一个意图,调用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);
    }
}

编辑:
NOTIFICATION_ID是您定义并传递给NotificationManager的常量,如下所示:
notificationManager.notify(NOTIFICATION_ID, yourNotificationObject);

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

<receiver android:name="com.example.package.CancelNotification" />

1
@IgorGanapolsky 这是你发布通知时在 NotificationManager 中定义的常量:notificationManager.notify(NOTIFICATION_ID, yourNotificationObject); - oemel09
如果有人发现这个答案,如果您有多个通知,则PendingIntent中的requestCode应该是唯一的(例如,使用通知的ID)。 - BigBoiVladica

3
如果您不想在用户点击通知时启动一个活动,则可以构建一个待定意图,该意图发送广播或启动服务。以下是一个示例:
PendingIntent.getBroadcast(context, 12, new Intent("any intent action"), PendingIntent.FLAG_UPDATE_CURRENT)

1
但是,是什么阻止了您的活动像这样实现呢?
@Override
public void onCreate(Bundle savedInstanceState) {}

在清单中添加了额外的nodisplay主题:
android:theme="@android:style/Theme.NoDisplay"

这只是一个no-op


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接