作业调度setRequiresDeviceIdle(true)和setPeriodic()不起作用

时间:2016-07-20 07:02:37

标签: java android background job-scheduling background-task

我正在开发应用程序,在10秒后执行后台任务并检查设备是否处于空闲状态,但是有些如何在不检查设备是否空闲的情况下每10秒触发一次。

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"/>

那么,任何人都知道我做错了什么?请帮帮忙?

1 个答案:

答案 0 :(得分:0)

添加.setRequirementsEnforced(true)可能会解决您的问题。

参见文档: 可以为作业设置多个要求,但是,并非所有要求都需要由基础{@link JobApi}来考虑。如果强制执行要求,则会在作业运行之前检查设备状态。如果未满足至少一个要求,则重新安排作业而不运行。 ...