Android:当您的应用在后台运行时,在通知上使用AUTO-CANCEL
问题内容:
我在这里查看了所有其他“自动取消”问题,这些问题似乎都包含我没有犯的错误。我都尝试过
builder.setAutoCancel(true);
和
Notification notif = builder.build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
都不行。
由于我的最低API为8,因此我正在使用NotificationCompat。这是我的完整代码。在此特定通知中,我并不是在调用意图,因为我不需要用户执行任何操作。
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getString(R.string.app_name) + ": my title");
builder.setContentText(message);
builder.setSmallIcon(R.drawable.notification_icon);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.prog_icon);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true); // dismiss notification on user click
NotificationManager notiManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notiManager.notify(MY_NOTI_MANAGER_ID, builder.build());
通知显示完美。您可以滑动以清除它。但是,只需点击它并不会取消该通知。它只是点亮并停留在那里。
我的代码与此处发布的其他代码之间可能存在一些差异:1)我正在使用NotificationCompat(这没有什么区别,但我们之前已经听说过)。2)因为通知很简单,所以我没有意图。
如果您有任何见解,请告诉我。
编辑:我的目的是在不使我的后台应用程序前台的情况下关闭通知。
问题答案:
因此,显然您 确实 需要一个待定的意图。
在Android的通知管理器中,我收到了一个没有意图的通知,我找到了一个解决方案,该解决方案可以将当前活动的应用程序作为待处理的意图(这样,您不必启动自己的活动即可关闭该通知)。
我只添加了以下两行代码(设置自动取消后):
PendingIntent notifyPIntent =
PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
builder.setContentIntent(notifyPIntent);
效果很好。我想说的是,如果您不希望由于用户单击通知而重新开始活动,那么这是您的最佳选择。