React-native-firebase: registerHeadlessTask('RNFirebaseBackgroundMessage' does not triggered function

Created on 26 Jul 2019  路  25Comments  路  Source: invertase/react-native-firebase


Issue



index.js

const NotificationHandler = async (message) => {
    console.warn('RNFirebaseBackgroundMessage: ', message);
    return Promise.resolve();
};

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => NotificationHandler);

NotificationHandler does not get triggered although I have made the following changes.


Project Files






iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [ ] I'm using Pods and my Podfile looks like:

# N/A
#### `AppDelegate.m`:
// N/A


Android

Click To Expand

#### `android/build.gradle`:

// N/A
#### `android/app/build.gradle`:
implementation 'me.leolin:ShortcutBadger:1.1.21@aar'
#### `android/settings.gradle`:
// N/A
#### `MainApplication.java`:
new RNAppAuthPackage(),
new RNFirebasePackage(),
new RNFirebaseCrashlyticsPackage(),
new RNFirebaseMessagingPackage(),
new RNFirebaseNotificationsPackage()
#### `AndroidManifest.xml`:
<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" />


Environment

Click To Expand

**`react-native info` output:**

 OUTPUT GOES HERE
- **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 - **`Firebase` module(s) you're using that has the issue:** "react-native": "0.59.9", "react-native-firebase": "5.2.2", "react-native-image-picker": "^1.0.1", "react-native-open-notification": "^0.1.3", "react-native-shortcutbadger": "^0.2.0", - **Are you using `TypeScript`?** - `N`




Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

Android Messaging Docs Stale >= 6

Most helpful comment

I found solution! Server send to server body with notification and data, we must send only data.

All 25 comments

Same for me, I did the following:

The foreground and tapping on notifications work, but the handler in bgMessaging.js is never called and I also see no errors.

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.

Hi all,

how i can debug message in bgMessaging.js when i got notification in background and kill app. I can receive notififation when app in background or kill app. it look like AppRegistry.registerHeadlessTask() never run.

I did it all:

sorry for my bad english and thank you.

Hi, I too got the same issue, HeadlessJSTask is not triggered when app is killed. I think this causes to not having head's-up notification. Could you please look into it

If the app is fully killed it's just dead. Nothing is running. That's the way mobile devices work.

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.

Me too. i did all the required step. But did not run the headless js task

@blastering66 I had an issue when originally setting my project up that if I did not register the headless task very early in startup, it would not run for some reason. When I made headless task registration happen during my bootstrapper object's construction - prior to rendering the root view etc - it worked.

So you might try putting that registration very early in your project startup and see if that helps things.

When migrating from 5.x.x to 6.0.2 I had convert my previous registration to the new TASK_KEY value.

Not sure if it applies to you but I had to go from:

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => backgroundHandler)

To:

AppRegistry.registerHeadlessTask('ReactNativeFirebaseMessagingHeadlessTask', () => backgroundHandler)

@adamfellon yes! and it's not in the migration list for messaging - could you hit the edit button on the top-right here and propose a change? https://invertase.io/oss/react-native-firebase/migrating-to-v6

Sure added: https://github.com/invertase/react-native-firebase/pull/2806

Hope it reads well, words are hard :D

Thanks for sending up the PR. I mentioned this on the PR but mentioning it here for others also;

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => backgroundHandler);

should be changed to:

firebase.messaging().setBackgroundMessageHandler(backgroundHandler);

Docs: https://invertase.io/oss/react-native-firebase/v6/messaging/reference/module#setBackgroundMessageHandler

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.

Hello, could yo help me?
My app don't work in background mode (AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => Push.hanldeBackgroundMessages);).
React native version 0.59.10.
android/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 21
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
}
repositories {
mavenCentral()
jcenter()
google()
maven {url 'https://maven.fabric.io/public'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath 'com.google.gms:google-services:4.2.0'
classpath 'io.fabric.tools:gradle:1.25.4'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

}

subprojects {
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 28 //do this in android/app/build.gradle too
buildToolsVersion '28.0.3' //do this in android/app/build.gradle too
}
}
}
}

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

app/build.gradle
apply plugin: "com.android.application"
apply plugin: "io.fabric"

