在我的应用程序中,有一个在后台运行的服务。我想通知用户该服务正在运行。但是我需要确保用户无法删除通知 - 无论是通过按清除按钮还是通过在通知栏中滑动它。
// Create notification
Notification note = new Notification(R.drawable.your_icon, "Example notification", System.currentTimeMillis());
// Set notification message
note.setLatestEventInfo(context, "Some text", "Some more text", clickIntent);
// THIS LINE IS THE IMPORTANT ONE
// This notification will not be cleared by swiping or by pressing "Clear all"
note.flags |= Notification.FLAG_NO_CLEAR;
对于 API 级别在 11 及以上,或者使用了 Android Support Library 的情况下,可以按照以下方式实现:
对于 API 级别在 11 及以上,或者使用了Android Support Library的情况下,可以像这样实现:
Notification noti = new Notification.Builder(mContext)
.setContentTitle("Notification title")
.setContentText("Notification content")
.setSmallIcon(R.drawable.yourIcon)
.setLargeIcon(R.drawable.yourBigIcon)
.setOngoing(true) // Again, THIS is the important line
.build();
要创建不可删除的通知,只需使用 setOngoing(true);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_service_launcher)
.setContentTitle("My title")
.setOngoing(true)
.setContentText("Small text with details");
要创建不可移除的通知,只需使用 setOngoing(true);
要创建可移除的通知,只需使用 setOngoing(false);