android - 从 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);
我显然不能这样做,因为我的通知服务器类不是视图模型。我应该如何解决这个问题?
解决方案
对于看到这一点的任何人,您都可以使用WorkManager.getInstance()
静态获取 WorkManager 对象。WorkManager 只有一个实例,只需确保在应用程序启动时像这样初始化它:WorkManager.initialize(this, new Configuration.Builder().build());
推荐阅读
- unity3d - Unity TextMeshPro 3D 对象与普通 UI 画布混淆
- php - 在购物车页面 Magento 2.3 中设置总计
- android - 比较sql数据库和json响应之间数据的有效方法
- firebase - 解析错误:“import”和“export”可能只出现在“sourceType:module”中
- c# - 最大化表单,并禁止用户调整表单大小
- file - Perl 将多个文件内容合并到单个文件中
- react-native - 通过单击 React Native 中的选项卡动态更改标题文本并显示/隐藏左/右标题按钮?
- jquery - 我无法让 .each() 处理我的每个图像
- php - 自动完成文本框的下拉菜单未出现在 texbox 下方
- wordpress - Gutenberg 自定义块如何将数据从插件索引文件发送到 js 文件