bla*_*awk 4 java android android-jobscheduler jobservice
我没有看到使用JobService的jobFinshed的示例,似乎我们必须在满足某些条件时跟踪更改,我们必须调用jobFinished()method,对吗?
jobFinished()从另一个类(如)调用的困难IntentService似乎是要获取扩展JobService到call的类的实例jobFinished()。您可以获取有关预定作业的信息,但不能获取有关信息JobService(至少,我找不到方法)。我可以想到三种致电方式jobFinished()。
在我的一JobService堂课上,我正在做定期工作。我不担心处理失败。该任务将很快再次执行。如果是这种情况,您可以这样做。
public boolean onStartJob(JobParameters params) {
startService(new Intent(this, MyIntentServiceThatDoesTheWork.class));
// job not really finished here but we assume success & prevent backoff procedures, wakelocking, etc.
jobFinished(params, false);
return true;
}
Run Code Online (Sandbox Code Playgroud)
如果您的工作很短,这也是您要执行的方法,那么在UI线程上执行它就没问题了。在这种情况下,请完成所有工作,onStartJob()然后返回false。
// common Strings
public static final String IS_SUCCESS = "isSuccess";
public static final String MY_BC_RCVR = "MyBroadcastRcvr";
Run Code Online (Sandbox Code Playgroud)
你的 JobService
public class MyJobService extends JobService {
JobParameters mParams;
public boolean onStartJob(JobParameters params) {
mParams = params;
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter(MY_BC_RCVR));
startService(new Intent(this, MyIntentServiceThatDoesTheWork.class));
return true;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isSuccess = false;
if(intent.hasExtra(IS_SUCCESS)) {
isSuccess = intent.getBooleanExtra(IS_SUCCESS, false);
}
LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
jobFinished(mParams, !isSuccess);
}
};
}
Run Code Online (Sandbox Code Playgroud)
& 你的 IntentService
public class MyIntentServiceThatDoesTheWork extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
boolean isSuccess = methodToDoAllMyWork();
Intent bcIntent = new Intent(MY_BC_RCVR);
bcIntent.putExtra(IS_SUCCESS, isSuccess);
LocalBroadcastManager.getInstance(this).sendBroadcast(bcIntent);
}
}
Run Code Online (Sandbox Code Playgroud)
我已经给出了一个示例,该示例AsyncTask基于来自Google Developer Advocate的Medium帖子(也由Arseny Levin引用),但是也应该可以使用IntentService(参见此SO帖子进行嵌套IntentService)。
public class MyJobService extends JobService {
JobParameters mParams;
public boolean onStartJob(JobParameters params) {
mParams = params;
new MyAsyncTaskThatDoesTheWork().execute();
return true;
}
private class MyAsyncTaskThatDoesTheWork extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
return methodToDoAllMyWork();
}
@Override
protected void onPostExecute(Boolean isSuccess) {
if(mParams != null) {
jobFinished(mParams, !isSuccess);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6192 次 |
| 最近记录: |