我使用的是WorkManager版本android.arch.work:work-runtime:1.0.0-beta03
。我使用此工作管理器使用OneTimeWorker以动态间隔时间将文件上传到服务器。
这就是我的工作。希望您可以检查一下,并告诉我哪里错了,以及其他修复方法。
首先,我提出工作要求
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorkRequest.class)
.setInitialDelay(0), TimeUnit.SECONDS)
.addTag("UploadData")
.build();
WorkManager
.getInstance()
.getWorkInfoByIdLiveData(workRequest.getId())
.observeForever(workInfoObserverBackground);
WorkManager
.getInstance()
.enqueueUniqueWork("UploadData", ExistingWorkPolicy.REPLACE, workRequest);
然后,定义“观察者”以侦听其结果。我也从这里开始下一次跑步。
workInfoObserverBackground = workInfo -> {
if (workInfo != null){
switch (workInfo.getState()) {
case SUCCEEDED:
case FAILURE:
WorkManager.getInstance().getWorkInfoByIdLiveData(workRequest.getId()).removeObserver(workInfoObserverBackground);
WorkManager.getInstance().cancelUniqueWork("UploadData");
WorkManager.getInstance().cancelAllWorkByTag("UploadData");
workRequest = new OneTimeWorkRequest.Builder(MyWorkRequest.class)
.setInitialDelay(next_interval_time_received_from_api), TimeUnit.SECONDS)
.addTag("UploadData")
.build();
WorkManager
.getInstance()
.getWorkInfoByIdLiveData(workRequest.getId())
.observeForever(workInfoObserverBackground);
WorkManager
.getInstance()
.enqueueUniqueWork("UploadData", ExistingWorkPolicy.REPLACE, workRequest);
break;
}
}
};
几分钟后(我无法记录它,因为它是随机发生的),它崩溃了,这是从logcat收集的堆栈跟踪信息。
1-15 21:46:14.806 25964-26054/com.example.app E/AndroidRuntime: FATAL EXCEPTION: pool-8-thread-1
Process: com.example.app, PID: 25964
android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
at android.database.CursorWindow.<init>(CursorWindow.java:108)
at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
at androidx.work.impl.model.WorkSpecDao_Impl.getInputsFromPrerequisites(WorkSpecDao_Impl.java:1112)
at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:171)
at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:124)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
我的间隔时间始终为1秒。也许旧任务挂在下一个任务上而无法销毁?