如何从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

在原生部分https://github.com/ABausG/home_widget/blob/3de5ff703e9f8f7700036a23e609e0627976f904/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetPlugin.kt#L61

"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
由于HomeWidget的方法是静态的,即使应用程序在后台,也可以在后台使用HomeWidget来更新Widget
示例应用程序使用flutter_workmanager插件来实现此

https://github.com/ABausG/home_widget/blob/3de5ff703e9f8f7700036a23e609e0627976f904/example/lib/main.dart#L10

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

最新更新