【问题标题】:Kotlin: How to call JobIntentService from Fragment?Kotlin:如何从 Fragment 调用 JobIntentService?
【发布时间】:2021-06-01 01:51:19
【问题描述】:

我正在创建 GPS 跟踪应用。所以我需要在后台(或前台?)运行这个应用程序。在 Fragment (FirstClass) 中点击“开始”按钮时如何调用 JobIntentService (SecondClass) 类?

例如,我查看了 this code - 但我仍然不明白如何从 Fragment 类调用 JobIntentService 类。

我尝试这样调用 SecondClass (source):

val contentIntent = Intent(context, SecondClass::class.java)

但它以这个错误结束:java.lang.RuntimeException: Unable to instantiate service com...SecondClass: java.lang.InstantiationException: java.lang.Class<com...SecondClass> cannot be instantiated

【问题讨论】:

    标签: kotlin fragment jobintentservice


    【解决方案1】:
    context?.run {
        JobIntentService.enqueueWork(
            applicationContext,
            SecondClass::class.java,
            100,// your id
            Intent(applicationContext, SecondClass::class.java)
        )
    }
    

    不要忘记以这种方式在清单中声明服务

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

    【讨论】:

    • 谢谢!看起来不错,但有一个错误:Unresolved reference: enqueueWork。我发现了这个:stackoverflow.com/a/54207056/15309916 - 但SecondClass.enqueueWork 也不起作用。
    • @djlj 是的,是的。尝试通过JobIntentService.enqueueWork
    • 是的! Gradle Build 现在可以工作,但是当我点击“开始”并出现以下错误时应用程序崩溃:Scheduled service ComponentInfo{com...SecondClass} does not require android.permission.BIND_JOB_SERVICE permission。我在清单中使用了很长时间的BIND_JOB_SERVICE。我尝试删除它 - 没有成功。
    • @djlj 在最后看到我的答案
    • 我用的是android:permission="ACCESS_BACKGROUND_LOCATION|ACCESS_COARSE_LOCATION|ACCESS_FINE_LOCATION|ACCESS_LOCATION_EXTRA_COMMANDS|ACCESS_MEDIA_LOCATION|CONTROL_LOCATION_UPDATES|INSTALL_LOCATION_PROVIDER|LOCATION_HARDWARE|android.permission.BLUETOOTH",我把它改成了android:permission="android.permission.BIND_JOB_SERVICE"。新错误:Unable to instantiate service com...SecondClass: java.lang.InstantiationException: java.lang.Class&lt;com...SecondClass&gt; cannot be instantiated :'(
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多