我正在开发用于用户跟踪的前台位置服务。每次位置更新时,该服务都会向 API 发送请求以更新当前位置。问题是,当应用程序置于后台或屏幕被锁定时,服务会在一段时间后停止发送请求(通常在 1 分钟左右,在此期间发送大约 10 个请求)。应用程序恢复后,服务再次开始工作,最小化/锁定屏幕后,场景会重复。
在里面onStartCommand我尝试返回多个启动选项,但都不起作用。我已经在 Android 10 和 11 上测试了该应用程序。
服务源码:
class LocationService: Service() {
@Inject
lateinit var apiService: ApiService
private val composite = CompositeDisposable()
private var locationManager: LocationManager? = null
private var locationListener: LocationListener? = null
override fun onBind(p0: Intent?): IBinder? =
null
val NOTIFICATION_CHANNEL_ID = "location_tracking"
val NOTIFICATION_CHANNEL_NAME = "Location tracking"
val NOTIFICATION_ID = 101
var isFirstRun = true
@SuppressLint("MissingPermission")
override fun onCreate() {
App.component.inject(this)
setupLocationListener()
locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?
val criteria …Run Code Online (Sandbox Code Playgroud)