react-native极光推送集成(jpush-react-native)

之前写了一篇阿里云推送的文章(//www.greatytc.com/p/83092e8817e7),今天把极光推送也和大家分享一下。

  • 1、jpush-react-native 自 1.4.4 之后, 需要安装 jcore-react-native大家一定要注意安装下。
  • 2、然后 npm install jpush-react-native jcore-react-native --save
  • 3、react-native link后根据提示,输入 appKey(在极光推送官网申请应用得到)

IOS

link后iOS还需要几步手动操作
  • 在 iOS 工程中设置 TARGETS-> BUILD Phases -> LinkBinary with Libraries 找到 UserNotifications.frameworkstatus设为optional

  • 在 iOS 工程中如果找不到头文件可能要在 TARGETS-> BUILD SETTINGS -> Search Paths -> Header Search Paths 添加如下路径
    $(SRCROOT)/../node_modules/jpush-react-native/ios/RCTJPushModule(link后应该就已经存在了)

Android

检查Android配置是否齐全

查看 app 下的 build.gradle 配置

android {
    defaultConfig {
        applicationId "yourApplicationId"//yourApplicationId 替换为你的项目的包名
        ...
        manifestPlaceholders = [
                JPUSH_APPKEY: "yourAppKey", //在此替换你的APPKey
                APP_CHANNEL: "default"    //link后此处不用修改
        ]
    }
}
...
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation project(':jpush-react-native')  // 添加 jpush 依赖
    implementation project(':jcore-react-native')  // 添加 jcore 依赖
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

查看 android/settings.gradle下是否存在(此处可能会有重复代码,需仔细检查)

include ':app', ':jpush-react-native', ':jcore-react-native'
project(':jpush-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jpush-react-native/android')
project(':jcore-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jcore-react-native/android')

查看 android/app/AndroidManifest.xml下是否存在

    <application
        ...
        <!-- Required . Enable it you can get statistics data with channel -->
        <meta-data android:name="JPUSH_CHANNEL" android:value="${APP_CHANNEL}"/> //不需要任何改动
        <meta-data android:name="JPUSH_APPKEY" android:value="${JPUSH_APPKEY}"/> //不需要任何改动

    </application>

在项目中引用

import JPushModule from 'jpush-react-native';
jumpSecondActivity () {
    //点击推送消息,在此进行页面跳转
    // this.props.navigation.navigate('Push')

    
    // JPushModule.jumpToPushActivityWithParams('SecondActivity', {
    //   hello: 'world'
    // })

  }
  componentDidMount() {
    // 新版本必需写回调函数
    // JPushModule.notifyJSDidLoad();
    if (Platform.OS === 'android') {
      JPushModule.initPush()
      JPushModule.getInfo(map => {
        this.setState({

        })
      });
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
        }
      })
    } else {
      JPushModule.setupPush()
    }

    // 接收自定义消息
    JPushModule.addReceiveCustomMsgListener((message) => {
      this.setState({pushMsg: message});
    });
    // 接收推送通知
    JPushModule.addReceiveNotificationListener((message) => {
      console.log("receive notification: " + message);
    });
    // 打开通知
    JPushModule.addReceiveOpenNotificationListener((map) => {
      console.log("Opening notification!");
      console.log("map.extra: " + map.extras);
      // 可执行跳转操作,也可跳转原生页面
      // this.props.navigation.navigate("SecondActivity");
    });
  }
  componentWillUnmount() {
    JPushModule.removeReceiveCustomMsgListener();
    JPushModule.removeReceiveNotificationListener();
  }

注意:在极光推送里面注册应用时,推送设置需要分别Android和iOS,Android只需要包名,我就不做说明了,主要说下iOS。

go_to_account_page
  • 从开发者账户页面左侧入口进入 “Certificates, IDs & Profiles” 页面。
go_to_cert_page
  • 创建 App ID,填写 App ID 的 NAME 和 Bundle ID(如果 ID 已经存在可以直接跳过此步骤)。
add_appid
    注: 此处需要指定具体的 Bundle ID 不要使用通配符。

