谁能告诉我为什么我的应用程序在显示大约 4 个通知后停止显示通知。 当我安装一个新的模拟器时,通知功能完美运行。但在 4 次通知后,它停止了。它发生在所有模拟器上。
顺便说一下,令牌是通过不同的函数保存在数据库中的。所以我只好把它拿来听听。我认为没有必要再次将其保存在数据库中。还是我错了?
代码:
final String currentUserId = FirebaseAuth.instance.currentUser!.uid;
late AndroidNotificationChannel channel;
/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
String? mtoken = ' ';
@override
void initState() {
super.initState();
requestPermission();
loadFCM();
listenFCM();
getToken();
FirebaseMessaging.instance.subscribeToTopic('RIDE_REQUESTS');
}
void sendPushMessage(
String token,
) async {
try {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key='*******',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'You have received a ride request',
'title': 'RIDE REQUEST'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': 1,
'status': 'done'
},
"to": token,
},
),
);
} catch (e) {
return;
}
}
void getToken() async {
await adsModel.token;
}
void requestPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
} else if (settings.authorizationStatus ==
AuthorizationStatus.provisional) {
} else {}
}
void listenFCM() async {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
// TODO add a proper drawable resource to android, for now using
// one that already exists in example app.
icon: 'launch_background',
),
),
);
}
});
}
void loadFCM() async {
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description: 'A passenger has chosen your ride', // description
importance: Importance.high,
enableVibration: true);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
}
TextButton(String name = adsModel.uid;
if (name != '') { DocumentSnapshot snap = await FirebaseFirestore.instance
.collection('ADS')
.doc(name)
.get();
String mtoken = snap['Token'];
sendPushMessage(mtoken);
})
Main.dart:
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { 等待 Firebase.initializeApp();
// 如果你打算在后台使用其他 Firebase 服务,比如 Firestore, // 确保在使用其他 Firebase 服务之前调用
initializeApp
。
// print('处理后台消息 ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => AuthProvider())],
child: MaterialApp(
title: 'Hitch Ride',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SplashScreen(),
),
);
}
}