React-native-firebase: RNFirebaseBackgroundMessage don't work

Created on 27 Apr 2018  路  11Comments  路  Source: invertase/react-native-firebase

It is impossible to adjust Windows 10. Notices when applications in a background don't come. Help me please

Index.js

import {AppRegistry} from 'react-native';

import App from './app/index';
import BackgroundNotifications from './app/assets/libs/BackgroundNotifications';

AppRegistry.registerComponent('templateRN', () => App);

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', BackgroundNotifications);

BackgroundNotifications.js

import firebase from 'react-native-firebase';
import Notice from "./notice";
import {Alert} from 'react-native';

export default async (message) => {
    // handle your message
    console.log(message);
    Alert.alert('BackgroundNotification', '111');
    await Notice.send({
        id       : 'main',
        title    : 'title 1',
        subtitle : 'subtitle 1',
        body     : 'body 1',
        actions  : [
            new firebase.notifications.Android.Action('action', 'icon', 'title')
                .setSemanticAction(firebase.notifications.Android.SemanticAction.Reply)
                .setShowUserInterface(true)
                .addRemoteInput(
                    new firebase.notifications.Android.RemoteInput('answer')
                        .setLabel('answer')
                )
        ]
    });

    return Promise.resolve();
}

AndroidManifest.xml

<application ...>
        ...
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
        <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
        <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"/>
</application>
  1. Application Target Platform: Windows 10
  2. Development Operating System: Android Studio - Nexus 5 Android 6.0 Marshmallow
  3. Build Tools:
react-native-cli: 2.0.1
react-native: 0.54.4
react-native-firebase: 4.0.0
Notifications Android Waiting for User Response

Most helpful comment

@fitimvata I was able to make it work with splash screen (sorta).

Change your splash screen class to this:

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);

        // NOTE: This is necessary to forward the original intent on to the main activity.
        // This makes firebase.notifications().getInitialNotification() work.
        intent.putExtras(this.getIntent());

        startActivity(intent);
        finish();
    }
}

Unfortunately I still haven't figured out how to make onNotificationOpened handler work yet. Will post back if I figure it out.

All 11 comments

Can you check if something like this exists in your MainApplication.java?

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }

MainApplication.java

package com.qdanik.templatern;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.rnfs.RNFSPackage;
import com.BV.LinearGradient.LinearGradientPackage;
import io.invertase.firebase.RNFirebasePackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import io.invertase.firebase.RNFirebasePackage;
// optional packages - add/remove as appropriate
import io.invertase.firebase.admob.RNFirebaseAdMobPackage; //Firebase AdMob
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; // Firebase Analytics
import io.invertase.firebase.auth.RNFirebaseAuthPackage; // Firebase Auth
import io.invertase.firebase.config.RNFirebaseRemoteConfigPackage; // Firebase Remote Config
import io.invertase.firebase.database.RNFirebaseDatabasePackage; // Firebase Realtime Database
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage; // Firebase Firestore
import io.invertase.firebase.instanceid.RNFirebaseInstanceIdPackage; // Firebase Instance ID
import io.invertase.firebase.links.RNFirebaseLinksPackage; // Firebase Dynamic Links
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // Firebase Cloud Messaging
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; // Firebase Notifications
import io.invertase.firebase.perf.RNFirebasePerformancePackage; // Firebase Performance
import io.invertase.firebase.storage.RNFirebaseStoragePackage; // Firebase Storage
import io.invertase.firebase.fabric.crashlytics.RNFirebaseCrashlyticsPackage; // Crashlytics

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            new RNFSPackage(),
            new LinearGradientPackage(),
            new RNFirebasePackage(),
            // add/remove these packages as appropriate
            new RNFirebaseAdMobPackage(),
            new RNFirebaseAnalyticsPackage(),
            new RNFirebaseAuthPackage(),
            new RNFirebaseCrashlyticsPackage(),
            new RNFirebaseDatabasePackage(),
            new RNFirebaseFirestorePackage(),
            new RNFirebaseInstanceIdPackage(),
            new RNFirebaseLinksPackage(),
            new RNFirebaseMessagingPackage(),
            new RNFirebaseNotificationsPackage(),
            new RNFirebasePerformancePackage(),
            new RNFirebaseRemoteConfigPackage(),
            new RNFirebaseStoragePackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

AndroidManifest.xml

   <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      tools:replace="android:allowBackup">
      <!-- Notification -->
      <!-- <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_ic_notification" /> -->
      <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />
      <service
        android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
      </service>
      <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
        <intent-filter>
          <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
      </service>
      <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

      <!-- Local Notifications -->
      <!-- <receiver android:name="io.invertase.firebase.messaging.RNFirebaseLocalMessagingPublisher"/>
      <receiver android:enabled="true" android:exported="true" android:name="io.invertase.firebase.messaging.RNFirebaseSystemBootEventReceiver">
        <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"/>
          <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
      </receiver> -->

      <activity
        android:name=".SplashActivity"
        android:theme="@style/SplashTheme"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="stateUnspecified|adjustResize"
        android:launchMode="singleTop"
        android:exported="true" />
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

SplashActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

MainActivity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SplashScreen.show(this);
        super.onCreate(savedInstanceState);
    }

App.js

this.notificationOpenedListener = firebase.notifications()
  .onNotificationOpened((notificationOpen: NotificationOpen) => {
    // Get the action triggered by the notification being opened
    const { action } = notificationOpen
    // Get information about the notification that was opened
    const { notification }: { notification: Notification } = notificationOpen
    this.handleNotification(notification)
    console.log(notification, action, 'notificationOpenedListener')
  })

notificationOpenedListener not listening on notitification click when using react-native-splash-screen

I don't use splash-screen, but thx for your guide.

How to disable background notifications, when app closed?

When the app is closed, if the app is registered for notifications and you send a notification it will receive them - there is no way to disable them as such, without not sending them.

I'd take it you have fixed your initial issue? Can I close this?

Yes, close this. Thx all

@fitimvata I was able to make it work with splash screen (sorta).

Change your splash screen class to this:

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);

        // NOTE: This is necessary to forward the original intent on to the main activity.
        // This makes firebase.notifications().getInitialNotification() work.
        intent.putExtras(this.getIntent());

        startActivity(intent);
        finish();
    }
}

Unfortunately I still haven't figured out how to make onNotificationOpened handler work yet. Will post back if I figure it out.

Thanks a lot @runia1 thanks to your code my getInitialNotification() finally works! But the onNotificationOpened still doesn't, do you know if it's still a problem with the SplashScreen?

@avencat I still haven't figured that out. I suspect it DOES have something to do with SplashScreen but not sure what.

@runia1 @avencat Did you guys figured out a way to make onNotificationOpened work? I am now stuck with this, Any help would be greatly appreciated :)

Was this page helpful?
0 / 5 - 0 ratings