我无法弄清楚如何使用 Android 的 Workmanager。本质上,我想发出一个带有时间延迟的 OneTime 请求,确定成功,然后做一些事情。工人阶级什么都不做。
我期待的是延迟后返回的成功代码。也就是说,我的 Workmanager 代码的唯一目的是提供延迟。
我知道还有许多其他方法可以影响延迟,但我的理解是,Android 比 AlarmManager 更好地“保护” Workmanager Workers。
不幸的是,我做不到。
这是我所做的
- 扩展我的活动以包括 LifecycleOwner
添加了所需的getLifeCycle方法,如下
@NonNull @Override public Lifecycle getLifecycle() { Log.d (TAG, "getLifecycle(): " + getLifecycle()); return getLifecycle(); }
这是工人阶级
public class makeAlarm extends Worker { public makeAlarm( @NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @Override public Result doWork() { // Do the work here--in this case, do nothing // Indicate whether the task finished successfully with the Result return Result.success(); } }
这是我的操作代码
// Create a OneTimeWorkRequest that delays "success" by the required time OneTimeWorkRequest makeAlarmWorkRequest = new OneTimeWorkRequest.Builder(makeAlarm.class) .setInitialDelay(120, TimeUnit.SECONDS) .build(); WorkManager.getInstance(this).enqueue(makeAlarmWorkRequest); // The following stmt. shows what appears to be a valid id Log.d (TAG, "makeAlarmWorkRequest.getId(): " + makeAlarmWorkRequest.getId()); WorkManager.getInstance(this).getWorkInfoByIdLiveData(makeAlarmWorkRequest.getId()) .observe(myLifecycleOwner, new Observer<WorkInfo>() { @Override public void onChanged(@Nullable WorkInfo workInfo) { if (workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED) { // Some amazing work here... } } });
我尝试了许多变体,但都没有成功。上面的代码导致堆栈溢出崩溃。帮助!