
在我的情况下,我正在学习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 – JobIntentService被破坏,当app被销毁时全部内容,希望文章能够帮你解决android – JobIntentService被破坏,当app被销毁时所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)