Android 禁用我的应用程序的清除通知
我需要写一些应用程序,这将在后台做一些工作。此应用程序将从autostart运行,并且不会有任何启动gui。可以通过单击通知调用Gui,该通知将随autostart一起显示。我担心,当用户清除通知时,他失去了调用此gui的机会。我的问题是,有没有办法阻止用户清除我的通知?您可能希望在通知的“运行”部分查看发出通知的情况。当用户清除这些通知时,它们不会被清除Android 禁用我的应用程序的清除通知,android,notifications,Android,Notifications,我需要写一些应用程序,这将在后台做一些工作。此应用程序将从autostart运行,并且不会有任何启动gui。可以通过单击通知调用Gui,该通知将随autostart一起显示。我担心,当用户清除通知时,他失去了调用此gui的机会。我的问题是,有没有办法阻止用户清除我的通知?您可能希望在通知的“运行”部分查看发出通知的情况。当用户清除这些通知时,它们不会被清除 使用和。这将为您提供您想要的效果您想要实现的。这是一个不允许用户清除的通知 Notification notification = new
使用和。这将为您提供您想要的效果您想要实现的。这是一个不允许用户清除的通知
Notification notification = new NotificationCompat.Builder(this)
.setTicker(r.getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(r.getString(R.string.app_name))
.setAutoCancel(false)
.setOngoing(true)
.build();
setconsuming(true)
调用实现了这一点,并且setAutoCancel(false)
在用户点击通知时停止通知
如果卸载应用程序,或通过调用Cancel或CancelAll:尽管@cja的回答可能是正确的,但他缺少一些代码行(通知不会显示或不会显示在通知栏上),通知将被清除 这是完整的工作功能:
public void createNotification() {
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setTicker( "Ticker Text" );
notification.setSmallIcon(R.drawable.ic_launcher);
notification.setContentTitle( "Content Title" );
notification.setContentText( "Content Text" );
notification.setAutoCancel( false );
notification.setOngoing( true );
notification.setNumber( ++NotificationCount );
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setContentIntent(pIntent);
notification.build();
NotificationManager nManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManger.notify(NotificationID, notification.build());
}
NotificationID为int,用作通知的ID
您可以使用以下方法清除它:
public void clear() {
NotificationManager oldNoti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
oldNoti.cancel( NotificationID );
}
确保notification.setAutoCancel(false)代码>设置为false,因此当按下清除按钮或出现刷卡手势时,它不会被清除
几行代码最初来自@cja post
干杯/快乐编码 只需将这两个标志添加到通知中,当用户触摸该标志时,该标志自动取消阻止通知,该标志正在进行的事件使其成为一个事件
单独使用此选项对我来说非常有效。FLAG\u NO\u CLEAR
随着
通知。设置正在进行(true)
通知。设置自动取消(错误) 前台服务可以工作,因为它“不是系统在内存不足时要终止的候选服务”,并且需要显示通知。但是,仅仅为了显示无法清除的通知而创建服务真的是最佳做法吗?库罗的答案似乎要好得多。真的有理由同时使用这两种方法吗?在Android 4.2.x上,我只使用了Notification.Builder.setContinuous(),这本身似乎阻止了清除通知。我很好奇,因为我注意到通知.Builder似乎没有对应于标志“NO\u CLEAR”的方法。@ralphspoon请提出一个新问题并在此处链接感谢@ralphgabb我尝试使用相同的方法,但我仍然能够通过单击“全部清除”并滑动手势来清除通知。我正在开发最低API级别19和目标API级别25这很奇怪,我会尝试检查一下,这个函数在我这方面真的很有效(用于多个项目),或者你可以在这里发布几行代码。
notification.flags=Notification.FLAG_AUTO_CANCEL|Notification.FLAG_ONGOING_EVENT;