我正在开发一个应用程序,希望通过添加持续通知来向用户提供功能的快捷方式。这有点像一些词典应用程序,它们提供快捷方式作为快速搜索的通知。
问题是即使我有 setOngoing(true) 和 setAutoCancel(false),一旦从多任务窗格中关闭应用程序,它仍然会被删除
我使用的代码如下。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "C1";
String description = "C1 is C1";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("XXXX")
.setContentText("XXXXXXXX")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setAutoCancel(false);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(NOTIFICATION_ID_2, builder.build());
您可以启动前台服务,以便您的通知持久存在。您需要将
FOREGROUND_SERVICE
权限添加到您的 manifest
,然后从您的应用程序构建/启动服务。然后,从服务内部设置通知。
前台服务的 Android 文档有很好的演练。