Android之JobSchedule的使用

setPeriodic的最小执行间隔,从Android7.0后,这个设置最少也是15分钟了,就是你设置的再短也是按15分钟执行。
在获取执行间隔时,会先比较最小间隔时间和设置的间隔时间,取其中大的那个。所以setPeriodic设置时间小于15分钟是不会生效的。

flexMillis参数是用来设置周期任务执行的活动时间的,这意味着JobScheduler规划的任务不是在精确的时间执行的。并且这个时间也是有最小值的,系统默认5分钟。

setMinimumLatency和setOverrideDeadline不能同setPeriodic一起使用,会引起报错。

import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import java.lang.Exception
import java.util.concurrent.TimeUnit
 

class PeriodicJobService: JobService() {
 
 
    private suspend fun Count(): Flow<Int> {
        return flow {
            for(i in 200..210){
                delay(100)
                emit(i)
            }
        }
    }
 
 
    override fun onStartJob(p0: JobParameters?): Boolean {
        val resScope = CoroutineScope(Job())
        resScope.launch {
            try {
                Count().flowOn(Dispatchers.IO).collect {
                    Log.i(TAG, "collect $it")
                }
                Log.i(TAG, "jobFinished")
            }catch (e: Exception){
                e.printStackTrace()
                Log.e(TAG, e.message.toString())
            }
        }
        startScheduler(this)
        return false
    }
 
 
    override fun onStopJob(p0: JobParameters?): Boolean = false
 
 
    companion object {
 
 
        var TAG: String = "taskjob"
        var JOBID : Int = 100
        var InterValTime :Long = 10000
        private var jobScheduler: JobScheduler? = null
        private var jobInfo: JobInfo? = null
 
 
        fun startScheduler(context: Context) {
            jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            cancelScheduler()
            if (jobInfo == null) {
                jobInfo = JobInfo.Builder(JOBID, ComponentName(context, PeriodicJobService::class.java))
                    .setMinimumLatency(InterValTime) // 最小为10秒
                    .build()
            }
            val result = jobScheduler?.schedule(jobInfo!!)
        }
 
 
        fun cancelScheduler() {
            jobScheduler?.cancel(JOBID)
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容