在待机模式约 1 小时后,前台应用程序被 OS 杀死

Foreground app killed by OS after ~ 1 hour in standby mode

我有一个应用程序,要求用户登录,然后显示 activity。登录时还会启动一项服务,该服务使用位置管理器来跟踪他的当前位置。 一切正常,直到应用程序处于待机模式(屏幕关闭后台应用程序超过 1 小时)

我怎样才能避免这种情况?

据我所知,如果我有一个前台服务 运行,OS 应该不会终止该应用程序。那么我做错了什么? OS 我正在测试的是 Oreo

登录时启动服务:

startService(intent);

服务:

public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

@Override
    public void onCreate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification notification = updateNotificationContent(); // the service notification
            if (notification == null)
                stopSelf();
            startForeground(id, notification);
        }

我在 activity 的功能上添加了日志记录和服务来检测何时发生这种情况但是当这种行为发生时日志永远不会被写入(当然它在我销毁应用程序时在正常情况下进入)

如果你有活跃的服务,你应该不会有这个问题。

参见here

A foreground process is one that is required for what the user is currently doing. Various application components can cause its containing process to be considered foreground in different ways. A process is considered to be in the foreground if any of the following conditions hold:

It is running an Activity at the top of the screen that the user is interacting with (its onResume() method has been called). It has a BroadcastReceiver that is currently running (its BroadcastReceiver.onReceive() method is executing). It has a Service that is currently executing code in one of its callbacks (Service.onCreate(), Service.onStart(), or Service.onDestroy()).

There will only ever be a few such processes in the system, and these will only be killed as a last resort if memory is so low that not even these processes can continue to run. Generally, at this point, the device has reached a memory paging state, so this action is required in order to keep the user interface responsive.

看看这个answer。 杀人时检测是否在前台。

根据Android Processes and Application Lifecycle Documentation

[...] An unusual and fundamental feature of Android is that an application process's lifetime is not directly controlled by the application itself. Instead, it is determined by the system through a combination of the parts of the application that the system knows are running, how important these things are to the user, and how much overall memory is available in the system.

前台服务 应该位于重要性层次结构 的顶部,它决定了内存不足时应终止哪些进程。

然而,

[...] Services that have been running for a long time (such as 30 minutes or more) may be demoted in importance to allow their process to drop to the cached LRU list described next. This helps avoid situations where very long running services with memory leaks or other problems consume so much RAM that they prevent the system from making effective use of cached processes.

所以你不能确定进程没有被操作系统杀掉

一些对我有用的预防措施:

  • 将应用程序添加到 "protected app" 的列表中(在某些手机上可用,例如 Huaweii)。
  • 限制前台服务中资源的使用。例如,执行周期性蓝牙扫描的进程比频繁使用 gps 的进程被杀死的可能性要小得多。
  • 避免向用户发送过多通知,最重要的是不要使用 PowerManager.Wake 锁定