现在,我正在使用Firebase上传照片,并且效果很好,并且能够重建此作品以使用workmanager,但是我不知道如何将内容URI触发器传递给我的workmanager构建器。
val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(applicationContext))
val job = dispatcher.newJobBuilder()
.setService(UploadJobService::class.java)
.setTag(TAG)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(0, 60))
.setTrigger(Trigger.contentUriTrigger( Arrays.asList(
ObservedUri(Uri.parse(Environment.getExternalStorageDirectory().absolutePath), ObservedUri.Flags.FLAG_NOTIFY_FOR_DESCENDANTS))
))
.setLifetime(Lifetime.FOREVER)
.setReplaceCurrent(false)
.setConstraints(
Constraint.ON_UNMETERED_NETWORK
)
.build()
dispatcher.mustSchedule(job)
这是我用于工作经理的代码,它在大多数时候都有效,但是当我拍照并删除后,由于间隔15分钟,它不起作用, 如何注册新的唯一工人,当检测到新照片时将如何开始工作?
编辑:以下是即时通讯正在使用的代码及其工作原理,但是不确定我是否正确实现了...
这是安排工时的方法:
public static void Checkfornewphotos(String ONE_MY_WORK) {
OneTimeWorkRequest.Builder photoCheckBuilder =
new OneTimeWorkRequest.Builder(MyWorker.class);
photoCheckBuilder.setConstraints(new Constraints.Builder()
.addContentUriTrigger(MediaStore.Images.Media.INTERNAL_CONTENT_URI, true)
.addContentUriTrigger(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true)
.build());
OneTimeWorkRequest Photocheck = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
instance.enqueueUniqueWork(ONE_MY_WORK, ExistingWorkPolicy.REPLACE, Photocheck);
}
这是我的工人:
public class MyWorker extends Worker {
public MyWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@Override
public Worker.Result doWork() {
// Do your actual work
try {
Log.i(TAG, "mywork")
Result.RETRY
} catch (exception: Exception) {
Log.i(TAG, "mywork")
Result.SUCCESS
}
// Then start listening for more changes
Checkfornewphotos(getTags().iterator().next());
}
}
答案 0 :(得分:1)
WorkManager不支持定期(即重复)内容URI触发器,但是它支持将addContentUriTrigger()
作为约束之一的OneTimeWorkRequest
入队。
public static void scheduleWork(String tag) {
OneTimeWorkRequest.Builder photoCheckBuilder =
new OneTimeWorkRequest.Builder(MyWorker.class);
photoCheckBuilder.setConstraints(new Constraints.Builder()
.addContentUriTrigger(MediaStore.Images.Media.INTERNAL_CONTENT_URI, true)
.addContentUriTrigger(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true)
.build());
OneTimeWorkRequest photoCheckWork = photoCheckBuilder.build();
WorkManager instance = WorkManager.getInstance();
instance.enqueueUniqueWork(tag, ExistingPeriodicWorkPolicy.REPLACE, photoCheckWork);
}
因为它是OneTimeWorkRequest
,所以它只会在第一次更改URI时触发-您需要在Worker完成后才能重新加入工作以捕获下一个更改:
public class MyWorker extends Worker {
public MyWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@Override
public Worker.Result doWork() {
// Do your actual work
// Then start listening for more changes
scheduleWork(getTags().iterator().next());
}
}