我使用WorkManager中的AlarmManager。 当应用程序出现在前台时,AlarmManager可以正常工作。 但是,当该应用程序被杀死(通过查看最新的应用程序关闭滑动)时,WorkManager也将被杀死。
为什么工作经理死了? 我想要类似于不朽服务的WorkManager。 因为我正在制作alarmApp
MainActivity.class onCreate
WorkManager workManager = WorkManager.getInstance();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).build();
workManager.enqueue(workRequest);
MyWorker.class
public class MyWorker extends Worker {
Context context;
Thread thread;
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
this.context = context;
}
@NonNull
@Override
public Result doWork() {
Log.d("1106", "MyWorker_doWork()");
Calendar calendar = Calendar.getInstance();
Log.d("1106", "" + calendar.getTime());
Intent notiIntent = new Intent(context, NotiReceiver.class);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
calendar.set(2020, 10, 06, 06, 25, 0);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 2, notiIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
thread = new Thread(new Runnable() {
@Override
public void run() {
int cnt = 0;
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("1106", cnt++ + "");
}
}
});
thread.start();
return Result.success();
}
}