我正在开发一款应用程序,它会在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"/>
大家好,我有一个问题,不知道做错了什么,请帮忙解决一下?