To obtain custom parameters during mobile push cold start in a Flutter or React-Native application, you need to handle the push notification payload and extract the custom data when the app is launched from a terminated state. Here's how to achieve this:
When a push notification is received while the app is closed (cold start), the notification payload is passed to the app upon launch. The custom parameters are typically included in the data field of the push notification (for Firebase Cloud Messaging or similar services). You need to:
firebase_messaging package to handle push notifications.onLaunch callback to capture the notification when the app is launched from a terminated state.Example:
import 'package:firebase_messaging/firebase_messaging.dart';
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
void initPushNotifications() {
// Handle foreground notifications
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Foreground message: ${message.notification?.title}');
});
// Handle cold start (app launched from terminated state)
FirebaseMessaging.onLaunch.listen((RemoteMessage message) {
print('App launched from terminated state');
// Extract custom parameters from the data payload
final Map<String, dynamic> data = message.data;
String customParam = data['custom_param'] ?? 'default_value';
print('Custom parameter: $customParam');
// Use the custom parameter in your app logic
});
// Request permissions and get the FCM token
FirebaseMessaging.instance.requestPermission();
FirebaseMessaging.instance.getToken().then((token) {
print('FCM Token: $token');
});
}
@react-native-firebase/messaging package to handle push notifications.getInitialNotification method to retrieve the notification when the app is launched from a terminated state.Example:
import messaging from '@react-native-firebase/messaging';
async function initPushNotifications() {
// Request permissions
const authStatus = await messaging().requestPermission();
if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) {
console.log('User has granted permission');
}
// Get the FCM token
const token = await messaging().getToken();
console.log('FCM Token:', token);
// Handle cold start (app launched from terminated state)
const initialNotification = await messaging().getInitialNotification();
if (initialNotification) {
console.log('App launched from terminated state');
const data = initialNotification.data;
const customParam = data.custom_param || 'default_value';
console.log('Custom parameter:', customParam);
// Use the custom parameter in your app logic
}
}
// Call this function during app initialization
initPushNotifications();
For reliable push notification delivery and custom parameter handling, consider using Tencent Cloud Push Service. It provides:
Tencent Cloud Push Service ensures your custom parameters are delivered correctly even during cold starts, enhancing user engagement and app functionality.