我正在尝试在我的 android 应用程序中做一些后台工作。正如网络建议的那样,我正在使用 JobScheduler
来执行此操作。
作业有时会触发 5-15 次 而不是一次。有时他们从不开火。我的测试设备在 5.1.1 和 7.0 上运行。牛轧糖的火力远低于 Lollipop 的火力。
这就是我启用作业的方式(5 秒间隔仅用于测试目的):
fun enableTasks() {
val jobScheduler = App.getContext().getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
if (PreferenceDao.getInstance().shouldUpdateJob()) jobScheduler.cancelAll()
scheduleJob(jobScheduler, MoniInfoJob.getJob())
scheduleJob(jobScheduler, QueueJob.getJob())
scheduleJob(jobScheduler, MontageOrderUpdateJob.getJob())
PreferenceDao.getInstance().setJobUpdated()
}
private fun scheduleJob(jobScheduler: JobScheduler, jobInfo: JobInfo) {
val jobExists = jobScheduler.allPendingJobs.any { it.id == jobInfo.id }
if (!jobExists) jobScheduler.schedule(jobInfo)
}
这三份工作看起来都差不多,所以我只发一份:
JobService
class QueueJob : JobService() {
override fun onStartJob(jobParameters: JobParameters?): Boolean {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, p1: Intent?) {
unregisterBroadcastReceiver(this)
jobFinished(jobParameters, false)
}
}
registerBroadcastReceiver(receiver)
MainController.startQueueService()
return true;
}
override fun onStopJob(jobParameters: JobParameters): Boolean {
Log.d(MontageOrderUpdateJob.TAG, "onStopJob")
return false;
}
private fun registerBroadcastReceiver(receiver: BroadcastReceiver) {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter(JOB_FINISHED))
}
private fun unregisterBroadcastReceiver(receiver: BroadcastReceiver) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
}
companion object {
val TAG = QueueJob::class.java.name
val jobId: Int = 2
val JOB_FINISHED = TAG + "_finished"
fun getJob(): JobInfo {
val builder = JobInfo.Builder(jobId, ComponentName(App.getContext(), TAG))
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
builder.setPeriodic(5000L)
builder.setPersisted(true)
return builder.build()
}
}
}
和JobIntentService
:
class QueueService : JobIntentService() {
private val TAG = QueueService::class.java.name
override fun onHandleWork(intent: Intent) {
try {
Log.d(TAG, "Jobservice started")
TimerecordQueue().workThroughQueue()
DangerAllowanceQueue().workThroughQueue()
ProjektEndQueue().workThroughQueue()
PhotoUploadQueue().workThroughQueue()
} finally {
sendFinishedBroadcast()
}
}
private fun sendFinishedBroadcast() {
val jobFinishedIntent = Intent(QueueJob.JOB_FINISHED)
LocalBroadcastManager.getInstance(this).sendBroadcast(jobFinishedIntent)
}
}
我曾经遇到过类似的问题。我当时的问题是我没有检查预先存在的时间表。您是否也需要这样做?
我是一名优秀的程序员,十分优秀!