android – JobIntentService被破坏,当app被销毁时

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()
       })
   }
}

表现

<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重新启动您的服务.即使这可能被用户终止,但它是用户的设备,而不是你的设备,因此用户可以做任何用户想要的事情.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...