gpt4 book ai didi

android - 如何在通知到达时在任何屏幕上显示自定义对话框?

转载 作者:行者123 更新时间:2023-12-03 02:50:58 24 4
gpt4 key购买 nike

当推送通知到达我的应用程序时,我试图在任何 Activity 屏幕中显示一个对话框。在应用程序运行时。我可以通过用户交互显示对话框,例如单击按钮。但我想在没有用户交互的情况下展示它。如果有通知到达,则仅应触发对话。我正在尝试使用后台获取来调用它。但找不到任何解决方案。所以,请帮助并提前感谢您。

最佳答案

我以前遇到过同样的问题,我会展示我的解决方案,希望它适合你

The main thing with the solution : we have page is not pop fromNavigator stack when app is life like HomePage as ex, so we can use the BuildContext from this page


所以绕过 上下文 我的 StatefulWidget(像主页)谁
必须仍然在 Navigator 堆栈中(当应用程序处于 Activity 状态时不会弹出它)到您的类(class),当您处理通知数据时,您可以使用它来显示对话框
现在让我们编写一些代码:
作为前我们有 通知管理器 此类用于处理通知消息的类 静态 方法
class NotificationManger {

static BuildContext _context;



static init({@required BuildContext context}) {
_context = context;

}

//this method used when notification come and app is closed or in background and
// user click on it, i will left it empty for you
static handleDataMsg(Map<String, dynamic> data){

}

//this our method called when notification come and app is foreground
static handleNotificationMsg(Map<String, dynamic> message) {
debugPrint("from mangger $message");

final dynamic data = message['data'];
//as ex we have some data json for every notification to know how to handle that
//let say showDialog here so fire some action
if (data.containsKey('showDialog')) {
// Handle data message with dialog
_showDialog(data);
}
}


static _showDialog({@required Map<String, dynamic> data}) {


//you can use data map also to know what must show in MyDialog
showDialog(context: _context,builder: (_) =>MyDialog());


}

}
现在我们在类 中将此回调作为顶级或静态(必须是其中之一) FCM 我的应用程序在里面
class Fcm {
static final FirebaseMessaging _fcm = FirebaseMessaging();

static initConfigure() {
if (Platform.isIOS) _iosPermission();

_fcm.requestNotificationPermissions();
_fcm.autoInitEnabled();

_fcm.configure(
onMessage: (Map<String, dynamic> message) async =>
NotificationManger.handleNotificationMsg(message),
onLaunch: (Map<String, dynamic> message) async =>
NotificationManger.handleDataMsg(message['data']),
onResume: (Map<String, dynamic> message) async =>
NotificationManger.handleDataMsg(message['data']),
onBackgroundMessage: async =>
NotificationManger.handleDataMsg(message['data']);


}

static _iosPermission() {
_fcm.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true));
_fcm.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}

}
要了解更多关于回调 fcm 的信息,请阅读 this
现在在我们的 首页 声明好在里面初始化我们的类 初始化状态 方法
 @override
void initState() {
super.initState();


Future.delayed(Duration.zero,(){
///init Notification Manger
NotificationManger.init(context: context);

///init FCM Configure
Fcm.initConfigure();


});


}
如之前所说,当应用程序显示时主页不会弹出,您可以启动另一个页面但不关闭主页
我希望这有帮助

关于android - 如何在通知到达时在任何屏幕上显示自定义对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57266652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com