从Android Developer JobIntentService开始,当在Android O或更高版本上运行时,工作将通过101作为作业(job)分派.当在旧版本的平台上运行时,它将使用102.

在我的例子中,我正在学习100,在我的例子中,我有一个计时器,它每一秒运行一次,并显示当前日期和时间,但是当我的应用程序被销毁时,100也会被销毁,当应用程序被销毁时,我如何运行它

JobIntentService

class OreoService : JobIntentService() {

    private val handler = Handler()

    companion object {
        private const val JOB_ID = 123

        fun enqueueWork(cxt: Context, intent: Intent){
            enqueueWork(cxt,OreoService::class.java,JOB_ID,intent)
        }
    }

    override fun onHandleWork(intent: Intent) {

        toast(intent.getStringExtra("val"))

        Timer().scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                println(Date().toString())
            }

        }, Date(),1000)

    }

    override fun onDestroy() {
        super.onDestroy()
        toast("Service Destroyed")
    }

   private fun toast(msg: String){

       handler.post({
           Toast.makeText(applicationContext,msg,Toast.LENGTH_LONG).show()
       })
   }
}

Manifest

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
....... >
<service android:name=".service.OreoService"
            android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>

MainActivity (When button is pressed the service get started)

startServiceBtn.setOnClickListener({
            val intent = Intent()
            intent.putExtra("val","testing service")
            OreoService.enqueueWork(this,intent)
        })

推荐答案

i am learning JobIntentService and in my case i have a timer that run every one second and display the current date and time

That is not a suitable use for JobIntentService (or pretty much anything else, for that matter).

when my app get destroyed the JobIntentService also get destroyed

The point of JobIntentService is to do a little bit of work — some disk I/O, some network I/O, etc. — and then go away. It is not for doing something indefinitely, and it is not suitable for starting asynchronous work, and you are trying to do both. Once onHandleWork() ends, the service goes away, and your process can be terminated at any point in time after that, which will stop your Timer.

当应用程序被销毁时,我如何运行它

欢迎使用前景Service,而不是IntentServiceJobIntentService.如果进程终止(例如,由于内存不足),请从onStartCommand()返回START_STICKY,请求Android重新启动服务.即使用户可能会终止该操作,但它是用户的设备,而不是您的设备,因此用户可以做用户想要做的任何事情.

Kotlin相关问答推荐

如何在Jetpack Compose中从领域查询中读取数据?

在Mapstruct中重用@映射定义

某些公共函数显然不能在类实例上访问;Klaxon示例

如何编写带有依赖项的自定义Kotlin串行化程序?

我需要后台工作才能使用卡夫卡的消息吗?

使用 kotlin 流删除 map 中具有某些相似性的值

在jetpack compose中将默认方向设置为横向?

如何在 kotlin 中使用带有泛型的密封类

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

Kotlin:内部类如何访问在外部类中声明为参数的变量?

将 jetpack compose 添加到现有元素

包括登录Elvis operator?

面临一些未知问题一些后端jvm内部错误

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

修改扩展函数中的this

在android java类中使用Kotlin扩展

Kotlin 中内部可见性修饰符的范围

在 IntelliJ Idea 中未为 Kotlin @ConfigurationProperties 类生成 spring-configuration-metadata.json 文件

var str:String是可变的还是不可变的?

从 Kotlin 访问 Integer.class