编程语言
首页 > 编程语言> > java – 作业调度setRequiresDeviceIdle(true)和setPeriodic()不起作用

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

作者:互联网

我正在开发应用程序,在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"/>

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

解决方法:

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

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

标签:java,android,background,job-scheduling,background-task
来源: https://codeday.me/bug/20190711/1430318.html