react native 极光推送

官网: https://www.jiguang.cn/

github: https://github.com/jpush/jpush-react-native

安装: 

yarn add jpush-react-native jcore-react-native

或者

npm install jpush-react-native --save

npm install jcore-react-native --save

自动配置:

react-native link    或者     

react-native link jpush-react-native

react-native link jcore-react-native

 

输入在极光官网所创建的应用名称的 appKey

手动配置(Android):

1、settings.gradle

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

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

2、build.gradle(app)

defaultConfig {
    applicationId "yourApplicationId" //此处改成你在极光官网上申请应用时填写的包名
    ...
    manifestPlaceholders = [
        JPUSH_APPKEY: "yourAppKey", //在此替换你的 APPKey
        APP_CHANNEL : "default" //应用渠道号, 默认即可
    ]
    ...
}

dependencies {
    ...
    compile project(':jpush-react-native')  // 添加 jpush 依赖
    compile project(':jcore-react-native')  // 添加 jcore 依赖
    ...
}

3、AndroidManifest.xml


    

 4、MainApplication.java 文件,然后加入 JPushPackage,可参考 demo

    // 设置为 true 将不弹出 toast
    private boolean SHUTDOWN_TOAST = false;
    // 设置为 true 将不打印 log
    private boolean SHUTDOWN_LOG = false;

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

        @Override
        protected boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List getPackages() {
            return Arrays.asList(
                    new MainReactPackage(),
                    new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
            );
        }
    };

 5、MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    JPushInterface.init(this);
}

@Override
protected void onPause() {
    super.onPause();
    JPushInterface.onPause(this);
}

@Override
protected void onResume() {
    super.onResume();
    JPushInterface.onResume(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

 

ios:link 成功之后:

Libraries文件夹下多出

react native 极光推送_第1张图片

在 Build Phases 里的 Link Binary With Libararies 下会多出以下依赖

react native 极光推送_第2张图片

在 AppDelegate.h 文件中 导入头文件

static NSString *appKey = @"appkey";     //填写appkey
static NSString *channel = @"nil";    //填写channel   一般为nil
static BOOL isProduction = false;  //填写isProdurion  平时测试时为false ,生产时填写true

在AppDelegate.m中的didFinishLaunchingWithOptions下添加

  ------  添加的内容开始  ------
  JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
  entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
  [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
  ------  添加的内容结束  ------
  [JPUSHService setupWithOption:launchOptions appKey:@"8d8c4ffead4718717efb756d"
                        channel:nil apsForProduction:nil];

在Capabilities 下打开 Push Notifications

react native 极光推送_第3张图片

证书的配置参考:https://docs.jiguang.cn/jpush/client/iOS/ios_cer_guide/

 

使用:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

import JPushModule from 'jpush-react-native';

export default class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      permission: '',
      registrationId: '',
      city: '',
      report: '暂未收到通知',
      isRead: '暂未收到通知',
    }
  }
  componentDidMount() {
    // 获取位置
    navigator.geolocation.getCurrentPosition(
      (position) => {
        let lon = position.coords.longitude;
        let lat = position.coords.latitude;
        // ak 与 mcode 请在百度地图进行申请
        let ak = 'LpR4OuOxoXdxYHHDINwnRV667m672jvY';
        let mcode = '17:5E:5B:02:3D:AA:22:0E:4B:74:2F:0D:FA:8C:19:23:1B:4A:A6:D4;com.push';
        let url = `https://api.map.baidu.com/geocoder/v2/?output=json&ak=${ak}&mcode=${mcode}&location=${lat},${lon}`;
        fetch(url).then((response) => response.json())
          .then((responseData) => {
              // console.log(responseData);
              let arr = [];
              let city = responseData.result.addressComponent.city;
              this.setState({city: city})
              arr.push(city)
              // 为当前设备添加标签(标签为当前城市名)
              JPushModule.addTags(arr, success => {
                // 添加成功
              })
          })
          .catch((error) => {
            console.log(error);
          })
      },
      (error) => alert(error.message),
    );

    // 
    JPushModule.notifyJSDidLoad((resultCode) => {
        // console.log(resultCode);
        if (resultCode === 0) {}
    });
    // 获取registrationId(registrationId由JPush SDK根据deviceToken生成)
    JPushModule.getRegistrationID(registrationId => {
      this.setState({registrationId: registrationId})
    })
    // 获取应用是否开启推送权限
    JPushModule.hasPermission( res => {
      if(!res){
        return this.setState({permission: res})
      }
      this.setState({permission: res})
    })
    // 接收自定义消息
    JPushModule.addReceiveCustomMsgListener((message) => {
        // this.setState({pushMsg: message});
        console.log("自定义消息 => ");
        console.log(message);
    });
    // 接收推送通知
    JPushModule.addReceiveNotificationListener((message) => {
        this.setState({
          report: message.alertContent,
          isRead: '您有通知未阅读'
        })
    });
    // 打开通知
    JPushModule.addReceiveOpenNotificationListener((map) => {
        this.setState({isRead: '已阅读'})
        // 可执行跳转操作,也可跳转原生页面
        // this.props.navigation.goBack();
    });
    // 获取设备信息
    JPushModule.getInfo((map) => {
      // console.log(map);
    });
  }
 
  componentWillUnmount() {
      JPushModule.removeReceiveCustomMsgListener();
      JPushModule.removeReceiveNotificationListener();
  }

  render() {
    let permission = this.state.permission;
    permission = permission ? '已开启' : '请前往应用设置内开启通知权限'
    return (
      
        通知权限: {permission}
        registrationId: {this.state.registrationId}
        最新通知: {this.state.report}
        是否阅读: {this.state.isRead}
        {/* 设置设备别名 */}
        所在城市: {this.state.city}
        关闭推送
        开启推送
      
    );
  }
  // 设置设备的应用程序别名,你可以用别名推送通知,每个设备只能有一个别名
  _setting = () => {
    JPushModule.setAlias('happy', success => {
      console.log(success)
    })
  }
  // 关闭推送
  _stop = () => {
    JPushModule.stopPush();
    alert('关闭成功')
  }
  // 开启推送
  _restart = () => {
    JPushModule.resumePush();
    alert('开启成功')
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 18,
    margin: 10,
  },
});

android效果图,虚拟机和真机(包括正式版)都已测试:

未布通知:

react native 极光推送_第4张图片


收到通知:

react native 极光推送_第5张图片


阅读通知:

react native 极光推送_第6张图片

 

react native 极光推送_第7张图片

自定义消息与这个一样,iOS目前没有开发者账号,有了再更新!!!

 

 

你可能感兴趣的:(react,native)