首页 文章

想要隐藏通知但是获取Context.startForegroundService()然后没有调用Service.startForeground()

提问于
浏览
0

我想隐藏服务在后台运行时出现的通知 . 我知道根据Google Play规则,我们必须显示通知,但对于我当前的应用,我不想显示任何通知 .

这是代码,它工作正常并显示通知 . 但是如何让它不显示任何通知:

try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = "com.app..";
                String channelName = "App Background Service";
                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                channel.setLightColor(Color.BLUE);
                channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(channel);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
                Notification notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("App is running in background")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                startForeground(0, notification);
            } else
            {
                startForeground(0, new Notification());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

如果我没有把上面的代码,它给出错误说没有找到startForeground . 并在5秒后自动被杀死 .

原因:Context.startForegroundService()没有调用Service.startForeground()

我希望服务不向用户显示任何通知,并在不被杀死的情况下以静默方式完成任务 . 甚至可以在Build Version> 26中使用它?

1 回答

  • 1

    我希望服务不向用户显示任何通知,并在不被杀死的情况下以静默方式完成任务

    使用 JobIntentService 并确保您的工作在不到10分钟的时间内完成 . 请注意,在工作开始之前可能会有一些延迟(这不会计入10分钟的限制) .

    或者,使用 IntentService 并确保您的工作在不到1分钟内完成 .

    这些都不需要前台服务 .

相关问题