1

在 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) 运行活动并按主页按钮返回启动器。

3) 当服务被终止并在多任务窗口中删除应用程序时

我最想要的是在案例 3) 中工作,但在上述任何情况下,我想要的服务都没有重新安排。

我错过了什么?

4

1 回答 1

-1

在应用程序被杀死时在 Oreo 中使用后台线程时,您需要将服务作为前台服务启动。是相同的细节。本质上,显示通知以使用户知道您的应用程序正在尝试在后台执行某些操作。希望它可以帮助你。

于 2018-10-18T11:46:53.587 回答