appid_suffix
  • 为 App 开启 Push Notification 功能。如果是已经创建的 App ID 也可以通过设置开启 Push Notification 功能。
appid_service
  • 填写好以上属性后,点击 “Continue”,确认 AppId 属性的正确性,点击 “Register”,注册 AppId 成功。

两种鉴权方式的配置

极光官网应用的鉴权信息一旦配置,只能用相同 bundleID 的鉴权信息进行更新,无法修改为其他的 bundleID,请在配置前仔细检查 bundleID 是否正确。

方式一:通过 .p12 证书鉴权

  • 如果你之前没有创建过 Push 证书或者是要重新创建一个新的,请在证书列表下面新建。
add_cert
  • 新建证书需要注意选择 APNs 证书种类。如图 APNs 证书有开发(Development)和生产(Production)两种。
    注:开发证书用于开发调试使用;生产证书既能用于开发调试,也可用于产品发布。此处我们选择生产证书为例。

cert_type
  • 点击 "Continue", 之后选择该证书准备绑定的 AppID。
cert_to_app
  • 点击 “Continue”,会进入 CSR 说明界面。
need_CSR
  • 再点 “Continue” 会让你上传 CSR 文件。( CSR 文件会在下一步创建)
update_CSR

△△△Certificate Signing Request文件一定要重新生成一个!!!!

  • 打开系统自带的 KeychainAccess 创建 Certificate Signing Request。如下图操作:
open_keychain
  • 填写“用户邮箱”和“常用名称” ,并选择“存储到磁盘”,证书文件后缀为 .certSigningRequest 。
cert_info
  • 回到浏览器中 CSR 上传页面,上传刚刚生成的后缀为 .certSigningRequest 的文件。
  • 生成证书成功后,点击 “Download” 按钮把证书下载下来,是后缀为 .cer 的文件。
cert_ready
  • 双击证书后,会在 “KeychainAccess” 中打开,选择左侧“钥匙串”列表中“登录”,以及“种类”列表中“我的证书”,找到刚才下载的证书,并导出为 .p12 文件。如下图:
export_p12
save_p12
  • 在极光控制台上,进入你应用的应用设置中 iOS 的鉴权方式选择 “证书”,上传刚才导出的 .p12 证书。极光会在后台为你的应用进行鉴权。
  • Apple 的生产推送证书允许用于开发环境的推送,勾选将生产证书用于开发环境,开发者可以仅上传生产证书,即可在官网推送平台处选择开发环境做推送,不用再生成和上传开发证书。
add_to_portal

方式二:通过 APNs Auth Key 鉴权

  • 点击左侧列表 “Keys” 中的 “All”,看账户中是否已有 auth key,没有则点击 “+” 新建。
go_to_add_auth_key
  • 填写该 key 的描述并选择服务,如下图。 (注:在开发和生产环境均可使用,且不会过期。)
create_auth_key
  • 点击 “Continue” 让你确认信息,再点击 “confirm”,就可以下载该 key 了。(注意:记下 key id,而且只可以下载一次,请妥善保存。)
download_auth_key
  • 获取你之前创建过的应用的 Bundle ID
get_bundle_id
  • 在开发者账户的 “Membership” 页面获取 Team ID
get_team_id
  • 在极光控制台上,进入你应用的应用设置中 iOS 的鉴权方式选择 “Token Authentication”,上传 auth key 文件,并填写你的 KEY ID,TeamID,和指定应用的 BundleID。极光会在后台为你的应用进行鉴权。
add_to_portal

下面为标签、别名、本地通知设置,需要的小伙伴可以看下:以下代码版本: ""react-native": "0.61.0";jcore-react-native": "^1.7.5" ;jpush-react-native": "^2.7.5"

import React from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  ScrollView,
  NativeModules,
  DeviceEventEmitter
} from 'react-native';
import JPush from 'jpush-react-native';
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  setBtnStyle: {
    width: 320,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
    borderWidth: 1,
    borderColor: '#3e83d7',
    borderRadius: 8,
    backgroundColor: '#3e83d7',
    padding: 10
  },
  textStyle: {
    textAlign: 'center',
    fontSize: 25,
    color: '#ffffff'
  }
});

