首页 > 解决方案 > 从 BroadcastReceiver 启动 WorkManager 任务

问题描述

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

通知服务接收器:

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

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

标签: androidandroid-studioandroid-workmanager

解决方案


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

Android Custom Work Manager Config 官方文档


推荐阅读