首页 > 解决方案 > 服务每分钟发送一次位置,即使应用程序在后台或系统重新启动

问题描述

我需要创建一个应用程序来跟踪用户位置。必须每隔一分钟将位置发送到服务器(延迟不是问题)。但是我在设置一个永远存在的任务/服务时遇到了很多麻烦(即使我关闭了我的应用程序或重新启动系统)

*获取“最后一个位置”不是问题,唯一的问题是有一个“永远”运行的任务/服务)

我尝试使用服务。但是android,从Marshmallow(我猜)版本开始,可以随时杀死后台应用程序和服务(这是一个避免许多应用程序创建后台服务/任务并消耗过多电池和内存的功能)。

现在我正在尝试使用新的 androidx“Worker”,因为我想构建一个具有 minSdk=16 和当前 maxSdk(29) 的应用程序。但现在我面临两个问题: - Worker 无法运行更多超过 10 分钟(所以我不能创建一个永远持续的 Worker)。- 我可以创建一个 PeriodicWorkRequest,但重新安排 Worker 的最短时间是 15 分钟(我需要每隔一分钟发送一次位置)。

我尝试使用 OneTimeWorkRequest 并重新安排自己,但在系统重新启动后它不起作用。

有什么想法/解决方案吗?

主要活动中的第一个时间表:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        WorkManager.getInstance(this).enqueue(
            OneTimeWorkRequest.Builder(WorkerTest::class.java).build()
        )
    }
}

工人(在“doWork”的初始化时重新安排自己,延迟一分钟):

public class WorkerTest(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        WorkManager.getInstance(applicationContext).enqueue(
            OneTimeWorkRequest.Builder(this::class.java).setInitialDelay(1, TimeUnit.MINUTES).build()
        )

        //TODO get and send location

        return Result.success()
    }

}

标签: androidserviceandroidx

解决方案


Well, I will tell you an idea:

1.Run your service on foreground/background: You can use a foreground service, this service is intended to run always, it is attached to a notification bar and if the user dismisses the notification the service will die, android will never let you run a service forever if the user is not aware of it.

2.Run your service after a Reboot: In order to run this service after a reboot, you will need to use a broadcast receiver for that system event. So when the reboot finishes you need to call your foreground service.

This is the road map that you have to follow. Remember that you will need user permissions for the location updates. And Depending on the SDK version the code, methods, and special needs on each one will be different.


推荐阅读