从Android Developer JobIntentService开始,当在Android O或更高版本上运行时,工作将通过101作为作业(job)分派.当在旧版本的平台上运行时,它将使用102.
在我的例子中,我正在学习100,在我的例子中,我有一个计时器,它每一秒运行一次,并显示当前日期和时间,但是当我的应用程序被销毁时,100也会被销毁,当应用程序被销毁时,我如何运行它
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()
})
}
}
Manifest
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
....... >
<service android:name=".service.OreoService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
MainActivity (When button is pressed the service get started)
startServiceBtn.setOnClickListener({
val intent = Intent()
intent.putExtra("val","testing service")
OreoService.enqueueWork(this,intent)
})