Android 13:即使设置了“setOnGoing(true)”,用户也可以关闭通知

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

我正在做一个前台服务,我们知道这样的服务需要通知才能继续运行。 然而,从 Android 13 开始,用户只需滑动即可关闭它,因此应用程序被杀死。

我尝试在通知生成器上使用 setOnGoing(true) 但没有用。

我需要让通知不可关闭。

这是我在 Kotlin 中的代码。

      private fun startForegroundServiceWithNotification() {
        Log.d("myTag", "startForegroundServiceWithNotification")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = CHANNEL_ID
            val channelName = "Wish2Go step counter"
            val chan = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            service.createNotificationChannel(chan)
        }


        var builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setOngoing(true)
            .setContentTitle("Counting steps")
            .setPriority(NotificationCompat.PRIORITY_HIGH)

        var notification = builder.build()
        notification.flags = Notification.FLAG_ONGOING_EVENT
        startForeground(1001, notification)

    }
android react-native foreground-service foregroundnotification
1个回答
0
投票

我做的一个app里有类似的前台服务。在我的应用程序中,我使用计时器每秒更新一次通知,因为我的应用程序将倒数计时器显示为通知的一部分。如果用户关闭了通知,它会在一秒钟后重新出现。也许你可以在你的应用程序中尝试类似的东西。

我会尝试创建一个无限循环的线程,该线程休眠一秒钟然后刷新通知。这是在 Java 中,但你明白了。

// init and build notification, same as before 
notification = builder.build();

// create a notification manager
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

// infinite loop with a 'kill switch' for when the user manually stops the service from the app
while (!killSwitch) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);  // sleep for one second

                /* make sure the first parameter here matches the id you defined when 
                   you initialized the notification */
                notificationManager.notify(1001, builder.build());

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }).start();
}  
© www.soinside.com 2019 - 2024. All rights reserved.