JobScheduler问题 - 多次激活JobsService

时间:2017-12-04 14:37:30

标签: android android-jobscheduler

我试图在我的Android应用程序中做一些后台工作。正如网络建议我使用JobScheduler这样做。

这些工作有时会发射 5-15次而不是一次。有时他们永远不会开火。 我的测试设备运行在5.1.1和7.0上。那个用牛轧糖的方式比那个用棒棒糖的方式少。

这是我启用作业的方式(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)
}
}

1 个答案:

答案 0 :(得分:0)

我曾遇到过类似的问题。我的问题是我没有检查预先存在的时间表。 难道你需要做同样的事吗?