问题描述
我正在创建 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
解决方法
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" />