我没有找到任何正确的解决方案来实现推送通知与WebSocket。
我的简单要求,如WhatsApp聊天,当消息到来时,它以推送通知的形式显示消息。
Here is the documentation用于推送通知。
/**
* Push notification code
*/
import { PushNotifications } from '@capacitor/push-notifications';
const addListeners = async () => {
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
});
await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});
await PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('Push notification received: ', notification);
});
await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}
const registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();
if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}
if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}
await PushNotifications.register();
}
const getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
/**
Web Socket related code
*/
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Connection opened
socket.addEventListener("open", (event) => {
socket.send("Hello Server!");
});
// Listen for messages
socket.addEventListener("message", (event) => {
console.log("Message from server ", event.data);
PushNotifications.send("Message from server ", event.data); // added for testing but does not work
});
}
1条答案
按热度按时间fykwrbwg1#
我建议不要使用WebSocket推送通知,因为WebSocket占用大量资源。此外,当你的应用程序在后台时,你也不能保持它,手机的操作系统可能会限制你的应用程序在前台时的活动。我建议使用电容器插件,如Capacitor Push Notification。这些插件使用OS提供的底层方法。
此外,如果您正在使用基于Web的解决方案,开发TLS WebSocket连接可能具有挑战性。Webview通常不提供对这种低级功能的直接访问。如果你想最终使用websockets,你需要实现本地解决方案。