我已经使用
flutterLocalNotificationsPlugin.zonedSchedule()
来安排本地通知,并且效果很好。
当此预定本地通知在我想检查应用程序是否位于前景或应用程序位于背景之前发送时。
如果 Flutter 应用程序正在运行,则意味着应用程序处于 Foreground,所以我希望将计划的通知设置为 In AppNotification,如果关闭则意味着应用程序处于 Background,而不是将计划的通知发送为 actualNotification。
我已经在 IOS 中使用 Flutter 中的本机 swift 代码完成了此功能,但是我如何为 android 端代码执行此操作?
无需本机代码的帮助即可关闭,并且适用于 ios 和 android(可能需要对代码进行少量修改)。
首先,我们创建一个生命周期处理程序类,它将扩展 WidgetsBindingObserver 类。简而言之,该类在flutter中用于通知对象环境的变化。要了解更多信息,请访问:https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html
import 'package:flutter/material.dart';
final lifecycleEventHandler = LifecycleEventHandler._();
class LifecycleEventHandler extends WidgetsBindingObserver {
bool inBackground = true;
LifecycleEventHandler._();
initialise() {
WidgetsBinding.instance.addObserver(lifecycleEventHandler);
}
@override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
switch (state) {
case AppLifecycleState.resumed:
inBackground = false;
print('App is in foreground');
break;
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
case AppLifecycleState.detached:
inBackground = true;
print('App is in background');
break;
}
}
}
现在,每当我们希望我们的应用程序监听更改时,我们都会使用此类。我们可以将其添加到 void main() 内的 main.dart 文件中。如果您想从应用程序启动时听到变化。
lifecycleEventHandler.initialise();
调用上述函数会将观察者添加到您的应用程序中。
现在,在通知功能中执行以下操作:
Future showNotification() async {
if (!lifecycleEventHandler.inBackground){
//Show in app notification
}
//otherwise notification in notification tray
...
}