Search code examples
androidreact-nativehuawei-mobile-serviceshuawei-push-notification

How do I get 'onMessageReceived' to trigger on Notification (HMS Push Kit) in React Native?


I'm trying to read the payload of my notifications, but the event won't trigger. It works fine for Data messages, but doesn't seem to notice notifications.

AndroidManifest:

        <service
            android:name="com.huawei.hms.push.react.RNHmsMessageService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <receiver android:name="com.huawei.hms.push.react.RNReceiver"/>
        <meta-data
            android:name="push_kit_auto_init_enabled"
            android:value="true" />

RNHmsMessageService

public void onMessageReceived(RemoteMessage message) {
        Log.i(TAG, "onMessageReceived is called");
        if (message == null) {
            Log.e(TAG, "Received message entity is null!");
            return;
        }

        Log.i(TAG, "getCollapseKey: " + message.getCollapseKey()...

        RemoteMessage.Notification notification = message.getNotification();
        if (notification != null) {
            Log.i(TAG, "\n getImageUrl: " + notification.getImageUrl()...
        }

        Boolean judgeWhetherIn10s = false;
        // If the messages are not processed in 10 seconds, the app needs to use WorkManager for processing.
        if (judgeWhetherIn10s) {
            startWorkManagerJob(message);
        } else {
            // Process message within 10s
            processWithin10s(message);
        }
    }

build.gradle

implementation 'com.huawei.hms:push:4.0.4.301'

I think that message.getNotification() is always null, thus not triggering.


Solution

  • For Notification Message use the below code snippet.

    If the app is opened by a push notification click, the remote message can be retrieved by calling HmsPush.getInitialNotification If the app is not opened by a push notification click, it returns null.

    async function getInitialNotification(){
      try{
         console.log(await HmsPush.getInitialNotification())
      }catch(ex){
         console.log(ex)
      }
    }
    

    Here's a link!

    This is included in latest plugin release [Cordova Push Plugin 5.0.2 (2020-09-30)]. This will work for sure.