当销毁应用程序时,JobIntentService被销毁

Sal*_*500 9 android kotlin

作为来自Android开发人员JobIntentService在Android O或更高版本上运行时,工作将作为作业通过分派JobScheduler.enqueue.在旧版本的平台上运行时,它将使用Context.startService.

在我的情况下,我正在学习JobIntentService,在我的情况下,我有一个计时器,每秒运行一次并显示当前的日期和时间,但当我的应用程序被销毁时,JobIntentService也被销毁,如何在销毁应用程序时运行它

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()
       })
   }
}
Run Code Online (Sandbox Code Playgroud)

表现

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
....... >
<service android:name=".service.OreoService"
            android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
Run Code Online (Sandbox Code Playgroud)

MainActivity(按下按钮时服务开始)

startServiceBtn.setOnClickListener({
            val intent = Intent()
            intent.putExtra("val","testing service")
            OreoService.enqueueWork(this,intent)
        })
Run Code Online (Sandbox Code Playgroud)

Com*_*are 12

我正在学习JobIntentService,在我的情况下,我有一个每秒运行一次的计时器,并显示当前的日期和时间

这不是一个合适的用途JobIntentService(或几乎任何其他东西,就此而言).

当我的应用程序被销毁时,JobIntentService也会被销毁

关键JobIntentService是要做一些工作 - 一些磁盘I/O,一些网络I/O等 - 然后消失.它不是无限期地做某事,它适合启动异步工作,而你正试图做到这两点.一旦onHandleWork()结束,服务就会消失,您的流程可以在此之后的任何时间点终止,这将阻止您的流程Timer.

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

欢迎您使用前景Service,而不是IntentServiceJobIntentService.返回START_STICKYonStartCommand()询问的Android重新启动您的服务,如果你的进程被终止(例如,由于内存不足).即使这可能被用户终止,但它是用户的设备,而不是你的设备,因此用户可以做任何用户想要的事情.