我已经为JobScheduler实现了一个演示应用程序。以下是我的MainActivity和JobScheduler服务代码。即使我按取消所有任务按钮取消所有预定作业,也不会调用OnStopJob。我无法理解为什么会这样。我也试过从onStopJob返回true。
package com.example.jobschedulerdemo;
import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private JobScheduler mJobScheduler;
private Button mScheduleJobButton;
private Button mCancelAllJobsButton;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScheduleJobButton = (Button) findViewById( R.id.schedule_job );
mCancelAllJobsButton = (Button) findViewById( R.id.cancel_all );
mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
mScheduleJobButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
JobInfo.Builder jobBuilder = new JobInfo.Builder(1, new ComponentName(getPackageName(), TestJobService.class.getName()));
jobBuilder.setPeriodic(3000);
jobBuilder.setRequiresCharging(true);
if(mJobScheduler.schedule(jobBuilder.build()) <= 0){
Log.i(TAG, "Error in scheduling job");
}
}
});
mCancelAllJobsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mJobScheduler.cancelAll();
}
});
}
}
package com.example.jobschedulerdemo;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class TestJobService extends JobService{
private static final String TAG = "TestJobService";
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(TestJobService.this, "Task Running", Toast.LENGTH_SHORT).show();
jobFinished((JobParameters)msg.obj, false);
return false;
}
});
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onJobStarted : Job Id = " + params.getJobId());
mHandler.sendMessage(Message.obtain(mHandler, 1, params));
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob : Job Id = " + params.getJobId());
mHandler.removeMessages(1);
return false;
}
}
答案 0 :(得分:0)
onStopJob(JobParameters params)取消待处理的任务。
您可以通过运行作业轻松地重现它并将其取消 BEFORE 结束(在调用jobFinished(...)之前)。它假设您放置了取消后台任务所需的逻辑。
3秒可能太短而无法进行测试。尝试更多时间。