如何在android上创建一个永久的后台服务

Raf*_*ima 6 android android-service android-background

我有一个噩梦试图在 android 上创建一个永久运行的简单后台服务。

此服务将执行一些后台任务,例如池用户社交媒体和显示通知,因此它只需要一次用户交互(登录)之后应该能够永远运行直到日子结束......

但它没有发生

这是我的清单:

<service
        android:name=".service.MyService"
        android:description="@string/serviceDescription"
        android:directBootAware="false"
        android:enabled="true"
        android:exported="false"
        android:icon="@drawable/ic_logo"
        android:label="@string/serviceLabel"/>
Run Code Online (Sandbox Code Playgroud)

我开始服务 Application onCreate()

    if (MyService.getInstance() == null) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }
Run Code Online (Sandbox Code Playgroud)

服务:

public void onCreate() {
        super.onCreate();
        this.workDone = 0;

        this.workerMap = new HashMap<User.UserData, Worker>(3);
        this.listeners = new HashMap<Worker, Worker.WorkerListener>(3);
        this.usernames = new HashMap<APIFacade, List<String>>(3);

        this.threadPool = Executors.newFixedThreadPool(3);
        INSTANCE = this;

    }
Run Code Online (Sandbox Code Playgroud)

在我的代码中绝对没有我调用 STOPSERVICE 或 STOPSELF

那么为什么在某些随机情况下我会得到 nullpointerexception 呢?

有人甚至告诉我执行以下代码以强制 android“重新启动”服务

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我...我对这个问题感到非常紧张

我的应用程序每天有超过 1000 名用户,其中大约 10% 的用户在使用该服务时“找到了一种方法”使 nullpointerexception

Cod*_*lan 5

Oreo(或者是牛轧糖?)中后台服务的很多内部结构都发生了变化。我会熟悉Android文档:

https://developer.android.com/about/versions/oreo/background

https://developer.android.com/training/best-background

您可能需要考虑该JobScheduler框架。