【发布时间】:2018-04-21 12:36:34
【问题描述】:
来自 android developer JobIntentService 在 Android O 或更高版本上运行时,工作将作为作业通过 JobScheduler.enqueue 分派。在旧版本平台上运行时,它将使用 Context.startService。
在我的情况下,我正在学习 JobIntentService,在我的情况下,我有一个计时器,每秒钟运行一次并显示当前日期和时间,但是当我的应用程序被破坏时 @ 987654325@ 也被销毁了,应用程序被销毁时如何运行它
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)
})
【问题讨论】: