Job Scheduling setRequiresDeviceIdle(true) and setPeriodic() not working

你说的曾经没有我的故事 提交于 2019-12-10 15:23:09

问题


I am working on app that do the background task after 10 second and check whether device is idle or not but some how It fires every 10 second without checking Device is idle or not.

MainActivity.java

private static final int JOB_ID = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     mJobScheduler = (JobScheduler) getSystemService(this.JOB_SCHEDULER_SERVICE);
     construct_job();
}

private void construct_job(){

     JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(getPackageName(), MyJobService.class.getName()))
                    .setPeriodic(10000).setRequiresDeviceIdle(true);

    int code = mJobScheduler.schedule(builder.build());

    if( code <= 0 ) {
          //If something goes wrong
          Log.v("SOMETHING", "GOES WRONG");
    }
 }

MyJobService.java

    public class MyJobService extends JobService {
        @Override
        public boolean onStartJob(JobParameters params) {

            Log.v("OnStart", "onStartJob-h");
            //Job Will Be Started Here


            mJobHandler.sendMessage( Message.obtain( mJobHandler, 1, params ) );
            return true;
        }

        @Override
        public boolean onStopJob(JobParameters params) {
            Log.v("JOB","STOPPED");
            mJobHandler.removeMessages( 1 );
            return false;
        }


        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;
            }

        });
}

AndroidManifiest.xml

  <service
            android:name=".MyJobService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="true"/>

Do, Anyone have idea what am i doing wrong ? Please help?


回答1:


Adding .setRequirementsEnforced(true) will probably fix your problem.

See the documentation: It's possible to set several requirements for a job, however, not all of them need to be considered by the underlying {@link JobApi}. If the requirements are enforced, then the device state is checked before your job runs. If at least one requirement isn't met, then the job is rescheduled and not run. ...



来源:https://stackoverflow.com/questions/38474425/job-scheduling-setrequiresdeviceidletrue-and-setperiodic-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!