我已经使用flutter_local_notification包创建了一个自定义通知,当我使用FCM发送通知时,两个通知在应用程序的前台和后台状态都可见。当我点击FCM生成的通知时,其工作正常,但当点击自定义后台通知时,我的应用程序启动,但无法运行我的逻辑,所以请帮助我处理后台自定义通知
点击后台自定义通知时,会显示以下信息
尝试启动重复的背景分离菌株。正在返回...
class NotificationService {
static final NotificationService _notificationService =
NotificationService._private();
NotificationService._private();
factory NotificationService() => _notificationService;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
final AndroidNotificationChannel _androidChannel =
const AndroidNotificationChannel(
'high_importance_channel', // id
'Notifications', // title
description: 'important notification channel', // description
importance: Importance.high,
playSound: true);
final AndroidInitializationSettings _initializationSettingsAndroid =
const AndroidInitializationSettings(
'app_icon',
);
///This functions initializes Flutterlocalnotificationplugin with required settings and channels
initialize() async {
AndroidFlutterLocalNotificationsPlugin? resp =
flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
await resp!.createNotificationChannel(_androidChannel);
resp.requestPermission();
var initializationSettings =
InitializationSettings(android: _initializationSettingsAndroid);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onDidReceiveNotificationResponse: _handleForegroundNotification,
onDidReceiveBackgroundNotificationResponse:
_handleBackgroundNotification);
}
/// This function create the custom notifcation.
/// before calling this function , firebaseLocalNotification instance should be initialized
showNotification(RemoteMessage message) {
var initializationSettings =
InitializationSettings(android: _initializationSettingsAndroid);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onDidReceiveNotificationResponse: _handleForegroundNotification,
onDidReceiveBackgroundNotificationResponse:
_handleBackgroundNotification);
flutterLocalNotificationsPlugin.show(
1123,
message.data['title'],
message.data['body'],
const NotificationDetails(
android: AndroidNotificationDetails(
'1123',
'channel.name',
channelDescription: 'channel.description',
color: Colors.blue,
playSound: true,
),
));
}
}
///This functions handle background notification press and performs given instructions
@pragma('vm:entry-point')
_handleBackgroundNotification(NotificationResponse response) async {
await Future.delayed(Duration(seconds: 3));
Fluttertoast.showToast(
msg: "backgrrrround call nice no",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
///This functions handel foregroud notification press and performs given instruction
_handleForegroundNotification(NotificationResponse response) async {
await Future.delayed(Duration(seconds: 3));
Fluttertoast.showToast(
msg: "Forerground call nice no",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
另一类用于管理FCM
class FCMService {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
String? fcmToken;
///This function initialized FCM and start stream of token,foregroundmessage,backgroundmessage
initialize() async {
fcmToken = await FirebaseMessaging.instance.getToken();
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
debugPrint(fcmToken);
_listenToTokenStream();
_listenToForegroundMessage();
}
// /Handle background but not teminated app notification press
_listenToOnMessageOpenedApp() {
//when
FirebaseMessaging.onMessageOpenedApp.listen((message) {
print("FCM>>>>>>>> backgroud");
});
}
/// Request permission for higher sdk version
_requestNotificationPermission() async {
NotificationSettings settings = await _firebaseMessaging.requestPermission(
alert: true,
sound: true,
);
debugPrint('User granted permission: ${settings.authorizationStatus}');
}
/// listen to foreground message recieved from FCM
_listenToForegroundMessage() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
NotificationService().showNotification(message);
});
}
///Listen to streamm of token when token expires helps us to updat it
_listenToTokenStream() {
FirebaseMessaging.instance.onTokenRefresh.listen((token) {
fcmToken = token;
debugPrint(fcmToken);
}).onError((e) {
debugPrint("token refresh failed");
});
}
}
///listen background message recieve from FCM , DO NOT: perform heavy task in background
///otherwise your process may get killed
Future<void> fcmBackgroundMessageHandler(RemoteMessage message) async {
await Firebase.initializeApp();
// await NotificationService().initialize();
NotificationService().showNotification(message);
}
主要方法:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FCMService().initialize();
NotificationService().initialize();
FirebaseMessaging.onBackgroundMessage(fcmBackgroundMessageHandler);
runApp(const MyApp());
}
1条答案
按热度按时间ff29svar1#
你应该在FCM初始化时监听后台消息,但是你是在main上做的,所以删除它并在FCM初始化中添加选项。
我已经更新了您的代码与所需的更新。