java - 如何在主线程中不执行代码的情况下保持粘性服务存活?

标签 java android service event-handling

我的应用程序有一项服务,即使在用户关闭它(将其滑开)后也需要保持 Activity 状态。我的服务在并行线程中每秒打印一次日志消息。

虽然它确实返回 START_STICKY,但只要用户关闭应用程序,它就会终止。这是我的 onStartCommand 方法:

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

    super.onStartCommand(intent, flags, startId);
    instance = this;
    Log.i("Service", "started");
    new Thread(() -> {
        int i = 0;
        while (true) {
            Log.i("Service", "#" + ++i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();

    start_recording(null);


    return START_STICKY;
}

我也在 list 中声明了它:

<service
    android:name=".MyService"
    android:stopWithTask="false"
/>

如何防止系统在应用程序退出时杀死线程?没有其他 SO 帖子为我提供了有效的解决方案。

最佳答案

基于documentation :

When an app goes into the background, it has a window of several minutes in which it is still allowed to create and use services. At the end of that window, the app is considered to be idle. At this time, the system stops the app's background services, just as if the app had called the services' Service.stopSelf() methods.

Android O 开始,操作系统对后台服务的执行自由度施加了一些限制。应用程序退出 X 分钟后,服务将终止,就像调用了 stopSelf() 一样。如果您仍想继续,则需要使用 ForegroundService,但需要考虑对电池生命周期的影响。如果您执行 CPU 密集型工作,那么使用 ForegroundService 将无济于事。

可以引用我在这个SO的回答了解更多详情。

关于java - 如何在主线程中不执行代码的情况下保持粘性服务存活?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125611/

相关文章:

Java 查找文件名和扩展名的开头

java - 方法返回错误

java - 在Java中获取存储在PNG图像中的文本

java - MPAndroidChart 如何获取三次折线图上所有点的列表

android - 我可以在前台服务中使用 Android Beacon 库吗,即使是在 Android 8 (Oreo) 上?

android - 在 Android 中解锁设备屏幕时启动服务

java - Android Studio 3 是否支持 Java 9 进行 Android 开发?如果支持,支持 Java 9 的哪些特性?

android - 如何从国家代码中获取国家的全名?

android - 将 Bitmap 转换为 Drawable 什么都不显示

mvvm - 将服务传递给 MainViewModel - 我应该使用依赖注入(inject)容器吗?