React Native Push Notification Not Working Properly

5.2k views Asked by At

Push Notification function:

PushNotification.configure({
  largeIcon: "ic_launcher",
  smallIcon: "ic_notification",
  onNotification: function (notification) {
    PushNotification.localNotification({
      autoCancel: true,
      message: 'Test Message',
      title: 'Test Message',
      vibrate: true,
      vibration: 300,
      playSound: true,
      soundName: 'default'
    })
    console.log(notification)
  },
});

Problem:

  1. When I run application, if I send notification from php server I am getting response in console.log

but

condition 1: PushNotification.localNotification() foreground not working.

condition 2: PushNotification.localNotification() background not working.

  1. If I send notification from firebase server I am getting response in console.log

but

condition 3: PushNotification.localNotification() foreground not working.

condition 4: PushNotification.localNotification() background working.

And after I get first notification from firebase server, i.e. condition 4, my application started receiving notifications from all other 3 conditions, mentioned above, also. Strange but I tested many time

  1. If I click on notification then notification still visible in bar
  2. And on OnePlus9 device overall notifications are not working.

I am getting response from php server:

    {
       "data": 
       {
          "message": "Your order with order no OID63112 has been dispatched. Expected time for arrival is 30 min", 
           "title": "Picked up order", 
           "vibrate": "1"
       }, 
       "from": "326331584681", 
       "messageId": "0:1607089521078208%d58aa421f9fd7ecd", 
       "sentTime": 1607089521064, 
       "ttl": 2419200
   }

I am getting response from firebase server:

   {   
       "channelId": "fcm_fallback_notification_channel", 
       "color": null, 
       "data": {}, 
       "finish": [Function finish], 
       "foreground": true, "id": "-1787502606", 
       "message": "Enjoy your meat! Order Online!",
       "priority": "high", 
       "sound": null, 
       "tag": "campaign_collapse_key_4040075812614528488", 
       "title": "Freshcut", 
       "userInteraction": false, 
       "visibility": "private"
    }

My Configurations are

"@react-native-firebase/app": "^8.4.7",
    "@react-native-firebase/crashlytics": "^8.4.9",
    "@react-native-firebase/database": "^10.0.0",
    "@react-native-firebase/messaging": "^7.9.0",
    "react-native-push-notification": "^6.1.3",

android/build.gradle

 ext {
        buildToolsVersion = "29.0.2"
        minSdkVersion = 19
        compileSdkVersion = 29
        targetSdkVersion = 29
        googlePlayServicesVersion = "+" // default: "+"
        firebaseMessagingVersion = "+" // default: "+"
    }

android/app/src/main/AndroidManifest.xml

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <permission
        android:name="com.freshcut.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.freshcut.permission.C2D_MESSAGE" />
<!-- Change the value to true to enable pop-up for in foreground (remote-only, for local use ignoreInForeground) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        <!-- Change the resource name to your App's accent color - or any other color you want -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->
 
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
 
        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

I am not able to get the exact problem, I read all other issues too and tried different solutions but nothing worked out. I am new to react-native-puch-notification.

2

There are 2 answers

0
Safi Deraiya On BEST ANSWER

DEFINE A NAME FOR YOUR NOTIFICATION CHANNEL It can be anything, and you will use it to target your custom channel from your push message, so that the custom sound you will tie to your channel plays. I should note that after installing the app the channel name will remain registered until the app is uninstalled. So keep that in mind if you change channel names later.

ADD YOUR SOUND AS A RESOURCE Drag your .wav sound into the your_project_root/android/app/src/main/res/raw folder (if it doesn’t exist, create it). ADD THE NOTIFICATION CHANNEL CODE:

First Add All The MainActivity Imports

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;

The code below must be placed inside the onCreate method of your MainActivity class. Fill in the text surrounded in brackets with your own, and customize anything else you need on your notification:

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      NotificationChannel notificationChannel = new NotificationChannel("my_default_channel", "Tallo", NotificationManager.IMPORTANCE_HIGH);
      notificationChannel.setShowBadge(true);
      notificationChannel.setDescription("");
      AudioAttributes att = new AudioAttributes.Builder()
              .setUsage(AudioAttributes.USAGE_NOTIFICATION)
              .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
              .build();
      notificationChannel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/sample"), att);
      notificationChannel.enableVibration(true);
      notificationChannel.setVibrationPattern(new long[]{400, 400});
      notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
      NotificationManager manager = getSystemService(NotificationManager.class);
      manager.createNotificationChannel(notificationChannel);
    }
  }
Here’s a code example with some values filled in

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          NotificationChannel notificationChannel = new NotificationChannel("new_email_arrived_channel", "My Emailer", NotificationManager.IMPORTANCE_HIGH);
          notificationChannel.setShowBadge(true);
          notificationChannel.setDescription("");
          AudioAttributes att = new AudioAttributes.Builder()
                  .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                  .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                  .build();
          notificationChannel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/my_custom_sound"), att);
          notificationChannel.enableVibration(true);
          notificationChannel.setVibrationPattern(new long[]{400, 400});
          notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
          NotificationManager manager = getSystemService(NotificationManager.class);
          manager.createNotificationChannel(notificationChannel);
      }

SET UP THE PUSH BODY Now that your request is configured, let’s add the push body. This is done in the body tab in the empty area under the data type options. Here is an example body:

{
    "to": "<FCM TOKEN>",
    "notification": {
      "title": "Some title",
        "body": "Some body",
        "sound": "my_custom_sound.wav",
        "android_channel_id": "new_email_arrived_channel"
    },
    "data": {
        "field1": "value1",
        "field2": "value2"
    },
    "content_available": true,
    "priority": "high"
}
0
Kishan Bharda On

You have to subscribe the firebase notification to receive notification. So first subscribe firebase notification using onMessage() method of messaging. After subscribing whenever message will receive from firebase, fire the localNotification to pop the notification in foreground more with the title, message and other data that you have received in remoteMessage as below :

useEffect(() => {
  const unsubscribe = messaging().onMessage(async (remoteMessage) => {
    PushNotification.localNotification({
      message: remoteMessage.notification.body,
      title: remoteMessage.notification.title,
      bigPictureUrl: remoteMessage.notification.android.imageUrl,
      userInfo: remoteMessage.data,
    });
  });

  return unsubscribe;
}, []);