【问题标题】:Want to hide Notification but getting Context.startForegroundService() did not then call Service.startForeground()想要隐藏通知但获取 Context.startForegroundService() 并没有调用 Service.startForeground()
【发布时间】:2019-05-11 06:43:00
【问题描述】:

我想在服务在后台运行时隐藏通知。我知道根据 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 中是否可行?

【问题讨论】:

  • "I want to hide notification" - 幸运的是这是不可能的 - 我不希望在我不知情的情况下在前台运行任何服务......

标签: android notifications android-service


【解决方案1】:

我希望该服务不向用户显示任何通知并静默完成其任务而不会被杀死

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

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

这些都不需要前台服务。

【讨论】:

  • 谢谢。会检查的。
猜你喜欢
  • 2017-11-09
  • 2019-01-09
  • 2018-03-29
  • 2018-03-04
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多