我正在使用新闻应用程序。而且我需要每天获取一次最新消息。为此,我使用了Jobsheduler.Here是代码:
ComponentName componentName = new ComponentName(this, JobService.class);
JobInfo jobInfo = new JobInfo.Builder(123, componentName)
.setRequiresCharging(false)
.setPeriodic(24 * 60 * 60 * 1000)
.setPersisted(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
JobScheduler jobScheduler = (JobScheduler)getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS){
Log.d(TAG, "Job Scheduled");
}
else {
Log.d(TAG, "Job Scheduling failed");
}
但是现在我需要在6:00以后的早晨进行一次此工作,届时将会有Internet连接。有没有办法用Job Scheduler做到这一点。我知道我可以使用“警报管理器”来执行此操作,但是在诸如是否存在连接以及设备充电的情况下,“作业计划程序”比“警报管理器”要好得多。或者我可以使用Workmanager来实现此目的,如果需要,可以使用Job Scheduler和AlarmManager。还是有另一种方式做到这一点???任何建议表示赞赏。
您可以将广播接收器与工作管理器一起使用,让您知道连接可用并完成计划的任务。并检查互联网是否可用并做好您的工作
public static final String CUSTOM_INTENT = "com.test.intent.action.ALARM";
public static Context ctx = OfferlyApplication.getContext();
@Override
public void onReceive(Context context, Intent intent) {
/* enqueue the job */
AlarmJobIntentService.enqueueWork(context, intent);
}
public static void cancelAlarm() {
AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
/* cancel any pending alarm */
alarm.cancel(getPendingIntent());
}
public static void setAlarm(boolean force) {
cancelAlarm();
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
// EVERY X MINUTES
long delay = (1000 * 60 * 60);
long when = System.currentTimeMillis();
if (!force) {
when += delay;
}
/* fire the broadcast */
PendingIntent pendingIntent = getPendingIntent();
int SDK_INT = Build.VERSION.SDK_INT;
if (SDK_INT < Build.VERSION_CODES.KITKAT)
alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);
else if (SDK_INT < Build.VERSION_CODES.M)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, when, pendingIntent);
else {
Log.d("JOB_SCHEDULING","waking device");
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, when, pendingIntent);
}
}
private static PendingIntent getPendingIntent() {
//Context ctx; /* get the application context */
Intent alarmIntent = new Intent(ctx, AlarmReceiver.class);
alarmIntent.setAction(CUSTOM_INTENT);
return PendingIntent.getBroadcast(ctx, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}