gpt4 book ai didi

android - 从 BroadcastReceiver 启动 WorkManager 任务

转载 作者:行者123 更新时间:2023-12-03 17:50:58 24 4
gpt4 key购买 nike

我在这里有一个广播接收器:

通知服务接收器:

public class NotificationServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RestService.ACTION_PENDING_REMINDERS_UPDATED)) {
//Reminders updated
NotificationServer.startNotificationWorkRequest(context);
}
}

通知服务器:
public class NotificationServer extends IntentService {

private static final String LOG_TAG = "NotificationService";
public static final String ACTION_SHOW_NOTIFICATION = "com.android.actions.SHOW_NOTIFICATION";
// this is a bypass used for unit testing - we don't want to trigger this service when the calendar updates during
// the intergration tests
public static boolean sIgnoreIntents = false;
private WorkManager mWorkManager;
private LiveData<List<WorkStatus>> mSavedWorkStatus;

public NotificationServer() {
super(NotificationServer.class.getName());
mWorkManager = WorkManager.getInstance();
}

/**
* Handles all intents for the update services. Intents are available to display a particular notification, clear all
* notifications, refresh the data backing the notification service and initializing our timer. The latter is safe to
* call always, it will check the current state of on-device notifications and update its timers appropriately.
*
* @param intent - the intent to handle. One of ACTION_SHOW_NOTIFICATION,
* ACTION_REFRESH_DATA or ACTION_INIT_TIMER.
*/
@Override
protected void onHandleIntent(Intent intent) {
startNotificationWorkRequest(this);
}

public void startNotificationWorkRequest(Context context) {
WorkContinuation continuation = mWorkManager
.beginUniqueWork(IMAGE_MANIPULATION_WORK_NAME,
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequest.from(CleanupWorker.class));

}

}

我想在广播接收器的接收上启动一个 WorkManager 任务。问题是我不能静态地执行此操作,因为我需要访问当前的 WorkManager 对象。 Google 在此处提供的示例代码: https://github.com/googlecodelabs/android-workmanager/blob/master/app/src/main/java/com/example/background/BlurActivity.java

像这样抓取 ViewModel: ViewModelProviders.of(this).get(BlurViewModel.class);
我显然不能这样做,因为我的通知服务器类不是 View 模型。我应该如何解决这个问题?

最佳答案

对于看到此内容的任何人,您可以使用 WorkManager.getInstance()静态获取 WorkManager 对象。 WorkManager 只有一个实例,只要确保在应用程序启动时像这样初始化它:WorkManager.initialize(this, new Configuration.Builder().build());
Android Custom Work Manager Config official documentation

关于android - 从 BroadcastReceiver 启动 WorkManager 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360508/

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