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

<application
    ...
    <meta-data
        android:name="JPUSH_APPKEY"
        android:value="${JPUSH_APPKEY}" />
    <meta-data
        android:name="JPUSH_CHANNEL"
        android:value="${APP_CHANNEL}" />
</application>

 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<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>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文件夹下多出

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

在 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

证书的配置参考: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 (
      <View style={styles.container}>
        <Text style={styles.welcome}>通知权限: {permission}</Text>
        <Text style={styles.welcome}>registrationId: {this.state.registrationId}</Text>
        <Text style={styles.welcome}>最新通知: {this.state.report}</Text>
        <Text style={styles.welcome}>是否阅读: {this.state.isRead}</Text>
        {/* <Text style={styles.welcome} onPress={this._setting}>设置设备别名</Text> */}
        <Text style={styles.welcome}>所在城市: {this.state.city}</Text>
        <Text style={styles.welcome} onPress={this._stop}>关闭推送</Text>
        <Text style={styles.welcome} onPress={this._restart}>开启推送</Text>
      </View>
    );
  }
  // 设置设备的应用程序别名,你可以用别名推送通知,每个设备只能有一个别名
  _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效果图,虚拟机和真机(包括正式版)都已测试:

未布通知:


收到通知:


阅读通知:

 

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值