[英]flutter schedule local notification by workManager
是否可以從后台 dart 代碼安排通知?
例如,就像使用executeTask
方法中的work_manager
插件一樣,就好像我注冊了每小時運行的服務並根據當前位置安排今天的通知一樣。
我試過但沒有運氣。
任何人都可以幫助我嗎?
是的,可以在工作經理的幫助下安排本地通知。 當我在我的小米設備上嘗試 Flutter 本地通知插件時,當應用程序關閉(並從最近的活動中清除)時,通知沒有顯示。 所以我找到的唯一解決方案是直接使用 Work Manager flutter 插件來 show() 無需調度。
優點
缺點
callbackDispatcher() {
Workmanager.executeTask((task, inputData) async {
if (LocalNotification.flutterNotificationPlugin == null) {
await LocalNotification.Initializer();
}
DateTime now = DateTime.now();
var hour = inputData['hour'];
var minute = inputData['minute'];
DateTime time = DateTime(now.year, now.month, now.day, now.hour, minute);
await LocalNotification.ShowOneTimeNotification(time);
return Future.value(true);
});
}
扳機
FlatButton(
child: Text('set'),
onPressed: () async {
await Workmanager.initialize(callbackDispatcher);
await Workmanager.registerPeriodicTask(
"test_workertask", "test_workertask",
inputData: {"data1": "value1", "data2": "value2"},
frequency: Duration(hours: 1),
initialDelay: Duration(seconds: 10),
existingWorkPolicy: ExistingWorkPolicy.replace);
},
),
您可以通過重用以下代碼段來嘗試使用flutter_local_notifications :
import 'dart:async';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
var duration = Duration(hours: 1);
var scheduledNotificationDateTime = DateTime.now().add(duration);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your other channel id',
'your other channel name',
'your other channel description',
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
NotificationDetails platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics,
iOSPlatformChannelSpecifics,
);
await flutterLocalNotificationsPlugin.schedule(
0,
'scheduled title',
'scheduled body',
scheduledNotificationDateTime,
platformChannelSpecifics,
);
為了安排通知工作,您應該在下面添加行。 解決方案是這樣的:在 AndroidManifest.xml 中的</activity>
之后添加這些行:
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.