如何在Android Oreo中继续后台服务而不显示通知点?我使用通知来继续我的后台服务,但我不想显示正在运行的服务的通知。
如果您在这里仔细阅读了Android Oreo 8.0文档,您可能就不会在此发布问题了。
步骤1:请确保按照下面的代码,将服务作为前台
Service
启动。
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), GpsServices.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BluetoothService.class));
ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BackgroundApiService.class));
步骤2:使用通知来显示您的服务正在运行。在
Service
的onCreate
方法中添加下面的代码行。
@Override
public void onCreate() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, notification);
}
...
}
第三步:在服务停止或销毁时删除
notification
。
@Override
public void onDestroy() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true); //true will remove notification
}
...
}
这种解决方案的一个问题是,它将一直显示notification
,直到您的Service
在Android Oreo 8.0上运行的所有设备上运行。
我相信即使应用程序在后台或被杀死状态下,这个解决方案也能工作。
重要提示: 在Android Oreo 8.0中,在后台运行服务时(应用程序在后台或已被杀死),必须显示通知。您不能逃避此规定。因此,建议您按照Android提供的最佳实践对应用程序进行必要的更改,以使其按照最好的方式正常工作。
希望这可以帮助解决您的问题。
startForegroundService()
方法,即使活动未运行,您也授予了在后台运行服务的权限。一旦服务创建完成,服务必须在五秒内调用其startForeground()
方法。 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3- 确保您已经启动了服务。
您的服务应该有一个通知。您需要注意,您的通知必须具有ChannelID!
此页面可以帮助您:
现在将以下代码粘贴到您的服务中
@Override
public void onCreate() {
super.onCreate();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(" your Notification ID ", notification);
}
} catch (Exception e) {
Log.e(" Error --->> ", e.getMessage());
}
}
@Override
public ComponentName startForegroundService(Intent service) {
return super.startForegroundService(service);
}
and this:
@Override
public void onDestroy() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
}
}