Я использовал FCM вместе с локальным уведомлением Flutter для получения сообщений. Локальное уведомление Flutter используется для отображения уведомлений, когда приложение находится на переднем плане. В настоящее время я использую Android 12 (Poco X3 PRO).
Когда я закрываю приложение и отправляю сообщение из консоли Firebase, в логарифме появляется следующее сообщение.
2022-07-26 07:40:16.751 11370-11370/? W/GCM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=au.org.nrna.test.app (has extras) }
Я проверил документацию по облачным сообщениям Firebase, связанную ЗДЕСЬ, однако там нет упоминания об обработке сообщений в завершенном состоянии.
Аналогично, когда приложение на переднем плане сообщение отображается только в области уведомлений. Он вообще не отображается на экране.
ФАЙЛ: main.dart
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:device_preview/device_preview.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'core/apps/app.dart';
import 'core/apps/device_preview_app.dart';
import 'core/bloc_observers/bloc_observer.dart';
import 'core/config_reader/config_reader.dart';
import 'core/injections/injections.dart';
import 'core/routes/app_router.gr.dart';
final appRouter = AppRouter();
void main() async {
BlocOverrides.runZoned(
() async {
runZonedGuarded(() async {
initAndRunApp();
},
(error, stack) => FirebaseCrashlytics.instance
.recordError(error, stack, fatal: true));
},
blocObserver: MyBlocObserver(),
);
}
void onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) {
// display a dialog with the notification details, tap ok to go to another page
debugPrint(
'Notification[#$id] - Title: $title, Body: $body Payload: $payload');
}
void onSelectNotification(String? payload) {
if (payload != null) {
Map payloadMap = jsonDecode(payload);
debugPrint(payloadMap.toString());
}
}
Future _setupPushNotification() async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('launch_background');
const IOSInitializationSettings iosInitializationSettings =
IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
const InitializationSettings initializationSettings = InitializationSettings(
iOS: iosInitializationSettings,
android: androidInitializationSettings,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
final bool? result = await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
var androidDetails = const AndroidNotificationDetails(
'com.test.app.notification_channel',
'Test Notification Channel',
channelDescription: 'Notification Channel for Test App for Android',
priority: Priority.high,
);
var iosDetails = const IOSNotificationDetails();
var generalNotificationDetails =
NotificationDetails(android: androidDetails, iOS: iosDetails);
FirebaseMessaging.onBackgroundMessage(_onBackgroundMessageHandler);
FirebaseMessaging.onMessage.listen((message) {
debugPrint(
'FCM NOTIFICATION[#${message.messageId}] - Data: ${message.data} Title: ${message.notification?.title} Body: ${message.notification?.body}');
RemoteNotification? notification = message.notification;
AndroidNotification? androidNotification = message.notification?.android;
AppleNotification? appleNotification = message.notification?.apple;
String? payloadJsonStr;
if (message.data.isNotEmpty) {
payloadJsonStr = jsonEncode(message.data);
}
if (notification != null && androidNotification != null) {
flutterLocalNotificationsPlugin.show(notification.hashCode,
notification.title, notification.body, generalNotificationDetails,
payload: payloadJsonStr);
}
});
}
Future _onBackgroundMessageHandler(RemoteMessage message) async {
debugPrint(
'Background FCM NOTIFICATION[#${message.messageId}] - Data: ${message.data} Title: ${message.notification?.title} Body: ${message.notification?.body}');
}
Future _initialiseApp() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// setup Push Notifications
_setupPushNotification();
// Pass all uncaught errors from the framework to Crashlytics.
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
// GetIt configuration
configureDependencies();
await getIt().initialize();
}
Future initAndRunApp() async {
await _initialiseApp();
Isolate.current.addErrorListener(RawReceivePort((pair) async {
final List errorAndStacktrace = pair;
await FirebaseCrashlytics.instance.recordError(
errorAndStacktrace.first,
errorAndStacktrace.last,
fatal: true,
);
}).sendPort);
final fcmToken = await FirebaseMessaging.instance.getToken();
debugPrint(fcmToken);
if (!kReleaseMode && getIt().isDevicePreviewEnabled) {
runApp(
DevicePreview(
enabled: !kReleaseMode,
builder: (context) => const DevicePreviewApp(), // Wrap your app
),
);
} else {
runApp(const MyApp());
}
}
ФАЙЛ: AndroidManifest.xml
Подробнее здесь: https://stackoverflow.com/questions/731 ... -is-closed
Flutter - сообщение FCM не приходит, когда приложение закрыто ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1732736458
Anonymous
Я использовал FCM вместе с локальным уведомлением Flutter для получения сообщений. Локальное уведомление Flutter используется для отображения уведомлений, когда приложение находится на переднем плане. В настоящее время я использую Android 12 (Poco X3 PRO).
Когда я закрываю приложение и отправляю сообщение из консоли Firebase, в логарифме появляется следующее сообщение.
2022-07-26 07:40:16.751 11370-11370/? W/GCM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=au.org.nrna.test.app (has extras) }
Я проверил документацию по облачным сообщениям Firebase, связанную ЗДЕСЬ, однако там нет упоминания об обработке сообщений в завершенном состоянии.
Аналогично, когда приложение на переднем плане сообщение отображается только в области уведомлений. Он вообще не отображается на экране.
[b]ФАЙЛ:[/b] main.dart
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:device_preview/device_preview.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'core/apps/app.dart';
import 'core/apps/device_preview_app.dart';
import 'core/bloc_observers/bloc_observer.dart';
import 'core/config_reader/config_reader.dart';
import 'core/injections/injections.dart';
import 'core/routes/app_router.gr.dart';
final appRouter = AppRouter();
void main() async {
BlocOverrides.runZoned(
() async {
runZonedGuarded(() async {
initAndRunApp();
},
(error, stack) => FirebaseCrashlytics.instance
.recordError(error, stack, fatal: true));
},
blocObserver: MyBlocObserver(),
);
}
void onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) {
// display a dialog with the notification details, tap ok to go to another page
debugPrint(
'Notification[#$id] - Title: $title, Body: $body Payload: $payload');
}
void onSelectNotification(String? payload) {
if (payload != null) {
Map payloadMap = jsonDecode(payload);
debugPrint(payloadMap.toString());
}
}
Future _setupPushNotification() async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('launch_background');
const IOSInitializationSettings iosInitializationSettings =
IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
const InitializationSettings initializationSettings = InitializationSettings(
iOS: iosInitializationSettings,
android: androidInitializationSettings,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
final bool? result = await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
var androidDetails = const AndroidNotificationDetails(
'com.test.app.notification_channel',
'Test Notification Channel',
channelDescription: 'Notification Channel for Test App for Android',
priority: Priority.high,
);
var iosDetails = const IOSNotificationDetails();
var generalNotificationDetails =
NotificationDetails(android: androidDetails, iOS: iosDetails);
FirebaseMessaging.onBackgroundMessage(_onBackgroundMessageHandler);
FirebaseMessaging.onMessage.listen((message) {
debugPrint(
'FCM NOTIFICATION[#${message.messageId}] - Data: ${message.data} Title: ${message.notification?.title} Body: ${message.notification?.body}');
RemoteNotification? notification = message.notification;
AndroidNotification? androidNotification = message.notification?.android;
AppleNotification? appleNotification = message.notification?.apple;
String? payloadJsonStr;
if (message.data.isNotEmpty) {
payloadJsonStr = jsonEncode(message.data);
}
if (notification != null && androidNotification != null) {
flutterLocalNotificationsPlugin.show(notification.hashCode,
notification.title, notification.body, generalNotificationDetails,
payload: payloadJsonStr);
}
});
}
Future _onBackgroundMessageHandler(RemoteMessage message) async {
debugPrint(
'Background FCM NOTIFICATION[#${message.messageId}] - Data: ${message.data} Title: ${message.notification?.title} Body: ${message.notification?.body}');
}
Future _initialiseApp() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// setup Push Notifications
_setupPushNotification();
// Pass all uncaught errors from the framework to Crashlytics.
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
// GetIt configuration
configureDependencies();
await getIt().initialize();
}
Future initAndRunApp() async {
await _initialiseApp();
Isolate.current.addErrorListener(RawReceivePort((pair) async {
final List errorAndStacktrace = pair;
await FirebaseCrashlytics.instance.recordError(
errorAndStacktrace.first,
errorAndStacktrace.last,
fatal: true,
);
}).sendPort);
final fcmToken = await FirebaseMessaging.instance.getToken();
debugPrint(fcmToken);
if (!kReleaseMode && getIt().isDevicePreviewEnabled) {
runApp(
DevicePreview(
enabled: !kReleaseMode,
builder: (context) => const DevicePreviewApp(), // Wrap your app
),
);
} else {
runApp(const MyApp());
}
}
[b]ФАЙЛ:[/b] AndroidManifest.xml
Подробнее здесь: [url]https://stackoverflow.com/questions/73117054/flutter-fcm-message-not-coming-when-app-is-closed[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия