Запуск задачи WorkManager из BroadcastReceiver - PullRequest
0 голосов
/ 17 сентября 2018

У меня есть 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

Захватывает модель представления следующим образом: ViewModelProviders.of(this).get(BlurViewModel.class);

Я не могу сделать это, очевидно, потому что мой класс сервера уведомлений не является моделью представления. Как мне подойти к этой проблеме?

1 Ответ

0 голосов
/ 17 сентября 2018

Для любого, кто видит это, вы можете использовать WorkManager.getInstance() для статического получения объекта WorkManager. Существует только один экземпляр WorkManager, просто убедитесь, что вы инициализируете его следующим образом при запуске приложения: WorkManager.initialize(this, new Configuration.Builder().build());

Официальная документация Android Custom Work Manager Config

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...