【发布时间】:2020-08-02 07:00:33
【问题描述】:
大家好,我正在尝试在 Android 上执行周期性任务,但我在某些设备上遇到了问题。
我需要每 15 或 30 分钟在后台运行一次任务。这适用于 Android 8.0 之前的版本。但是在 8+ 上,它仅在应用程序处于后台或前台时才有效。当应用程序从最近被刷出时,计划任务在真实设备(Ulefone note 7(Android 8.1),Tecno LC7(Android 10),itel A56(Abdroid 9))上被杀死,但在模拟器(Android 10)上运行良好。我尝试了几种方法:
1.Workmanager(仅在应用处于后台或前台时有效)
build.gradle
implementation "androidx.work:work-runtime:2.4.0"
主活动
PeriodicWorkRequest periodicSyncDataWork =
new PeriodicWorkRequest.Builder(NotificationWorker.class, 15,TimeUnit.MINUTES)
.addTag("TAG_SYNC_DATA")
.setBackoffCriteria(BackoffPolicy.LINEAR,PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
.build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"NOTIFICATION_WORKER",
ExistingPeriodicWorkPolicy.REPLACE, //Existing Periodic Work policy
periodicSyncDataWork //work request
);
NotificationWorker
public class NotificationWorker extends Worker {
public NotificationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams)
{
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
Log.d("MYWORKER", "LLLLLLLLLLL");
//My code here
return Result.success();
}
}
2.JobScheduler(仅在应用处于后台或前台时有效)
ComponentName serviceComponent = new ComponentName(context, NotifJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(1880, serviceComponent);
builder.setPersisted(true);
builder.setPeriodic(16*60*1000, 20*60 *1000);
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
3.Alarm Manager(不触发 BroadcastReceiver)
主要代码
Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, 100,intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis();
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
广播接收器
public class NotificationBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent in = new Intent(context, MyIntentService.class);
context.startService(in);
}
}
IntentService
public class MyIntentService extends IntentService {
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("NotifIntentService", "Starting");
//My task here
}
}
我无法弄清楚我在这里做错了什么。请帮忙
【问题讨论】:
标签: android alarmmanager android-workmanager android-jobscheduler periodic-task