从 BroadcastReceiver 启动 WorkManager 任务

Starting WorkManager task from a BroadcastReceiver

我这里有一个 BroadcastReceiver:

NotificationServiceReceiver:

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));

}

}

我想在 Broadcast Receiver 的 Receive 上启动一个 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);

显然我不能这样做,因为我的通知服务器 class 不是视图模型。我该如何解决这个问题?

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

Android Custom Work Manager Config official documentation