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

how to create a PERMANENT background service on android

我在试图在 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"/>

我在 Application onCreate()

开始服务
    if (MyService.getInstance() == null) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

服务:

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;

    }

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

那么为什么我在某些随机情况下会出现 nullpointerexception?

有人甚至告诉我执行以下代码以强制 android 到 "restart" 服务

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

有人能帮帮我吗...这个问题让我压力很大

我的应用程序每天有 1000 多个用户,其中大约 10% "find a way" 在使用该服务时出现 nullpointerexception

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

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

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

您可能需要考虑 JobScheduler 框架。

答案是:不能! 当前 Android 100% 阻止开发人员提供永久服务。
过去有可能(但不完全可靠)达到 KitKat。

最接近永久服务的方法是在启动服务时使用 startForeground() method from inside the service and startServiceForeground() method(在 API 26 及以上)使用前台服务。
但即便如此,该服务仍会在某个时候被杀死。

备选方案是:

  • 使用 WorkManager 执行 "once in a while" 任务(根据您的描述,这听起来像是一个可行的选择)
  • 用户 AlarmManager 在特定时间执行任务
  • 用户 FCM(推送消息)执行服务器通知时执行的任务。