本文介绍了Kotlin:如何从Fragment调用JobIntentService?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建GPS跟踪应用程序.因此,我需要在后台(或前台?)运行此应用程序.当我点击按钮开始"时,如何调用JobIntentService(SecondClass)类.在Fragment(FirstClass)中?

I'm creating GPS tracking app. So I need to run this app at background (or foreground?). How can I call JobIntentService (SecondClass) class when I tap to button "Start" in Fragment (FirstClass)?

例如,我查看了此代码-但我仍然不了解如何从Fragment类调用JobIntentService类.

I looked for example at this code - but still I don't understand how to call JobIntentService class from Fragment class.

我尝试这样调用SecondClass():

I try to call SecondClass like this (source):

val contentIntent = Intent(上下文,SecondClass :: class.java)

但是它以以下错误结尾: java.lang.RuntimeException:无法实例化服务com ... SecondClass:java.lang.InstantiationException:java.lang.Class< com ... SecondClass>无法实例化

But it ends with this error: java.lang.RuntimeException: Unable to instantiate service com...SecondClass: java.lang.InstantiationException: java.lang.Class<com...SecondClass> cannot be instantiated

推荐答案

context?.run {
    JobIntentService.enqueueWork(
        applicationContext,
        SecondClass::class.java,
        100,// your id
        Intent(applicationContext, SecondClass::class.java)
    )
}

别忘了以清单方式声明服务

Don't forget to declare service in manifest in such way

<service
    android:name=".SecondClass"
    android:permission="android.permission.BIND_JOB_SERVICE" />

这篇关于Kotlin:如何从Fragment调用JobIntentService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 13:26