gpt4 book ai didi

android - JobScheduler 的问题 - JobsService 多次触发

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:35 25 4
gpt4 key购买 nike

我正在尝试在我的 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)
}
}

最佳答案

我曾经遇到过类似的问题。我当时的问题是我没有检查预先存在的时间表。您是否也需要这样做?

关于android - JobScheduler 的问题 - JobsService 多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47635731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com