【问题标题】:why is IntentService's onStartCommand method called every time the service handles a new intent为什么每次服务处理一个新意图时都会调用 IntentService 的 onStartCommand 方法
【发布时间】:2019-12-24 14:50:33
【问题描述】:

我有一项服务每 1-3 秒左右接收一次位置更新。该服务是使用挂起的意图从主要活动启动的:

    mFusedLocationClientFast.requestLocationUpdates(mLocationRequest, getPendingIntent());

其中getPendingIntent() 是一个方法,它定义了我的IntentServicehandleIntent() 中处理的操作

然而,我注意到一件奇怪的事情是,每次IntentService 处理handleIntent() 中的位置更新时,它总是紧接着调用同一服务的onStartCommand()

有谁知道为什么每次服务处理意图时都需要调用onStartCommand()? 谢谢

【问题讨论】:

    标签: android android-pendingintent intentservice location-updates


    【解决方案1】:

    IntentService 简单来说就是在工作线程上运行onHandleIntent 的服务。服务接收意图的机制是onStartCommand

    在 IntentService 中,onStartCommand 方法将意图转发给 onHandleIntent 方法。

    代码是here

    令我困惑的是,IntentService 的设计者并没有实现 onStartCommandonStart final

    【讨论】:

    • 知道了......所以每次 onHandleIntent 运行完成时,服务都会停止并在每次新位置进入时重新创建。我猜 IntentService 可能不是这项任务的最佳机制.. .我正在尝试制作类似于跑步跟踪器的东西,您可以在其中全天动态查看您的位置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    相关资源
    最近更新 更多