import com.android.build.OutputFile

/**

  • The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
  • and bundleReleaseJsAndAssets).
  • These basically call react-native bundle with the correct arguments during the Android build
  • cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
  • bundle directly from the development server. Below you can see all the possible configurations
  • and their defaults. If you decide to add a configuration block, make sure to add it before the
  • apply from: "../../node_modules/react-native/react.gradle" line.
    *
  • project.ext.react = [
  • // the name of the generated asset file containing your JS bundle
  • bundleAssetName: "index.android.bundle",
    *
  • // the entry file for bundle generation
  • entryFile: "index.android.js",
    *
  • // whether to bundle JS and assets in debug mode
  • bundleInDebug: false,
    *
  • // whether to bundle JS and assets in release mode
  • bundleInRelease: true,
    *
  • // whether to bundle JS and assets in another build variant (if configured).
  • // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
  • // The configuration property can be in the following formats
  • // 'bundleIn${productFlavor}${buildType}'
  • // 'bundleIn${buildType}'
  • // bundleInFreeDebug: true,
  • // bundleInPaidRelease: true,
  • // bundleInBeta: true,
    *
  • // whether to disable dev mode in custom build variants (by default only disabled in release)
  • // for example: to disable dev mode in the staging build type (if configured)
  • devDisabledInStaging: true,
  • // The configuration property can be in the following formats
  • // 'devDisabledIn${productFlavor}${buildType}'
  • // 'devDisabledIn${buildType}'
    *
  • // the root of your project, i.e. where "package.json" lives
  • root: "../../",
    *
  • // where to put the JS bundle asset in debug mode
  • jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
    *
  • // where to put the JS bundle asset in release mode
  • jsBundleDirRelease: "$buildDir/intermediates/assets/release",
    *
  • // where to put drawable resources / React Native assets, e.g. the ones you use via
  • // require('./image.png')), in debug mode
  • resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
    *
  • // where to put drawable resources / React Native assets, e.g. the ones you use via
  • // require('./image.png')), in release mode
  • resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
    *
  • // by default the gradle tasks are skipped if none of the JS files or assets change; this means
  • // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
  • // date; if you have any other folders that you want to ignore for performance reasons (gradle
  • // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
  • // for example, you might want to remove it from here.
  • inputExcludes: ["android/", "ios/"],
    *
  • // override which node gets called and with what additional arguments
  • nodeExecutableAndArgs: ["node"],
    *
  • // supply additional arguments to the packager
  • extraPackagerArgs: []
  • ]
    */

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 {
configurations.all {
resolutionStrategy {
force 'com.google.android.gms:play-services-gcm:16.1.0'
force 'com.google.android.gms:play-services-basement:16.2.0'
force 'com.google.android.gms:play-services-auth:16.0.1'
force 'com.google.firebase:firebase-messaging:18.0.0'
force 'com.google.firebase:firebase-common:17.0.0'
force 'com.google.firebase:firebase-iid:18.0.0'
force 'com.google.android.gms:play-services-stats:16.0.1'
force 'com.google.android.gms:play-services-base:16.0.1'
}
}
compileSdkVersion 28
buildToolsVersion '28.0.2'

defaultConfig {
    applicationId "com.wanda.carelink"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    missingDimensionStrategy 'react-native-camera', 'general'
    versionCode 41
    versionName "3.2.1"
    multiDexEnabled true
    //    ndk {
    //         abiFilters "armeabi-v7a", "x86"
    //     }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
signingConfigs {
    release {
        if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
            storeFile file(MYAPP_RELEASE_STORE_FILE)
            storePassword MYAPP_RELEASE_STORE_PASSWORD
            keyAlias MYAPP_RELEASE_KEY_ALIAS
            keyPassword MYAPP_RELEASE_KEY_PASSWORD
        }
    }
}
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"
        signingConfig signingConfigs.release
    }
}
aaptOptions {
    additionalParameters "--no-version-vectors"
}

// 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]
        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-sound')
