android oreo的后台服务 [英] Background service for android oreo

查看:240
本文介绍了android oreo的后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在没有显示通知点的情况下在android Oreo中继续后台服务?我使用通知继续我的后台服务,但我不想显示运行服务的通知。

How to continue background service in android Oreo without showing notification dot? i continues my background service using notification but i don't want to show notification for running service.

推荐答案

如果您已经在 Android Oreo 8.0 文档https://developer.android.com/guide/components/services.html#Foregroundrel =nofollow noreferrer>这里,您可能没有在这里发布此问题。

If you would have read the Android Oreo 8.0 Documentation properly somewhere in here, you might not have posted this question here.


步骤1:确保启动服务作为前景服务,如下所示下面的代码

Step 1: Make sure you start a service as a foreground Service as given in below code



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步:使用通知显示您的服务正在运行。在 onCreate 服务的方法中添加以下代码行。

Step 2: Use notification to show that your service is running. Add below line of code in onCreate method of Service.



@Override
public void onCreate() {
    ...
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(NOTIFICATION_ID, notification);
    }
    ...
}




步骤3 :停止或销毁服务时删除通知

Step 3: Remove the notification when the service is stopped or destroyed.



@Override
public void onDestroy() {
    ...
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          stopForeground(true); //true will remove notification
    }
    ...
}

此解决方案的一个问题是它将继续显示通知,直到您的服务在所有正在运行的设备上运行在 Android Oreo 8.0

One problem with this solution is that it will keep showing the notification until your Service is running on all devices running on Android Oreo 8.0.

我确信即使应用程序处于后台或处于终止状态,此解决方案也能正常运行。

I'm sure that this solution will work even when the app is in the background or in kill state.


重要说明:显示在背景中运行服务的通知(背景中的应用程序或杀死状态)是强制性的IN ANDROID OREO 8.0。你无法逃跑与它。 SO 建议您您在应用程序中进行必要的更改,使其按照最佳做法正确或按照ANDROID的要求进行正确工作。

IMPORTANT NOTE: SHOWING A NOTIFICATION FOR RUNNING A SERVICE IN BACKGROUND (APP IN BACKGROUND OR KILLED STATE) IS MANDATORY IN ANDROID OREO 8.0. YOU CANNOT RUN AWAY WITH IT. SO IT IS RECOMMENDED THAT YOU MAKE NECESSARY CHANGES IN YOUR APP TO MAKE IT WORK PROPERLY AS PER THE BEST PRACTICES FOLLOWED OR ASKED BY ANDROID.

我希望这可能有助于解决您的问题。

I hope this might help to solve your problem.

这篇关于android oreo的后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