gpt4 book ai didi

android - 避免从 WorkManager 复制 PeriodicWorkRequest

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:24:01 25 4
gpt4 key购买 nike

在应用程序启动时,我想启动将永远有效的服务,但是当用户再次打开应用程序时,它会重复。

PeriodicWorkRequest.Builder sendDataBuilder = new PeriodicWorkRequest.Builder(SendConnectionMetricsWorker.class, Constants.REPEAT_TIME_INTERVAL_IN_HOURS, Constants.REPEAT_TIME_INTERVAL_UNITS)
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build());
PeriodicWorkRequest periodicWorkRequest = sendDataBuilder
.build();
WorkManager.getInstance().enqueue(periodicWorkRequest);

最佳答案

您可以使用 enqueueUniquePeriodicWork 而不是 enqueue。基于文档:

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work. The uniqueWorkName uniquely identifies this PeriodicWorkRequest.

您可以按如下方式实现:

PeriodicWorkRequest.Builder sendDataBuilder = new PeriodicWorkRequest.Builder(SendConnectionMetricsWorker.class, Constants.REPEAT_TIME_INTERVAL_IN_HOURS, Constants.REPEAT_TIME_INTERVAL_UNITS)
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build());
PeriodicWorkRequest periodicWorkRequest = sendDataBuilder
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Send Data", ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest);

注意:

ExistingPeriodicWorkPolicy.REPLACE 确保如果有标记为 uniqueWorkName 的挂起工作,它将被取消并运行新工作。 ExistingPeriodicWorkPolicy.KEEP 仅当没有标有 uniqueWorkName 的未决工作时才会运行新的 PeriodicWorkRequest。

关于android - 避免从 WorkManager 复制 PeriodicWorkRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50943056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com