【发布时间】: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