【问题标题】:Intent service can't be started in backgroundIntent 服务无法在后台启动
【发布时间】:2019-12-04 20:03:57
【问题描述】:

在我的 android 应用程序中,我想检测活动从 stillwalking 的变化并开始跟踪位置,无论应用程序的状态如何(在后台或完全关闭) )。

我能够通过将应用程序设置为前台服务(显示通知)来创建在后台运行的位置跟踪服务,但我无法根据活动检测开始跟踪。

这是IntentService的代码片段,它应该在接收到检测到活动转换的意图后启动位置跟踪服务:

class ActivityDetectionIntent : IntentService(TAG) {
    override fun onHandleIntent(intent: Intent?) {
        val i = Intent(this@ActivityDetectionIntent, LocationTracking::class.java)
        if (Build.VERSION.SDK_INT >= 26) {
            startForegroundService(i)
            // this followed by foregroundService call in LocationTracking service
        } else {
            startService(i)
        }
    }
    // ...
}

这是我收到的错误消息:

2019-12-04 19:57:59.797 3866-15015/? W/ActivityManager:后台启动不 允许:服务意图 { cmp=com.anatoliymakesapps.myapplication/.ActivityDetectionIntent (有附加功能)} 到 com.anatoliymakesapps.myapplication/.ActivityDetectionIntent 从 pid=-1 uid=10377 pkg=com.anatoliymakesapps.myapplication startFg?=false

我想知道我是否遗漏了一些明显的东西,或者整个方法是错误的,我需要尝试其他方法?任何实现预期结果的建议都将受到赞赏。

我尝试将IntentService 更改为JobIntentService,但没有任何区别,错误看起来一样。

【问题讨论】:

  • 你在清单中有这个吗
  • 是的,我在清单中有这个,ActivityDetectionIntent 和 LocationTracking Services 也在清单中。

标签: android geolocation android-pendingintent background-service activity-transition


【解决方案1】:

原来intent service不能直接启动,但是借助broadcast receiver可以间接实现。

这是我用的,而不是IntentService

class ActivityTransitionBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        Log.i(TAG, "got activity transition signal")
        val i = Intent(context, LocationTrackingService::class.java)
        if (Build.VERSION.SDK_INT >= 26) {
            startForegroundService(context, i)
        } else {
            context.startService(i)
        }
    }

    companion object {
        private val TAG = ActivityTransitionBroadcastReceiver::class.java.simpleName
    }

}

清单:

        <receiver android:name=".ActivityTransitionBroadcastReceiver"  android:exported="true" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多