如何为我的聊天应用程序使用 websocket 支持 Capacitor 中的推送通知

问题描述 投票:0回答:1

我没有找到任何正确的解决方案来使用 websocket 实现推送通知。

我的简单需求,例如 WhatsApp 聊天,当消息到来时,以推送通知的形式显示消息。

这里是推送通知的文档

/**
 *  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
});

}

javascript ionic-framework push-notification capacitor
1个回答
4
投票

我建议不要使用 websocket 来推送通知,因为 websocket 会占用大量资源。当您的应用程序处于后台时,您也无法保持它,当您的应用程序不在前台时,手机的操作系统可能会限制您的应用程序的活动。我建议使用电容器插件,例如电容器推送通知。这些插件使用操作系统提供的底层方法。

此外,如果您正在使用基于 Web 的解决方案,那么开发 TLS Websocket 连接可能会具有挑战性。 Webview 通常不提供对此类低级功能的直接访问。如果您最终想使用 websocket,您需要实现本机解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.