Job scheduler in android nougat is not running

2019-08-31 03:44发布

问题:

I am trying to make job scheduler run after every 3 seconds but it doesnt work on android noughat. Here is my code.

     mJobScheduler = (JobScheduler) getSystemService( Context.JOB_SCHEDULER_SERVICE );
     JobInfo.Builder builder = new JobInfo.Builder( 1,
                            new ComponentName( getPackageName(), JobSchedulerService.class.getName() ) );


                  builder.setPeriodic(3000);
                    builder.setRequiresDeviceIdle(false);
                    builder.setPersisted(true);
                    JobInfo j=builder.build();
                    mJobScheduler.schedule(j);

Job Scheduling service that contains the code to be executed on jobs.

       public class JobSchedulerService extends JobService {

        private Handler mJobHandler = new Handler( new Handler.Callback() {
            @Override
            public boolean handleMessage( Message msg ) {
                Toast.makeText( getApplicationContext(), "JobService task running", Toast.LENGTH_SHORT ).show();
                jobFinished( (JobParameters) msg.obj, false );
                return true;
            }
        } );

        @Override
        public boolean onStartJob(JobParameters params ) {
        //    Toast.makeText( getApplicationContext(), "kutta", Toast.LENGTH_SHORT ).show();
            mJobHandler.sendMessage( Message.obtain( mJobHandler, 1, params ) );
            return true;
        }

        @Override
        public boolean onStopJob( JobParameters params ) {
            mJobHandler.removeMessages( 1 );
            return false;
        }

    }

回答1:

The minimum period a job can be scheduled is 15 minutes. This started with Nougat. If it is set to a value less than 15 minutes, the job will use 15 minutes.

MIN_PERIOD_MILLIS

getMinPeriodMillis() copy & paste of function description below

Query the minimum interval allowed for periodic scheduled jobs. Attempting to declare a smaller period that this when scheduling a job will result in a job that is still periodic, but will run with this effective period.