从BroadcastReceiver启动WorkManager任务

时间:2018-09-17 03:49:01

标签: android android-studio android-workmanager

我在这里有一个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));

}

}

我要在广播接收器的接收上启动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);

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

1 个答案:

答案 0 :(得分:1)

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

Android Custom Work Manager Config official documentation