Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get setBackgroundMessageHandler to work

In react-native-firebase v6, I can't get setBackgroundMessageHandler to work in my app. Notifications are received just fine but the handler is not executed.

I have done it like in the guide to no avail.

import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-community/async-storage';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

messaging().setBackgroundMessageHandler(async ({ data: { title, message } }) => {
    console.log('in background');
    // Save the notification locally
    const notificationList = JSON.parse(await AsyncStorage.getItem('@SM_NOTIFICATIONS')) || [];
    notificationList.push({ title, message, isRead: false });
    await AsyncStorage.setItem('@SM_NOTIFICATIONS', JSON.stringify(notificationList));
});

Nothing happened beside the incoming notifications. I expected the code to save the incoming notifications in AsyncStorage.

like image 618
Dorklord Avatar asked Oct 27 '19 18:10

Dorklord


1 Answers

Okay. After consulting the developer's team, I finally figure this one out.

First, setBackgroundMessageHandler must be called before registerComponent.

Second, don't send notification data. Only send custom data (silent push). Hence, you need to use local notification instead of push notification to display the notification in system tray.

Because Firebase Console somehow doesn't support silent push, I used FCM API v1 to send data-only. Here is my example:

POST https://fcm.googleapis.com/v1/projects/my-project/messages:send

{
    "validate_only": false,
    "message": {
        "name": "XXX",
        "data": {
            "title": "BG 2",
            "message": "BG BARU"
        },
        "topic": "C3166"
    }
}

As you can see, no notification field in JSON above.

like image 57
Dorklord Avatar answered Sep 21 '22 14:09

Dorklord