我在Android中实现了一个应用程序,它使用JobService来检查更新。我已经用一些设备进行了测试:三星J3、RedMi 5+、RedMi note、MI A2 lite。它在J3中工作正常,但在我测试过的其他手机中,如果应用程序不活动或应用程序不在最近的应用程序列表中,则不会计划JobService。
这就是我是如何实施的。
MainActivity.java
public static void scheduleJob(Context context) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
JobScheduler js =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo job = new JobInfo.Builder(
MY_BACKGROUND_JOB,
new ComponentName(context, CheckAdService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.setPeriodic(15 * 60 * 1000)
.build();
int resultCode = js.schedule(job);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("JOB", "Scheduled");
} else {
Log.d("JOB", "Not Scheduled");
}
}
}Service.java
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CheckAdService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
Log.d("NetworkAvailable", "Flag No 2");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
final Context context = getApplicationContext();
...
IonDB ionDB = new IonDB(CheckAdService.this, "checkStatus");
ionDB.getData(new OnDbData() {
@Override
public void OnDbDataReceived(JsonObject jsonObject, boolean withError) {
...
// after notifying user with news I call jobFinished with rescheduling true option
jobFinished(params, true);
}
});
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d("DBDATA", "Job cancelled before completion");
return true;
}
}请更正我的JobService实现,使它在所有的安卓versions >= LOLLIPOP工作。
考虑到我是Android的新手,如果我犯了一些编码错误,请告诉我任何建议。
发布于 2019-03-30 09:48:19
我想如果你要使用工人经理,它将是更正确的。
它具有不同Android版本之间的功能。
https://stackoverflow.com/questions/55429969
复制相似问题