簡體   English   中英

flutter 通過 workManager 安排本地通知

[英]flutter schedule local notification by workManager

是否可以從后台 dart 代碼安排通知?

例如,就像使用executeTask方法中的work_manager插件一樣,就好像我注冊了每小時運行的服務並根據當前位置安排今天的通知一樣。

我試過但沒有運氣。

任何人都可以幫助我嗎?

是的,可以在工作經理的幫助下安排本地通知。 當我在我的小米設備上嘗試 Flutter 本地通知插件時,當應用程序關閉(並從最近的活動中清除)時,通知沒有顯示。 所以我找到的唯一解決方案是直接使用 Work Manager flutter 插件來 show() 無需調度。

優點

  • 工作管理器幫助我在應用關閉並從最近的應用列表中清除后顯示通知。
  • 即使在設備重啟后也能正常工作

缺點

  • 通知有時不會顯示。
  • 無法管理到固定時間的調度。 (如果應用程序關閉,android有時不允許執行任務)

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM