在我的情况下,我正在学习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()
       })
   }
} 
 表现
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
....... >
<service android:name=".service.OreoService"
            android:permission="android.permission.BIND_JOB_SERVICE"/>
</application> 
 MainActivity(按下按钮时服务开始)
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
这不适合JobIntentService(或者其他任何事情).
when my app get destroyed the JobIntentService also get destroyed
JobIntentService的目的是做一些工作 – 一些磁盘I / O,一些网络I / O等 – 然后消失.它不是无限期地做某事,它不适合启动异步工作,而你正试图做到这两点.一旦onHandleWork()结束,服务就会消失,您的进程可以在此之后的任何时间点终止,这将停止您的Timer.
How can i run it when app is destroyed
您可以使用前台服务,而不是IntentService或JobIntentService.如果您的进程被终止(例如,由于内存条件较低),请从onStartCommand()返回START_STICKY以要求Android重新启动您的服务.即使这可能被用户终止,但它是用户的设备,而不是你的设备,因此用户可以做任何用户想要的事情.