调用代码A后,即使我关闭了APP,JobScheduler也将继续运行。

但是某些自定义的Android系统可能会在关闭APP时清除JobScheduler

如何检查JobScheduler是否以编程方式运行?

代码A

private fun startScheduleRestore(mContext:Context){
   logError("Start Server")

   val interval=if (isDebug())
                    10*1000L
                 else
                    mContext.getInteger(R.integer.AutoRestoreInterval)*60*1000L

    val mJobScheduler = mContext.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

    val jobInfo = JobInfo.Builder(mContext.getInteger(R.integer.JobID), ComponentName(mContext, RestoreService::class.java))
                        .setPeriodic(interval)
                        .setPersisted(true)
                        .build()

    mJobScheduler.schedule(jobInfo)
}

代码B
private fun stopScheduleRestore(mContext:Context){
    logError("Stop Server")

    val mJobScheduler = mContext.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
    mJobScheduler.cancel(mContext.getInteger(R.integer.JobID))

}

最佳答案

您可以使用JobScheduler的getAllPendingJobs方法。基于documentation:


public static boolean isJobSchedulerRunning(final Context context) {
    final JobScheduler jobScheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE );
    return jobScheduler.getAllPendingJobs().size() > 0;
}

如果要检查特定JobId是否仍然有效,则可以执行以下操作:
public static boolean isJobIdRunning( Context context, int JobId) {
    final JobScheduler jobScheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE ) ;

    for ( JobInfo jobInfo : jobScheduler.getAllPendingJobs() ) {
        if ( jobInfo.getId() == JobId ) {
           return true;
        }
    }

    return false;
}

关于android - 我如何知道JobScheduler是否正在运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50483874/

10-12 05:22