React-native-firebase: 馃敟background notification not trigger on Android API =< 25

Created on 14 Apr 2019  路  8Comments  路  Source: invertase/react-native-firebase

Issue

Hey guys I have a small issue I hoped you can help me with. I am building a notification listener and I struggle to make it work properly on background on Android API <= 25. As I can see the notification going right to the tray, it never showing the heads up notification. It works great on API >= 26.
This is my notification listener, hope someone could point me to a relevant GH issue or something I am pretty hopeless at this point! lol


// channel 

    const channel = new firebase.notifications.Android.Channel(
      "channel1",
      "channel1",
      firebase.notifications.Android.Importance.Max
    )
      .setDescription("My apps test channel")
      .setVibrationPattern([500])
      .setSound("default");

    firebase.notifications().android.createChannel(channel);

// listener
      this.notificationListener = firebase
        .notifications()
        .onNotification(async message => {
          const notification = new firebase.notifications.Notification({
            sound: "default",
            show_in_foreground: true
          })
            .setNotificationId("notificationId")
            .setTitle(message._title)
            .android.setChannelId("channel1")
            .android.setSmallIcon("@mipmap/ic_launcher")
            .android.setPriority(firebase.notifications.Android.Priority.High)
            .setSound("default")
            .setBody(message._body)
            .setData({
              key1: "value1",
              key2: "value2"
            });

          firebase.notifications().displayNotification(notification);
        });

Thank you!


Project Files

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.2"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 27
        supportLibVersion = "28.0.0"

    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
              // ADD THIS
        maven { url 'https://maven.google.com' }

        // ADD THIS
        maven { url "https://jitpack.io" }
    }
}


task wrapper(type: Wrapper) {
    gradleVersion = '4.7'
    distributionUrl = distributionUrl.replace("bin", "all")
}



android/app/build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        applicationId "com.inlinebiz"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':react-native-firebase')
    implementation project(':react-native-splash-screen')
    implementation project(':react-native-share')


    implementation project(':tipsi-stripe')

    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation "com.google.firebase:firebase-messaging:17.3.4"
    implementation "com.google.firebase:firebase-core:16.0.6"


    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

    implementation project(':react-native-picker')
    implementation project(':react-native-languages')
    implementation project(':react-native-branch')
    implementation project(':react-native-photo-view')
    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-image-crop-picker')
    implementation project(':react-native-image-picker')
    implementation project(':react-native-orientation-locker')
    implementation project(':react-native-vector-icons')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation project(':react-native-svg')

}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

AndroidManifest.xml

<manifest xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.appYanted">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
        tools:replace="android:allowBackup"
      android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                tools:replace="android:resource"
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
      <activity
          android:launchMode="singleTop"
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
          android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>


        <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id"/>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_launcher_notif" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/notification_icon_color" />

    </application>

</manifest>

Environment

  • Platform that you're experiencing the issue on:

    • [ ] iOS

    • [x] Android

    • [ ] iOS but have not tested behavior on Android

    • [ ] Android but have not tested behavior on iOS

    • [ ] Both

  • If known, the version of the platform are you experiencing the issue on:

    • Android API =< 25

  • Operating System:

    • [x] MacOS, version: N/A

    • [ ] Windows, version: N/A

    • [ ] Other, please specify: N/A

  • Build Tools:

    • Android Studio

  • React Native version:

    • 0.57.8

  • React Native Firebase library version:

    • 5.2.3

  • Firebase module(s) you're using that has the issue:

    • [x] N/A

    • [ ] Authentication

    • [ ] Analytics

    • [ ] Cloud Firestore

    • [x] Cloud Messaging (FCM)

    • [ ] Crashlytics

    • [ ] Dynamic Links

    • [ ] Functions Callable

    • [x] In App Messaging

    • [ ] Indexing

    • [ ] Invites

    • [ ] Instance ID

    • [ ] ML Kit

    • [ ] Notifications

    • [ ] Performance Monitoring

    • [ ] Realtime Database

    • [ ] Remote Config

    • [ ] Storage

  • Are you using TypeScript?

    • [x] No

    • [ ] Yes, version: N/A

  • Are you using Expo, e.g. ExpoKit?

    • [x] No

    • [ ] Yes, I've _not_ ejected

    • [ ] Yes, but I have ejected to ExpoKit

    • [ ] Yes, but I have ejected to vanilla React Native

    • Expo version: N/A


Notifications Question Stale

Most helpful comment

Reopen issue, the same problem.

All 8 comments

Update

After long.. LONG research I couldn't make it work using notification as the payload, therefore I moved to use data instead by implementing the stage 4 here. so now all notifications on android comes through it. In case someone know how to make it work using notification payload it will be great. (:

Edit

The problem using data is it make the IOS not working at all. so what I did is to leave the onNotification listener in my App.js, and the onMessage listener in my bgMessage.js and in my server I am sending the notification payload with proper property for each of the platforms. i.e.

const payloadType = platform == "ios" ? "notification" : "data"
const payload = {
  [payloadType]: {
      title,
      body
    }
}

So this is my workaround to make it work cross platform.

This is not an answer, just a hunch. The android 25->26 API move added the notification channels. If you have a notification type it is trying to display, and trying to use the channel because of the API level. But for APIs below 26 - where there is no notification channel support - I wonder if you are actually throwing an exception in java about notification channel APIs missing for the platform and need to put an API guard around it somehow? You might check the logs carefully with an eye towards the channel, or try without setting the channel. I don't have experience in react-native / javascript with channels but I come from the Java Android side and this was a big deal there - smells the same to me. Good luck

I am stuck on the same issue. I have followed all the steps correctly but as soon as I kill the app notifications are not triggered I even changed my app settings to Don't Optimise still i am not getting the notifications.

Hello 馃憢, to help manage issues we automatically close stale issues.
This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs.
Thank you for your contributions.

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

Reopen issue, the same problem.

No, better to open a fresh issue (if you have not already) following the full issue template with your specific information. You might want to watch logcat (unfiltered! just adb logcat) on a device that exhibits the problem while you are reproducing it, and post that.

I am also facing same issue

Was this page helpful?
0 / 5 - 0 ratings