如何合法防止Android中的通知被删除

问题描述 投票:0回答:3

我正在开发一个应用程序,希望通过添加持续通知来向用户提供功能的快捷方式。这有点像一些词典应用程序,它们提供快捷方式作为快速搜索的通知。
问题是即使我有 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());
android notifications
3个回答
0
投票

您可以启动前台服务,以便您的通知持久存在。您需要将

FOREGROUND_SERVICE
权限添加到您的
manifest
,然后从您的应用程序构建/启动服务。然后,从服务内部设置通知。

前台服务的 Android 文档有很好的演练。


0
投票

在 Android 13(API 级别 33)中,用户可以通过滑动手势来关闭与前台服务链接的通知。之前版本的 Android 不允许在前台服务停止或从前台删除之前关闭通知。 要使 API 33 及更高版本中的通知不可被用户忽略,请使用

Notification.Builder

并在创建过程中将

setOngoing()
方法设置为
TRUE
Android 文档:

    处理用户发起的停止
  • 用户关闭通知

0
投票
始终可以被用户忽略

© www.soinside.com 2019 - 2024. All rights reserved.