首页 > 解决方案 > Running a Service indefinitely

问题描述

I am migrating my Android App to target Android Oreo. I am running a service which should run indefinitely to perform a particular task.

The running of the service is to perform a particular task with the users' consent of course.

Till now my app has been targeting Android Marshmallow and the service is working fine and is running also fine.

This is my service

public class MyService extends Service {

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    private void DoSomething() {
     //Some Code keep watching something.       
    }


    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {

        DoSomething();

        return  Service.START_STICKY;
    }


}

And this is how I am Starting the service from an Activity

startService(new Intent(getBaseContext(), MyService.class));

Now my problem is that when I target my app to Android Oreo then the service is not running and hence the function which I am trying to achieve is not working.

But whereas If my App target Android Marshmallow everything is working fine with the exact same code.

Can anyone help me to run a Serice indefinitely in Android App targeting Android Oreo would be appreciated?

标签: javaandroidandroid-serviceandroid-8.0-oreoandroid-jobscheduler

解决方案


在 Android Oreo+ 中,后台服务受到严格限制。要运行您的代码,您有两个选择:使用前台服务或使用 JobScheduler/ WorkManager API 之类的东西。

但它们都不会无限期地工作,并且 WorkManager 仅适用于可延迟的任务。这是我们无能为力的事情。


推荐阅读