implementation project(':@react-native-community_async-storage')
compile project(':ihealthlibrary-react-native')
compile project(':react-native-splash-screen')
compile project(':react-native-ble-manager')
compile project(':react-native-touch-id')
compile project(':react-native-keychain')
compile project(':react-native-barcode-scanner-google')
implementation project(':react-native-bluetooth-status')
implementation project(':realm')
implementation project(':react-native-vector-icons')
implementation project(':react-native-svg')
implementation project(':react-native-push-notification')
implementation project(':react-native-linear-gradient')
implementation project(':react-native-firebase')
implementation project(':react-native-device-info')
implementation project(':appcenter-crashes')
implementation project(':appcenter-analytics')
implementation project(':appcenter')
implementation project(':react-native-push-notification')
implementation project(':react-native-svg')
implementation project(':react-native-device-info')
implementation project(':realm')
implementation project(':react-native-vector-icons')
implementation project(':react-native-linear-gradient')

implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-v7:27.1.0" // please take this code required for build release apk
implementation "com.facebook.react:react-native:0.59.10"
implementation "me.leolin:ShortcutBadger:1.1.21@aar"

implementation 'com.twilio:video-android:5.0.0'
implementation "com.koushikdutta.ion:ion:2.1.7"
implementation "com.android.support:preference-v14:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"

// Firebase dependencies
implementation "com.google.android.gms:play-services-base:16.1.0"
implementation "com.google.firebase:firebase-core:16.0.9"
implementation "com.google.firebase:firebase-messaging:18.0.0"
implementation('com.crashlytics.sdk.android:crashlytics:2.9.5@aar') {
  transitive = true
 }

 implementation 'com.google.android.gms:play-services-vision:15.0.2'
 implementation project(':react-native-camera')

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}

apply plugin: 'com.google.gms.google-services'

com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

@volodymyrFilatenko - if you're still using v5, it's possible to get it working but the versions still move fast enough (implying bugfixes), and maintainer time here is limited enough that you should make sure you are on all up to date versions of all underlying dependencies and this module before wasting any time troubleshooting old versions), then I'd open a fresh issue with full details as requested in the issue template

Hello, I have updated react native to 0.61.5 version and firebase to 5.6.0, but background mode doesn't work(. Could you help me? I can send build.gradle and AndroidManifest.

if you are certain you implemented it correctly in all other ways but it is still not working, you need to make sure that you are registering the headless task outside the lifecycle of the app, to be specific - as soon in your application startup as possible, before you have registered the app itself with react-native

If I correct understand then I did true. My index.js
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';

import { receivePatientSurveysChange, receivePatientRemindersChange, receiveClientConfigChange } from 'src/services/notificationHelper';
import * as Push from 'src/services/pushnotification';
import * as Twilio from 'src/services/twilio/video';

console.disableYellowBox = true;

Twilio.setupVideoCallHandler();

receivePatientSurveysChange();
receivePatientRemindersChange();
receiveClientConfigChange();

AppRegistry.registerComponent(appName, () => App);
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => Push.hanldeBackgroundMessages);

And handleBackgroundMessages body:
export async function hanldeBackgroundMessages(message) {
console.log('test');
handleNotification(message);
return Promise.resolve();
}

switch headless task before register component -> that's what I meant, try that?

thanks, but this not helped(. If I correct understood
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => {
console.log('test');
return Promise.resolve();
});
AppRegistry.registerComponent(appName, () => App)

I found solution! Server send to server body with notification and data, we must send only data.

Hi @volodymyrFilatenko, I have sent data only, but still get this error:
com.facebook.react.common.JavascriptException: TypeError: undefined is not a function (near '...taskProvider()(data).then...'), stack:
startHeadlessTask

May I know how you solve the registerHeadlessTask problem?

I found solution! Server send to server body with notification and data, we must send only data.

Thanks so much

Currently the task name has change to ReactNativeFirebaseMessagingHeadlessTask, which also works with notification payload.

const NotificationHandler = async (message) => {
  console.warn('RNFirebaseBackgroundMessage1: ', message);
  return Promise.resolve();
};
AppRegistry.registerHeadlessTask(
  'ReactNativeFirebaseMessagingHeadlessTask',
  () => NotificationHandler,
);
Was this page helpful?
0 / 5 - 0 ratings