android - 如何从 Flutter 发送 ACTION_APPWIDGET_UPDATE 广播
问题描述
在我的“java”应用程序中,我的 getDataFromServer() 函数中有这段代码(我的 WorkManager 每 2 小时调用一次,我的 MainActivity Onrefresh() 调用一次),以便用新数据更新我的主屏幕小部件:
AppWidgetManager.getInstance(context).getAppWidgetIds(
new ComponentName(context,MyWidgetProvider.class));
Intent updateIntent = new Intent();
updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
updateIntent.putExtra(MyWidgetProvider.WIDGET_ID_KEY, ids);
context.sendBroadcast(updateIntent);
这将使我的 ,MyAppWidgetProvider “唤醒”,从文件中读取新数据并进行更新。
现在,我已经将我的逻辑转移到了 Flutter,我不知道如何从我的 Dart 代码中调用这段代码。
有什么建议吗?
解决方案
可以参考包https://pub.dev/packages/home_widget
"updateWidget" -> {
val className = call.argument<String>("android") ?: call.argument<String>("name")
try {
val javaClass = Class.forName("${context.getPackageName()}.${className}")
val intent = Intent(context, javaClass)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids: IntArray = AppWidgetManager.getInstance(context.applicationContext).getAppWidgetIds(ComponentName(context, javaClass))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
context.sendBroadcast(intent)
} catch (classException: ClassNotFoundException) {
result.error("-3", "No Widget found with Name $className. Argument 'name' must be the same as your AppWidgetProvider you wish to update", classException)
}
}
在Background Update
https://pub.dev/packages/home_widget#background-update
的 Dart 部分
由于方法HomeWidget
是静态HomeWidget
的,即使应用程序在后台,也可以在后台使用来更新 Widget。
示例应用程序正在使用flutter_workmanager
插件来实现这一点
void callbackDispatcher() {
Workmanager.executeTask((taskName, inputData) {
debugPrint('Native called background task: $taskName');
final now = DateTime.now();
return Future.wait<bool>([
HomeWidget.saveWidgetData('title', 'Updated from Background'),
HomeWidget.saveWidgetData('message',
'${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} ${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}'),
HomeWidget.updateWidget(
name: 'HomeWidgetExampleProvider', iOSName: 'HomeWidgetExample'),
]).then((value) {
return !value.contains(false);
});
});
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
Workmanager.initialize(callbackDispatcher, isInDebugMode: kDebugMode);
runApp(MyApp());
}
推荐阅读
- python - 从python中的函数调用类实例的类属性
- asp.net-core - 将 ASP.NET Core 标识添加到具有数据库优先模型的现有项目中
- javascript - 如何将表格编写成嵌套元素,打印没有循环的数组
- c++ - LLVM:访问函数中的数组参数
- makefile - 使用 makefile 自动创建目录
- javascript - react-native CLI 应该是本地模块还是全局模块?
- c - task_struct -> parent 总是指向根进程而不是实际的父进程
- spring-security-oauth2 - Zuul 网关未携带授权标头
- php - 如何在创建方法 laravel6 后重定向用户?
- batch-file - 批处理文件findstr,如何?