Anonymous
Уведомления о флаттере дирижабля не работают, когда приложение закрыто. (iOS)
Сообщение
Anonymous » 15 янв 2025, 18:41
Мое приложение Flutter получает уведомления с помощью Urban Airship. Я хочу, чтобы эти уведомления перенаправляли пользователя на настраиваемую страницу в зависимости от типа уведомления. В настоящее время это работает так, как и предполагалось, за исключением случаев, когда приложение полностью закрыто. Например, если я коснусь уведомления, когда приложение не было закрыто, проведя его в фоновом режиме, оно просто откроется, не запуская код внутри моего
Код: Выделить всё
Airship.push.onNotificationResponse.listen((event){}
Чтобы проверить это, я клонировал git-репозиторий флаттера дирижабля
https://github.com/urbanairship/airship-flutterи единственное изменение, которое я сделал, это анимация страницы 1 при нажатии на уведомление
Код: Выделить всё
Airship.push.onNotificationResponse.listen((event) {
debugPrint('Notification Response $event');
controller.animateTo(1);
});
это работает только тогда, когда приложение не закрыто (я запускаю свое приложение в режиме выпуска, затем закрываю его, а затем нажимаю на уведомление, которое я отправляю себе с помощью почтальона, чтобы проверить эту функциональность )
опять же, эта функция работает, когда программа открыта или находится в фоновом режиме, но не закрыта.
вот код в файле main.dart< /p>
Код: Выделить всё
import 'package:airship_example/screens/message_center.dart';
import 'package:airship_example/screens/message_view.dart';
import 'package:airship_example/screens/preference_center.dart';
import 'package:airship_example/screens/settings.dart';
import 'package:airship_example/screens/test.dart';
import 'package:flutter/material.dart' hide Notification;
import 'package:airship_example/styles.dart';
import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome;
import 'package:airship_example/screens/home.dart';
// ignore: depend_on_referenced_packages
import 'package:airship_flutter/airship_flutter.dart';
// Supported deep links
const String home_deep_link = "home";
const String message_center_deep_link = "message_center";
const String settings_deep_link = "settings";
@pragma('vm:entry-point')
Future backgroundMessageHandler(PushReceivedEvent event) async {
debugPrint("Background Push Received $event");
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
var config = AirshipConfig(
androidConfig: AndroidConfig(
notificationConfig: AndroidNotificationConfig(
icon: "ic_notification",
)),
defaultEnvironment: ConfigEnvironment(
appKey: KEY,
appSecret: SECRET,
logLevel: LogLevel.verbose,
ios: IOSEnvironment(logPrivacyLevel: AirshipLogPrivacyLevel.public)),
);
Airship.takeOff(config);
Airship.push.android
.setBackgroundPushReceivedHandler(backgroundMessageHandler);
Airship.push.iOS.setForegroundPresentationOptions([
IOSForegroundPresentationOption.banner,
IOSForegroundPresentationOption.list
]);
Airship.contact.identify(USERID);
Airship.messageCenter.setAutoLaunchDefaultMessageCenter(false);
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
// ignore: library_private_types_in_public_api
_MyAppState createState() => _MyAppState();
}
// SingleTickerProviderStateMixin is used for animation
class _MyAppState extends State with SingleTickerProviderStateMixin {
late TabController controller;
final GlobalKey key = GlobalKey();
@override
void initState() {
super.initState();
controller = TabController(length: 4, vsync: this);
initPlatformState();
addFlutterTag();
trackFeatureFlagInteraction();
// Uncomment to enable Hybrid Composition on Android
// InboxMessageView.hybridComposition = true;
}
static void trackFeatureFlagInteraction() {
Airship.featureFlagManager.flag("rad_flag").then((flag) {
Airship.featureFlagManager.trackInteraction(flag);
}).catchError((e) {
debugPrint('Error: $e');
});
}
static void addFlutterTag() {
Airship.channel.addTags(["flutter"]);
}
// Platform messages are asynchronous, so we initialize in an async method.
Future initPlatformState() async {
Airship.push.onPushReceived.listen((event) {
debugPrint('Push Received $event');
});
Airship.push.onNotificationResponse.listen((event) {
debugPrint('Notification Response $event');
controller.animateTo(1);
});
Airship.push.onPushTokenReceived.listen((event) {
debugPrint('Push token received $event');
});
Airship.push.onNotificationStatusChanged.listen((event) {
debugPrint('Notification status changed $event');
});
Airship.push.iOS.onAuthorizedSettingsChanged.listen((event) {
debugPrint('Authorized settings changed $event');
});
Airship.push.iOS.authorizedNotificationSettings
.then((value) => debugPrint("authorizedNotificationSettings $value"));
Airship.push.iOS.authorizedNotificationStatus
.then((value) => debugPrint("authorizedNotificationStatus $value"));
Airship.onDeepLink.listen((event) {
const home_tab = 0;
const message_tab = 1;
const settings_tab = 2;
switch (event.deepLink) {
case home_deep_link:
{
controller.animateTo(home_tab);
break;
}
case message_center_deep_link:
{
controller.animateTo(message_tab);
break;
}
case settings_deep_link:
{
controller.animateTo(settings_tab);
break;
}
}
});
Airship.inApp.onEmbeddedInfoUpdated
.listen((event) => debugPrint('Embedded info updated $event'));
Airship.messageCenter.onInboxUpdated
.listen((event) => debugPrint('Inbox updated $event'));
Airship.messageCenter.onDisplay
.listen((event) => debugPrint('Show inbox $event'));
Airship.messageCenter.onDisplay.listen((event) {
key.currentState
?.push(MaterialPageRoute(builder: (BuildContext context) {
return event.messageId != null
? MessageView(
messageId: event.messageId ?? "",
)
: SizedBox();
}));
});
Airship.channel.onChannelCreated.listen((event) {
debugPrint('Channel created $event');
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
navigatorKey: key,
title: "Airship Sample App ",
theme: ThemeData(
primaryColor: Styles.borders,
colorScheme: ColorScheme.fromSwatch().copyWith(
secondary: Styles.airshipBlue, // Set the accent color to airshipBlue
),
switchTheme: SwitchThemeData(
trackColor:
WidgetStateProperty.all(Styles.airshipBlue), // Set track color
),
),
initialRoute: "/",
routes: {
'/': (context) => tabBarView(),
},
);
}
Widget bottomNavigationBar() {
return Container(
color: Styles.borders, // Set the same color as the tab bar
child: SafeArea(
bottom: true,
child: Material(
color: Colors.transparent,
child: Container(
color: Styles.borders,
child: TabBar(
indicatorColor: Styles.airshipRed,
unselectedLabelColor: Colors.grey, // Set unselected label color
labelColor:
Styles.airshipBlue, // Set selected label color to airshipBlue
tabs: const [
Tab(
icon: Icon(Icons.home),
),
Tab(
icon: Icon(Icons.inbox),
),
Tab(
icon: Icon(Icons.menu),
),
Tab(
icon: Icon(Icons.settings),
),
],
controller: controller,
),
),
),
),
);
}
Widget tabBarView() {
return PopScope(
// ignore: deprecated_member_use
onPopInvoked: null,
child: Scaffold(
backgroundColor: Styles.borders,
body: TabBarView(
controller: controller,
children: const [
Home(),
MessageCenter(),
PreferenceCenter(),
Settings()
],
),
bottomNavigationBar: bottomNavigationBar(),
),
);
}
}
Полный код можно найти в репозитории git
https://github.com/urbanairship/airship-flutter
Подробнее здесь:
https://stackoverflow.com/questions/791 ... closed-ios
1736955694
Anonymous
Мое приложение Flutter получает уведомления с помощью Urban Airship. Я хочу, чтобы эти уведомления перенаправляли пользователя на настраиваемую страницу в зависимости от типа уведомления. В настоящее время это работает так, как и предполагалось, за исключением случаев, когда приложение полностью закрыто. Например, если я коснусь уведомления, когда приложение не было закрыто, проведя его в фоновом режиме, оно просто откроется, не запуская код внутри моего [code]Airship.push.onNotificationResponse.listen((event){} [/code] Чтобы проверить это, я клонировал git-репозиторий флаттера дирижабля https://github.com/urbanairship/airship-flutterи единственное изменение, которое я сделал, это анимация страницы 1 при нажатии на уведомление [code]Airship.push.onNotificationResponse.listen((event) { debugPrint('Notification Response $event'); controller.animateTo(1); }); [/code] это работает только тогда, когда приложение не закрыто (я запускаю свое приложение в режиме выпуска, затем закрываю его, а затем нажимаю на уведомление, которое я отправляю себе с помощью почтальона, чтобы проверить эту функциональность ) опять же, эта функция работает, когда программа открыта или находится в фоновом режиме, но не закрыта. вот код в файле main.dart< /p> [code]import 'package:airship_example/screens/message_center.dart'; import 'package:airship_example/screens/message_view.dart'; import 'package:airship_example/screens/preference_center.dart'; import 'package:airship_example/screens/settings.dart'; import 'package:airship_example/screens/test.dart'; import 'package:flutter/material.dart' hide Notification; import 'package:airship_example/styles.dart'; import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome; import 'package:airship_example/screens/home.dart'; // ignore: depend_on_referenced_packages import 'package:airship_flutter/airship_flutter.dart'; // Supported deep links const String home_deep_link = "home"; const String message_center_deep_link = "message_center"; const String settings_deep_link = "settings"; @pragma('vm:entry-point') Future backgroundMessageHandler(PushReceivedEvent event) async { debugPrint("Background Push Received $event"); } void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); var config = AirshipConfig( androidConfig: AndroidConfig( notificationConfig: AndroidNotificationConfig( icon: "ic_notification", )), defaultEnvironment: ConfigEnvironment( appKey: KEY, appSecret: SECRET, logLevel: LogLevel.verbose, ios: IOSEnvironment(logPrivacyLevel: AirshipLogPrivacyLevel.public)), ); Airship.takeOff(config); Airship.push.android .setBackgroundPushReceivedHandler(backgroundMessageHandler); Airship.push.iOS.setForegroundPresentationOptions([ IOSForegroundPresentationOption.banner, IOSForegroundPresentationOption.list ]); Airship.contact.identify(USERID); Airship.messageCenter.setAutoLaunchDefaultMessageCenter(false); runApp(MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override // ignore: library_private_types_in_public_api _MyAppState createState() => _MyAppState(); } // SingleTickerProviderStateMixin is used for animation class _MyAppState extends State with SingleTickerProviderStateMixin { late TabController controller; final GlobalKey key = GlobalKey(); @override void initState() { super.initState(); controller = TabController(length: 4, vsync: this); initPlatformState(); addFlutterTag(); trackFeatureFlagInteraction(); // Uncomment to enable Hybrid Composition on Android // InboxMessageView.hybridComposition = true; } static void trackFeatureFlagInteraction() { Airship.featureFlagManager.flag("rad_flag").then((flag) { Airship.featureFlagManager.trackInteraction(flag); }).catchError((e) { debugPrint('Error: $e'); }); } static void addFlutterTag() { Airship.channel.addTags(["flutter"]); } // Platform messages are asynchronous, so we initialize in an async method. Future initPlatformState() async { Airship.push.onPushReceived.listen((event) { debugPrint('Push Received $event'); }); Airship.push.onNotificationResponse.listen((event) { debugPrint('Notification Response $event'); controller.animateTo(1); }); Airship.push.onPushTokenReceived.listen((event) { debugPrint('Push token received $event'); }); Airship.push.onNotificationStatusChanged.listen((event) { debugPrint('Notification status changed $event'); }); Airship.push.iOS.onAuthorizedSettingsChanged.listen((event) { debugPrint('Authorized settings changed $event'); }); Airship.push.iOS.authorizedNotificationSettings .then((value) => debugPrint("authorizedNotificationSettings $value")); Airship.push.iOS.authorizedNotificationStatus .then((value) => debugPrint("authorizedNotificationStatus $value")); Airship.onDeepLink.listen((event) { const home_tab = 0; const message_tab = 1; const settings_tab = 2; switch (event.deepLink) { case home_deep_link: { controller.animateTo(home_tab); break; } case message_center_deep_link: { controller.animateTo(message_tab); break; } case settings_deep_link: { controller.animateTo(settings_tab); break; } } }); Airship.inApp.onEmbeddedInfoUpdated .listen((event) => debugPrint('Embedded info updated $event')); Airship.messageCenter.onInboxUpdated .listen((event) => debugPrint('Inbox updated $event')); Airship.messageCenter.onDisplay .listen((event) => debugPrint('Show inbox $event')); Airship.messageCenter.onDisplay.listen((event) { key.currentState ?.push(MaterialPageRoute(builder: (BuildContext context) { return event.messageId != null ? MessageView( messageId: event.messageId ?? "", ) : SizedBox(); })); }); Airship.channel.onChannelCreated.listen((event) { debugPrint('Channel created $event'); }); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, navigatorKey: key, title: "Airship Sample App ", theme: ThemeData( primaryColor: Styles.borders, colorScheme: ColorScheme.fromSwatch().copyWith( secondary: Styles.airshipBlue, // Set the accent color to airshipBlue ), switchTheme: SwitchThemeData( trackColor: WidgetStateProperty.all(Styles.airshipBlue), // Set track color ), ), initialRoute: "/", routes: { '/': (context) => tabBarView(), }, ); } Widget bottomNavigationBar() { return Container( color: Styles.borders, // Set the same color as the tab bar child: SafeArea( bottom: true, child: Material( color: Colors.transparent, child: Container( color: Styles.borders, child: TabBar( indicatorColor: Styles.airshipRed, unselectedLabelColor: Colors.grey, // Set unselected label color labelColor: Styles.airshipBlue, // Set selected label color to airshipBlue tabs: const [ Tab( icon: Icon(Icons.home), ), Tab( icon: Icon(Icons.inbox), ), Tab( icon: Icon(Icons.menu), ), Tab( icon: Icon(Icons.settings), ), ], controller: controller, ), ), ), ), ); } Widget tabBarView() { return PopScope( // ignore: deprecated_member_use onPopInvoked: null, child: Scaffold( backgroundColor: Styles.borders, body: TabBarView( controller: controller, children: const [ Home(), MessageCenter(), PreferenceCenter(), Settings() ], ), bottomNavigationBar: bottomNavigationBar(), ), ); } } [/code] Полный код можно найти в репозитории git https://github.com/urbanairship/airship-flutter Подробнее здесь: [url]https://stackoverflow.com/questions/79115192/airship-flutter-notification-taps-not-working-when-the-app-is-closed-ios[/url]