react-native-firebase推送通知未显示在前台

时间:2019-12-02 16:35:11

标签: android firebase react-native push-notification react-native-firebase

我正在尝试通过react-native-firebase软件包推送通知,但该推送通知仅在后台运行,而不在前台运行。

这是我的课程

import React from 'react';
import {Alert, AsyncStorage} from 'react-native';
import {GoogleSignin, GoogleSigninButton, statusCodes} from '@react-native-community/google-signin';
import SplashScreen from './component/splashscreen';
import {AccessToken, GraphRequest, GraphRequestManager, LoginButton} from 'react-native-fbsdk';
import firebase from 'react-native-firebase';

class Login extends React.Component {
    state = {userInfo: '', isSignInProgress: false, loggedIn: true, loading: false};

    async componentDidMount() {
        const enabled = await firebase.messaging().hasPermission();

        if (enabled) {
            await this.getToken();
        } else {
            await this.requestPermission();
        }

        await this.createNotificationListeners();

        if (await AsyncStorage.getItem('name') && await AsyncStorage.getItem('photo')) {
            this.props.navigation.replace('Index');
        } else {
            this.setState({
                loggedIn: false,
                loading: false,
            });
        }
    }

    componentWillUnmount() {
        this.notificationListener();
        this.notificationOpenedListener();
    }

    showAlert = (title, body) => {
        Alert.alert(
            title, body,
            [
                {text: 'OK', onPress: () => console.log('OK Pressed')},
            ],
            {cancelable: false},
        );
    };

    async createNotificationListeners() {
        const channel = new firebase.notifications.Android.Channel('test-channel', 'test-channel', firebase.notifications.Android.Importance.Max)
            // .setDescription('channel_name')
            .setSound('default');
        await firebase.notifications().android.createChannel(channel);
        /*
        * Triggered when a particular notification has been received in foreground
        * */
        this.notificationListener = firebase.notifications().onNotification(async notification => {
            const {title, body} = notification;
            const localNotification = new firebase.notifications.Notification({
                sound: 'default',
                show_in_foreground: true,
            })
                .setNotificationId(new Date().valueOf().toString())
                .setTitle('a')
                .setSound('default')
                .setBody('a')
                .setData({
                    now: new Date().toISOString(),
                    payload: data,
                })
                .android.setAutoCancel(true)
                .android.setBigText(body)
                // .android.setLargeIcon('ic_launchers')
                .android.setVibrate(1000)
                .android.setColor('#74c900')
                .android.setColorized(true)
                .android.setChannelId('test-channel') // e.g. the id you chose above
                // .android.setSmallIcon('ic_launchers') // create this icon in Android Studio
                .android.setPriority(firebase.notifications.Android.Priority.High);

            firebase
                .notifications()
                .displayNotification(localNotification);
            this.showAlert(title, body);
        });


        /*
        * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
        * */
        this.notificationOpenedListener = firebase.notifications().onNotificationOpened(notificationOpen => {
            const {title, body} = notificationOpen.notification;
            this.showAlert(title, body);
        });

        /*
        * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
        * */
        const notificationOpen = await firebase.notifications().getInitialNotification();
        if (notificationOpen) {
            const {title, body} = notificationOpen.notification;
            this.showAlert(title, body);
        }
        /*
        * Triggered for data only payload in foreground
        * */
        this.messageListener = firebase.messaging().onMessage((message) => {
            //process data message
            alert(JSON.stringify(message));
            console.log(JSON.stringify(message));
        });
    }

    async getToken() {
        const fcmToken = await firebase.messaging().getToken();
        await AsyncStorage.setItem('fcmToken', fcmToken);
        console.log(fcmToken);
    }

    async requestPermission() {
        try {
            await firebase.messaging().requestPermission();
            // User has authorised
            this.getToken();
        } catch (error) {
            // User has rejected permissions
            console.log('permission rejected');
        }
    }

    render() {
        if (this.state.loading) {
            return <SplashScreen/>;
        } else {
            return (
                <Text>App Page<Text/>
            );
        }
    }

}


export default Login;

这是我的android清单xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
        <meta-data android:name="com.facebook.sdk.ApplicationId"
                   android:value="@string/facebook_app_id"/>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustResize">
        <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_icon"
                android:resource="@drawable/ic_launcher" />

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

        <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
        <receiver android:enabled="true"
                  android:exported="true"
                  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
            <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>
    </application>

</manifest>

这是strings.xml

<resources>
    <string name="app_name">Tnt</string>
    <string name="facebook_app_id">2905xxxx</string>
    <string name="default_notification_channel_id" translatable="false">test-channel</string>
</resources>

有什么建议吗?我已经尝试为FCM申请该渠道,真的适用吗?

我的react-native-firebase版本是"^5.5.6",我的react-native-firebase版本是"0.61.2"

项目:https://github.com/ericanthonywu/mobileTNT

0 个答案:

没有答案