当应用程序在 Android 8+ 停止时定期任务终止

Periodic task killed when app is stopped on Android 8+

大家好,我正在尝试在 Android 上执行周期性任务,但我在某些设备上卡住了。

我需要每 15 或 30 分钟 运行 在后台执行一项任务。这适用于 Android pre 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 管理器(不触发 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
    }
}

我不知道我做错了什么。请帮忙

几天来我一直被同一个问题困扰,最终发现目前还没有合适的方法,只能要求用户授予一些权限(自动启动、节电优化等)

您可以在此处找到更多信息:https://dontkillmyapp.com

这个问题以多种不同的方式被问到,没有很好的答案,但在这里你可能会找到一些抽象的答案,就是我刚才告诉你的。