class Button extends React.Component {
  render() {
    return <TouchableHighlight
        onPress={this.props.onPress}
        underlayColor='#e4083f'
        activeOpacity={0.5}
    >
      <View
          style={styles.setBtnStyle}>
        <Text
            style={styles.textStyle}>
          {this.props.title}
        </Text>
      </View>
    </TouchableHighlight>
  }
}

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {

    JPush.init();
    //连接状态
    this.connectListener = result => {
      console.log("connectListener:" + JSON.stringify(result))
    };
    JPush.addConnectEventListener(this.connectListener);
    //通知回调
    this.notificationListener = result => {
      console.log("notificationListener:" + JSON.stringify(result))
    };
    JPush.addNotificationListener(this.notificationListener);
    //本地通知回调
    this.localNotificationListener = result => {
      console.log("localNotificationListener:" + JSON.stringify(result))
    };
    JPush.addLocalNotificationListener(this.localNotificationListener);
    //自定义消息回调
    this.customMessageListener = result => {
      console.log("customMessageListener:" + JSON.stringify(result))
    };
    JPush.addCustomMessagegListener(this.customMessageListener);
    //tag alias事件回调
    this.tagAliasListener = result => {
      console.log("别名事件回调:" + JSON.stringify(result))
    };
    JPush.addTagAliasListener(this.tagAliasListener);
    //手机号码事件回调
    this.mobileNumberListener = result => {
      console.log("mobileNumberListener:" + JSON.stringify(result))
    };
    JPush.addMobileNumberListener(this.mobileNumberListener);
  }
  render() {
    return (
        <View style={styles.container}>
          <ScrollView>
            <Button title="setLoggerEnable"
                    onPress={() => JPush.setLoggerEnable(true)
                    }/>

            <Button title="获取id"
                    onPress={() => JPush.getRegistrationID(result =>
                        console.log("registerID:" + JSON.stringify(result))
                    )}/>

            {/* 用标签或者别名都可以接收消息,别名只能有1个,而标签可以有多个*/}
            <Button title="添加标签"
                    onPress={() => JPush.addTags({sequence: 1, tags: ["cui1", "cui2", "cui3"]})}/>
            <Button title="升级标签"
                    onPress={() => JPush.updateTags({sequence: 2, tags: ["cui4", "cui5", "cui6"]})}/>
            <Button title="删除指定标签"
                    onPress={() => JPush.deleteTag({sequence: 3, tags: ["4", "5", "6"]})}/>
            <Button title="删除所有标签"
                    onPress={() => JPush.deleteTags({sequence: 4})}/>
            <Button title="获取指定标签"
                    onPress={() => JPush.queryTag({sequence: 4, tag: "1"})}/>
            <Button title="获取所有标签"
                    onPress={() => JPush.queryTags({sequence: 5})}/>
            <Button title="设置别名"
                    onPress={() => JPush.setAlias({sequence: 6,alias:"cuitao"})}/>
            <Button title="删除别名"
                    onPress={() => JPush.deleteAlias({sequence: 7})}/>
            <Button title="获取别名"
                    onPress={() => JPush.queryAlias({sequence: 8})}/>
            <Button title="设置移动手机号"
                    onPress={() => JPush.setMobileNumber({mobileNumber: "13888888888"})}/>
            <Button title="添加本地事件"
                    onPress={() => JPush.addLocalNotification({
                      messageID: "37", //发送本地通知必须存在:messageID
                      title: "标题啦啦",
                      content: "内容133",
                      extras: {"key123": "value123"}  //附加内容
                    })}/>

            {/*<Button title="setBadge"*/}
            {/*        onPress={() => JPush.setBadge({"badge":1,"appBadge":1})}/>*/}
            {/*<Button title="initCrashHandler"*/}
            {/*        onPress={() => JPush.initCrashHandler()}/>*/}

            <Button title="移除本地指定事件"
                    onPress={() => JPush.removeLocalNotification({messageID: '37'})}/>
          </ScrollView>
        </View>
    );
  }

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容