gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:37:51 36 4
gpt4 key购买 nike

来自安卓开发者JobIntentService在 Android O 或更高版本上运行时,工作将通过 JobScheduler.enqueue 作为作业分派(dispatch)。在旧版本平台上运行时,将使用 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()
})
}
}

list

<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 等等——然后离开。 not 用于无限期地做某事,它 not 适合启动异步工作,而您正在尝试同时做这两种工作。一旦 onHandleWork() 结束,服务就会消失,并且您的进程可以在之后的任何时间点终止,这将停止您的 Timer

How can i run it when app is destroyed

欢迎您使用前台 Service,而不是 IntentServiceJobIntentService。如果您的进程终止(例如,由于内存不足),则从 onStartCommand() 返回 START_STICKY 以要求 Android 重新启动您的服务。即使这样也可能被用户终止,但它是用户的设备,而不是您的设备,因此用户可以为所欲为。

关于android - JobIntentService 被销毁,当应用程序被销毁时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49955839/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com