gpt4 book ai didi

android - 通过在后台运行的推送通知做出 native react

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:17 25 4
gpt4 key购买 nike

我正在尝试使用此插件实现推送通知 react-native-push-notifications .我成功的是在应用程序运行时(在前台)获得通知,但我想要做的是在应用程序关闭(后台)、未运行以及我收到进入应用程序的通知时获得通知。

我的代码

 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 中测试。

当我在后台发送时,我在 postman 中测试时得到成功响应

{
"success": {
"results": [
{
"messageId": "0:1526575831372268%a0cec506f9fd7ecd"
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 0,
"successCount": 1,
"multicastId": 8639210245128054000
}

但我没有在设备中(在后台)获取它

最佳答案

看起来好像您正在发送一条包含 notificationdata 负载的云消息。为了让 Android 应用在应用处于后台时在收到消息时唤醒,您只能发送带有 data 负载的消息。

查看这些文档——尤其是关于“静默远程推送通知”的部分: https://github.com/zo0r/react-native-push-notification/blob/master/trouble-shooting.md

和 FCM 文档以获取更多信息: https://firebase.google.com/docs/cloud-messaging/android/receive

关于android - 通过在后台运行的推送通知做出 native react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50396289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com