我试图实现推送通知与反应本机与此插件反应本机推送通知。我成功的是在应用程序运行时收到通知(在前台),但我想做的是在应用程序关闭时收到通知(后台),不运行,当我收到通知进入应用程序时。
我的密码
componentDidMount() {
this.initEventPushNotification()
this.initPushNotification()
}
initEventPushNotification() {
AppState.addEventListener('change', (state) => {
console.log(state)
if (state === 'background') {
PushNotification.popInitialNotification((notification) => {
if (notification) {
this.onNotification(notification);
}
});
PushNotification.setApplicationIconBadgeNumber(0);
}
if (state === 'active') {
PushNotification.popInitialNotification((notification) => {
if (notification) {
this.onNotification(notification);
}
})
}
});
}
initPushNotification() {
console.log('init')
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
AppStore.setFCMToken(token.token)
FirebaseService.setTokenData(token.token)
},
// (required) Called when a remote or local notification is opened or received
onNotification: function (notification) {
if (!notification.userInteraction) {
PushNotification.setApplicationIconBadgeNumber(0);
}
if (notification) {
console.log(notification)
PushNotification.localNotification({
/* Android Only Properties */
id: '0', // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
ticker: "My Notification Ticker", // (optional)
autoCancel: true, // (optional) default: true
largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
bigText: "My big text that will be shown when notification is expanded", // (optional) default: "message" prop
subText: "This is a subText", // (optional) default: none
color: "red", // (optional) default: system default
vibrate: true, // (optional) default: true
vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
tag: 'some_tag', // (optional) add tag to message
group: "group", // (optional) add group to message
ongoing: false, // (optional) set whether this is an "ongoing" notification
/* iOS only properties */
message: "My Notification Message", // (required)
playSound: false, // (optional) default: true
soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
number: '10', // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
repeatType: 'day', // (Android only) Repeating interval. Could be one of `week`, `day`, `hour`, `minute, `time`. If specified as time, it should be accompanied by one more parameter 'repeatTime` which should the number of milliseconds between each interval
actions: '["Yes", "No"]', // (Android only) See the doc for notification actions to know more
});
}
// process the notification
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
// notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "XXXXXXXXXX1", // my sender ID
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true,
});
}
我正在使用firebase函数发送通知
export const sendNotificationTest = functions.https
.onRequest(async (req, res) => {
try {
const { token } = req.body;
let tokens = "coeC4T6tmeU:APA91bGEQs4MRQXq4C09SKpyK2Oxz7gIKS-QdoGGKeCcxQj2CXGpCD7qe763WnFVgQRer81iZGscASVq-QP7_I81xtCM9vfiPitQJ4P6HFSH3QiGQQljiLPBixsVcCtbDNCZX4z4u8n-"
let payload = {
data: {
body: 'Message body',
title: 'Message title',
color: "#00ACD4",
priority: "high",
icon: "ic_notif",
show_in_foreground: 'true',
channelId:'sqtrivia-channel'
},
notification: {
title: "Alarm",
subtitle: "First Alarm",
body: "First Alarm",
click_action: "com.myapp.MyCategory" // The id of notification category which you defined with FCM.setNotificationCategories
}
};
let options = { priority: "high", contentAvailable: true };
// Set the message as high priority and have it expire after 24 hours.
console.log('token', token)
if(token){
let d = await admin.messaging().sendToDevice(token, payload, options);
return res.status(200).send({ success: d })
}
return res.status(400).send({ error: 'you should send token' })
} catch (e) {
console.info(e)
return res.status(400).send({ error: 0 })
}
})
AndroidManifest。xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moonsite.sqlivetrivia">
<uses-permission android:name="android.permission.INTERNET" />
<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" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="${applicationId}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme">
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</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.RNFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service> -->
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
<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>
<!-- <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_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" /> -->
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTop" >
<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" />
</application>
</manifest>
正如我之前所说的,只有当应用程序运行时,当我使用firebase http功能发送时,我才能成功获得通知。我现在只在Android系统上测试过。
当我在后台发送邮件时,当我在邮递员中测试时,我会得到成功响应
{
"success": {
"results": [
{
"messageId": "0:1526575831372268%a0cec506f9fd7ecd"
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 0,
"successCount": 1,
"multicastId": 8639210245128054000
}
}
但我没有在设备中(在后台)得到它
来自FCM文档https://firebase.google.com/docs/cloud-messaging/android/receive
后台受限应用(Android P或更新版本)
从2019年1月开始,FCM将不会向用户设置为后台限制的应用程序发送消息(如via:Setting)-
您是否尝试添加后台消息处理程序?
如果没有,那么试试这个:
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Your message was handled in background');
});
它看起来像是在发送一条云消息,其中既有通知
又有数据
有效载荷。为了让Android应用程序在后台收到消息时唤醒,您只能发送带有数据
有效负载的消息。
看看这些文档——特别是关于“静默远程推送通知”的部分:https://github.com/zo0r/react-native-push-notification/blob/master/trouble-shooting.md
和FCM文档了解更多信息:https://firebase.google.com/docs/cloud-messaging/android/receive
我正在制作一个带有oneSignal推送通知的react原生应用程序。我只想在收到通知时更改屏幕。如果应用程序位于前台或单击通知,我可以这样做。如果应用程序关闭或处于后台,我将如何触发此操作?
我正在使用Firebase云消息发送推送通知。 和: 在中声明: 问题是,当应用程序运行时,显示良好,通知带有默认声音,但当应用程序在后台或未运行时,通知没有任何声音,而不显示在状态栏中。 为什么会出现这种情况,我如何修复它?
我已经在我的项目上实现了react原生firebase推送通知,它可以与android正常工作,但不会在iOS上显示。 iOS项目包括GoogleService-info.plist文件。 在后台模式下,消息推送和远程通知的项目功能也“开启”。 我已将APNs身份验证密钥添加到Firebase控制台。 当应用程序在设备上运行时,它会向用户请求通知权限 预期结果:android和iOS设备上都会弹出
当应用程序在后台时,如何更新包含数据负载的Firebase推送通知?有没有办法在通知中指定通知id给Firebase API? 完整的项目在github https://github.com/akshatashan/FireBaseCloudMessagingDemo中
我的应用程序有推送通知(FCM)。当应用程序在前台运行时,我可以在onMessageReceived()函数中获取数据负载。当应用程序在后台运行或应用程序完全关闭时,不会调用onMessageReceived()函数。我的问题是,当app在后台或关闭时,是否可能获得数据有效载荷? 提前道谢!