【FCM 与 APN 接入】使用 Expo 的推送服务接入 ReactNative 项目

本贴最后更新于 490 天前,其中的信息可能已经事过境迁

接入前准备

本文使用 Expo 开发,使用 dev-client 构建来进行的真机测试。

由于通知服务只支持物理设备,所以为了方便调试,使用 eas 的开发构建打包

需要一个谷歌账号,一个苹果开发者账号,iOS 真机,Android 真机调试。

需要 Firebase 云消息服务(FCM),APN(苹果通知)。

接收推送

调整 eas 配置

调整 eas.json 如下:我们在其中一个构建(这里是 preview)里加上

"preview": {
        "developmentClient": true,
        "android": {
        "buildType": "apk",//apk方便android测试
      },
      "distribution": "internal"
    },
"developmentClient": true

安装通知包

npx exop install expo-notifications

配置 App.json

插件部分设置小图标和声音。

"plugins": [
      [
        "expo-notifications",
        {
          "icon": "./local/assets/notification-icon.png",
          "color": "#ffffff",
          "sounds": [
            "./local/assets/notification-sound.wav",
            "./local/assets/notification-sound-other.wav"
          ]
        }
      ]
    ]

配置 APP.js

首先创建一个工具函数,来实现通知服务的注册与通知权限的申请。

import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import {Platform} from "react-native";

// 后端测试通知 https://expo.dev/notifications
export async function registerForPushNotificationsAsync() {
    let token;
       console.log('test notify')
        token = (await Notifications.getExpoPushTokenAsync({
            //这里更换expo用户名/slug
            experienceId:"@yfd/w-rtk"
        })).data;

           console.log('token')
           console.log(token);

    if (Device.isDevice) {
        console.log('获取通知权限')
        const { status: existingStatus } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus;
        console.log(finalStatus)
        if (existingStatus !== 'granted') {
            const { status } = await Notifications.requestPermissionsAsync();
            finalStatus = status;
        }
        if (finalStatus !== 'granted') {
            alert("未授予通知权限")

            return;
        }

        console.log(token);
    } else {
//        alert("推送限制真机")
        console.warn("非物理设备,推送不可用")
    }

    if (Platform.OS === 'android') {
        Notifications.setNotificationChannelAsync('default', {
            name: 'default',
            importance: Notifications.AndroidImportance.MAX,
            vibrationPattern: [0, 250, 250, 250],
            lightColor: '#FF231F7C',
        }).catch((er)=>{
            console.log('error')
            console.error(er)
        })
    }

    return token;
}

我们这里使用 expo 的推送,由他接管 FCM 与 APN,也可以自行接入后端。首先注册 expo 的设备 id(后期推送使用),注册后,一般情况不会更改一直有效(除非卸载,或者主动变更)。这个 token 这里暂时用不上,一会测试使用这个(注册后提交到后端,根据 token 来识别推送设备)

expo 通知流程

Diagram explaining sending a push from your server to device

设置监听

在 app.js 里设置通知。

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

  useEffect(() => {
	//使用刚才的工具函数注册设备
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

   	//应用在前台监听回调
    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    //后台通知触发回调
    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      console.log(response);
    });

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

到此准备好了接收,需要构建一个测试包了。

构建 android

eas build --platform --profile preview 

构建 iOS

eas build --platform ios --profile preview

iOS 需要提交 Testflight 安装到设备。

启动开发调试

eas start --dev-client

打开手机上的应用,应该是 expo 的工具,输入本地调试地址,局域网加入连接。

发送推送

配置 firebase

打开控制台设置新的项目 Firebase,创建的 android 项目包名要一致。随后下载 google-services.json 文件。放入 RN 项目里。更改 app.json->android 配置:加入文件路径

"android": {
    "googleServicesFile": "./google-services.json",
    ...
  }

上传凭证到 expo 后台

企业微信截图 16692782566627.png

在 firebase 这里,找到密钥复制下来,打开 expo 后台该项目找到凭证上传,找到 FCM,添加即可,也可以在本地使用终端:expo push:android:upload --api-key xxxtoken

配置完成后 使用 expo 推送工具测试 其中 To (Expo push token from your app) 就是刚才的设备 token。

点击发送后,手机应该已经收到了,小米设备可能被折叠在其他通知里,注意不要发送随意的字符,会被折叠。

02509a247a9ef3758edaf8120bd0bcb1.jpg

为什么没有 APN 的配置,因为 eas submit 的时候会自动帮你配置,手动狗头。

更多资料 https://docs.expo.dev/push-notifications/overview/

  • Expo
    3 引用
  • React

    React 是 Facebook 开源的一个用于构建 UI 的 JavaScript 库。

    192 引用 • 291 回帖 • 444 关注
  • iOS

    iOS 是由苹果公司开发的移动操作系统,最早于 2007 年 1 月 9 日的 Macworld 大会上公布这个系统,最初是设计给 iPhone 使用的,后来陆续套用到 iPod touch、iPad 以及 Apple TV 等产品上。iOS 与苹果的 Mac OS X 操作系统一样,属于类 Unix 的商业操作系统。

    84 引用 • 139 回帖
  • Android

    Android 是一种以 Linux 为基础的开放源码操作系统,主要使用于便携设备。2005 年由 Google 收购注资,并拉拢多家制造商组成开放手机联盟开发改良,逐渐扩展到到平板电脑及其他领域上。

    331 引用 • 315 回帖 • 83 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...