我需要编写一些可以在后台完成一些工作的应用程序。这个应用程序将从autostart运行,并没有任何开始gui。 Gui可以通过点击通知进行呼叫,该通知将显示自动启动。我担心,当用户明确通知时,他失去了打电话给这个gui的机会。我的问题是,有没有办法阻止用户清除我的通知?
答案 0 :(得分:21)
这是一个不允许用户清除它的通知。
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();
setOngoing(true)
来电达到此目的,当用户点按通知时,setAutoCancel(false)
会停止通知离开。
如果卸载了应用程序或通过调用取消或取消所有通知将被清除:http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)
答案 1 :(得分:3)
您可能希望在通知的“正在运行”部分中进行通知。当用户清除这些通知时,不会清除这些通知。
使用Notification.FLAG_NO_CLEAR AND Notification.FLAG_ONGOING_EVENT。这应该给你想要的效果
答案 2 :(得分:0)
虽然@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帖子。
欢呼/快乐编码......答案 3 :(得分:0)
只需将这两个标志添加到通知中, FLAG_AUTO_CANCEL 会阻止用户触摸时自动解除通知, FLAG_ONGOING_EVENT 使其成为Ongoing Notification。
notification.flags=Notification.FLAG_AUTO_CANCEL|Notification.FLAG_ONGOING_EVENT;
答案 4 :(得分:0)
单独使用此功能对我来说非常完美 Notification.FLAG_NO_CLEAR 随着 notification.SetOngoing(true);
notification.SetAutoCancel(false);
答案 5 :(得分:-5)
您想要实施Foreground Service。