在Android Oreo中,我想创建一个定期更新网络数据的服务。
class NetworkJobService : JobService() {
override fun onStopJob(p0: JobParameters?): Boolean {
jobFinished(p0,true)
return true
}
override fun onStartJob(p0: JobParameters?): Boolean {
//Average working time 3 to 5 minutes
NetworkConnect.connect()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doFinally {
jobFinished(p0,true)
}
.subscribe({result->
// Writes the parameters to the cache with the current time.
Cache.write("result : $result")
},{e->
// Writes the parameters to the cache with the current time.
Cache.write(e)
})
return true
}
}当您运行MainActivity时,此服务将在计划中注册。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
jobSchedule()
button.setOnClickListener { readLog() }
}
val interval = 1000 * 60 * 15L
private fun jobSchedule(){
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val jobInfo = JobInfo.Builder(3,
ComponentName(this, NetworkJobService::class.java))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPeriodic(interval)
.build()
jobScheduler.schedule(jobInfo)
}
private fun readLog(){
//The log file is read line by line.
Cache.read()
.reversed()
.toObservable()
.subscribe({ text->
Log.i("Service Log",text)
},{
})
}
}但是,当我读取日志文件并检查结果时,服务仅在MainActivity运行时运行。换句话说,它没有被重新安排。
1)运行活动并关闭设备屏幕
2)运行活动并按Home按钮返回到启动器。
3)服务终止,app在多任务窗口被删除
我最想要的是在情况3)下工作,但在上面的任何一种情况下,我想要的服务都没有重新安排。
我错过了什么?
发布于 2018-10-18 19:46:54
在Oreo中使用后台线程时,当应用程序处于killed状态时,您需要将服务作为前台服务启动。Here的细节也是一样的。本质上,显示一个通知,让用户意识到你的应用程序正试图在后台做一些事情。希望能对你有所帮助。
https://stackoverflow.com/questions/52865491
复制相似问题