SDK 中的 Android 服务问题 >= 26

Issue with Android Service in SDK >= 26

我正在创建一个应用程序,即使应用程序从进程中或在后台被终止,它也会向用户发送通知。实际上,在 SDK >= 26 的 Android 版本中,我正在使用前台服务。 为了显示通知,我有一个服务 (DatasNotification),它启动一个 asyncTask (HttpRequest) 来发出 http 请求,条件结束时的 asynctask 启动一个显示通知的新服务。 当我的应用程序进入后台时,我收到一条系统通知:我的应用程序正在耗尽电池电量。 在我的分析过程中,我了解到这个系统通知是由 DatasNotification 服务生成的。

这是我的 DatasNotification 代码:

@Override
public void onCreate() {
    super.onCreate();
    Fabric.with(this, new Crashlytics());
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(1, new Notification());
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    new HttpRequest(getApplicationContext(), 0).execute();
    return START_STICKY;
}

sdk >= 26 中的后台服务运行有什么解决方案吗?

这是奥利奥 (API26-27) 的一项特定功能,用于在某个应用程序处于 运行 后台服务时显示“[应用程序] 正在使用电池”的系统通知。您您会注意到,您不会在设备 运行 P (API28) 或 Android 10 (API 29) 中收到相同的警告,因为该警告是 removed/disabled 完全。我不认为您可以在您的应用程序中更改任何内容以防止该警告显示在 Oreo 设备中,除非您可以完全摆脱您的(后台)服务。

用户可以通过执行以下操作来禁止显示该警告:

  1. Unlock your device running Android Oreo
  2. Swipe down on the notification shade, fully exposing the “using battery” notification
  3. Long press on the notification until it changes and shows a toggle
  4. Tap on the toggle, making sure that it’s grayed out
  5. Select Done to disable the “using battery” notification

(source)