我已经使用react-native-fcm
在Android和iPhone中进行远程通知。
在Android前台中,我无法在通知栏中获得远程通知。
在后台模式下,我能够成功获取通知,但在前台却不能。
Android Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nusape">
<application>
<receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
<receiver android:enabled="true" android:exported="true" android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
<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>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher"/>
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="my_default_channel"/>
<service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<activity android:launchMode="singleTop" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="fcm.ACTION.HELLO" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
App.js
async componentDidMount() {
// create NotificationChannel for future use!
FCM.createNotificationChannel({
id: 'my_default_channel',
name: 'Default',
description: 'used for example',
priority: 'high'
});
// initially user get InitialNotification frim the app if any pending
FCM.getInitialNotification().then(notif => {
console.log("getInitialNotification Notification : => ", notif);
// if notif.targetScreen is details screen then it will redirect to details screen directly!
if (notif && notif.targetScreen === "detail") {
setTimeout(() => {
this.props.navigation.navigate("Detail");
}, 500);
}
});
// added notification listener for getting any notification called below function then
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
console.log("FCMEvent.Notification Notification : => ", notif);
if (Platform.OS === 'ios' && notif._notificationType === NotificationType.WillPresent && !notif.local_notification) {
notif.finish(WillPresentNotificationResult.All);
return;
}
// if user tap to notification bar then open app then below condition will follow up and redirect to details screen!
if (notif.opened_from_tray) {
if (notif.targetScreen === 'detail') {
setTimeout(() => {
navigation.navigate('Detail')
}, 500)
}
setTimeout(() => {
alert(`User tapped notification\n${JSON.stringify(notif)}`)
}, 500)
}
// check whether app is in background or foreground for generate notification
if (AppState.currentState !== 'background'){
this.showLocalNotification(notif);
});
// getting user permission for sending notification or not ?
try {
let result = await FCM.requestPermissions({
badge: true,
sound: true,
alert: true
});
console.log("Notification requestPermissions : => ", result)
} catch (e) {
console.error(e);
}
// Generating token for particular user wise send notification
FCM.getFCMToken().then(token => {
FCM.subscribeToTopic("channelToTopic");
console.log("Notification token : => ", token);
this.setState({ token: token || "" });
});
// Get APNSTOKEN for only ios
if (Platform.OS === "ios") {
FCM.getAPNSToken().then(token => {
console.log("APNS TOKEN (getFCMToken)", token);
});
}
}
// show notification when app is in foreground and getting any new notification
showLocalNotification = (notif) => {
FCM.presentLocalNotification({
channel: 'my_default_channel',
id: new Date().valueOf().toString(),
title: notif.fcm.title,
body: notif.fcm.body,
priority: "high",
badge: 1,
number: 1,
ticker: "My Notification Ticker",
auto_cancel: true,
big_text: "Show when notification is expanded",
sub_text: "This is a subText",
wake_screen: true,
group: "group",
icon: "ic_launcher",
ongoing: true,
my_custom_data: "my_custom_field_value",
lights: true,
show_in_foreground: true
});
};
最近两个月以来,我一直在遭受这个问题的困扰,但由于我进行了许多新的尝试来解决问题,但最终没有获得成功,因此我无法像以前那样获得很好的解决方案。
答案 0 :(得分:2)
根据here列出的图书馆问题,您可以尝试两种方法:
只需在您的show_in_foreground
属性的远程通知中传递data
android仅在应用状态被杀死或后台时显示通知。要在应用前景中显示通知,您需要显示local notification
。
示例代码:
FCM.on(FCMEvent.Notification, notif => {
if (!notif.opened_from_tray) {
showLocalNotification();
}
});
showLocalNotification() {
FCM.presentLocalNotification({
id: new Date().valueOf().toString(), // (optional for instant notification)
title: "Test Notification with action", // as FCM payload
body: "Force touch to reply", // as FCM payload (required)
show_in_foreground: true // notification when app is in foreground (local & remote)
});
}
完整代码为here
答案 1 :(得分:2)
您要测试哪个API级别? Android API 26及更高版本要求创建通道以便在前台接收通知。请阅读this了解更多信息。
react-native-fcm
也进行了更新,包括频道,请参考this
尽管不应再使用该库(因为不再维护该库),但是react-native-firebase是一个很好的选择。
答案 2 :(得分:2)
根据官方的Github react-native-fcm, 该库已贬值。 您可以使用 react-native-firebase 用于生成通知。 我能够在大约2个小时的时间内让android收到通知。 如果您需要代码,我可以共享。 祝你好运。
更新-很抱歉,由于我的办公室帐户,我无法早些回答。
这是我用于显示android前台通知的代码。
firebase.messaging()
.subscribeToTopic(this.state.user.user_name)
.then(response => console.log('response from FCM TOPIC' + response))
.catch(error => console.log('error from FCM TOPIC'+ error));
this.notificationListener = firebase.notifications().onNotification(notification => {
let notificationMessage = notification._android._notification._data.action;
let recordId = notification._android._notification._data.recordID;
let { title, body } = notification;
// console.log('ttttt', notification)
// notification.android.setAutoCancel(false)
console.log(title, body, notificationMessage, recordId);
this.getInspectionUserLogs(this.state.user);
const channelId = new firebase.notifications.Android.Channel(
'Default',
'Default',
firebase.notifications.Android.Importance.High
);
firebase.notifications().android.createChannel(channelId);
let notification_to_be_displayed = new firebase.notifications.Notification({
data: notification._android._notification._data,
sound: 'default',
show_in_foreground: true,
title: notification.title,
body: notification.body,
});
if (Platform.OS == 'android') {
notification_to_be_displayed.android
.setPriority(firebase.notifications.Android.Priority.High)
.android.setChannelId('Default')
.android.setVibrate(1000);
}
console.log('FOREGROUND NOTIFICATION LISTENER: \n', notification_to_be_displayed);
firebase.notifications().displayNotification(notification_to_be_displayed);
});