我创建了一个例子来了解JobService的工作原理。在下面的代码中,我有MainActivity和onclik()方法启动JobService。在运行时,调用onClikc方法时 应用程序崩溃没有任何logCat输出,但我收到一个对话框说:不幸的是,JobServiceTest_00已经停止
请参加MainActivity和TestJobService,让我知道导致此次崩溃的原因
注意:TestJobService已在清单文件中注册
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
ComponentName mServiceComponent = new ComponentName(this, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(kJobId++, mServiceComponent);
builder.setMinimumLatency(5 * 1000); // wait at least
builder.setOverrideDeadline(10 * 1000); // maximum delay
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // require unmetered network
builder.setRequiresDeviceIdle(true); // device should be idle
builder.setRequiresCharging(false); // we don't care if the device is charging or not
JobScheduler jobScheduler = (JobScheduler) getApplication().getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
}
public void cancelAllJobs(View v) {
JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
tm.cancelAll();
}
}
TestJobService :
public class TestJobService extends JobService {
private final static String TAG = TestJobService.class.getClass().getSimpleName();
@Override
public boolean onStartJob(JobParameters params) {
Log.w(TAG, SubTag.bullet("onStartJob"));
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.w(TAG, SubTag.bullet("onStopJob"));
return true;
}
}
答案 0 :(得分:0)
我不得不在清单中的服务标签中添加以下行:
android:permission="android.permission.BIND_JOB_SERVICE"