React-Native如何使用jpush,也就是极光推送 拉勾网插件,给手机发短信

jpush-react-native 插件的集成与使用 Android 篇 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
已注册用户请 &
jpush-react-native 插件的集成与使用 Android 篇
17:50:01 +08:00 · 922 次点击
当前 React Native 虽说版本更新比较快,各种组件也提供的很全面了,但是在某些情况下,混合开发的方式才会快速缩短开发周期,原因无非就是原生平台的“底蕴”无疑更深,拥有众多且类型丰富的第三方支持库。很多情况下,运用这些库可以避免苦逼的重复劳动。接下来我们以 为例来看看在 React Native 中如何使用原生的第三方库。
在开始之前,你必须安装以下软件:npm 命令行工具,react-native 命令行工具,Android Studio。jpush-react-native 是提供的 React Native 版本插件,可以让我们快速集成推送功能。实际上这个插件就是一个混合应用,使用他们自己的原生 SDK,并且封装了一些接口,让开发者可以在 JS 和原生平台之间互相调用。接下来我们只需要三个步骤就可以完成绝大多数原生库在 React Native 中的应用。
先明确两个概念,在 Android Studio 中一个项目往往会包含很多模块( Module ),项目中的 build.gradle 配置一般对所有 module 生效。而 Module 中的 build.gradle 则配置了该 Module 所需的依赖或者任务等等。
第一步——安装
在命令行中进入 React Native 项目,然后使用如下两个命令即可完成 jpush-react-native 插件的安装:
npm install jpush-react-native --save
rnpm link jpush-react-native
jpush-react-native 发布到 npm 了,所以使用命令行可以轻松安装。
然而有很多第三方库可能需要原生的安装方式。比如提供 jar 包或者 aar 包的方式在 Android 中很常见,也有可能以 maven 依赖的方式安装。如果是以上方式安装需要做一些调整:
jar 包或者 aar 包的方式:
将依赖包复制到 module 的 libs 文件夹下(如果没有则需要手动创建)
在 build.gradle 中添加:
sourceSets {
jniLibs.srcDirs = ['libs']
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
以 maven 依赖的方式:
在项目的 build.gradle 中增加:
allprojects {
repositories {
mavenCentral()
url "https://oss.sonatype.org/content/repositories/snapshots/"
ii. 在 module 的 build.gradle 中添加:
dependencies {
compile 'xxx-SNAPSHOT'
其中的 xxx 指代 groupId、artifactId 以及版本号(以 : 分隔),一般都会由提供方给出。比如 ActiveAndroid:
compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'
第二步——适配(配置)
这一步因第三方库而异,其实大多都是大同小异,有的库甚至不需要配置直接可以“搭建桥梁”使用。jpush-react-native 还是要配置一下的
首先在命令行中运行脚本:
// 将 AppKey 和 Module Name 替换成自己的
npm run configureJPush [AppKey] [Module Name]
配置 AndroidManifest
&meta-data android:name="JPUSH_CHANNEL" android:value="${APP_CHANNEL}"/&
&meta-data android:name="JPUSH_APPKEY" android:value="${JPUSH_APPKEY}"/&
将以上代码复制到你 Module 的 AndroidManifest 下即可。
配置 build.gradle
打开与 AndroidManifest 同级的 build.gradle 文件,做以下改动:
defaultConfig {
// 换成自己的包名
applicationId "com.xxx"
manifestPlaceholders = [
JPUSH_APPKEY: "xxx",
//在此替换你的 AppKey,极光官网注册应用获得
APP_CHANNEL: "developer-default"
//应用渠道号
到此配置完成。
第三步 搭建桥梁
这一步是最后也是最核心的一步。“搭建桥梁”主要是在 Native 侧提供一些 @ReactMethod 标签的方法,或者在 Native 中处理后回调到 JS,说白了就是要使得 JS 和 Native 可以相互调用。这也是混合开发的优势所在,原生平台提供的库,我们只需要搭建一下桥梁,就可以拿来使用。只要稍微写一点原生的代码,可以省去我们绝大部分工作。许多刚接触 React Native 的人不知道如何在 Native 中打开 JS 的界面(众所周知,JS 的界面由一个个 Component 组成,有自己的路由系统)后面我会写一个简单例子,用 Native 的方式声明注册界面(在 Android 中即为 Activity ),然后用 JS 渲染界面,这个问题就迎刃而解了。接下来还是先看看 jpush-react-native 的例子。
首先在你的 Module 下创建一个 ManiActivity 以及 MainApplication 类。RN 0.29 后,需要在 MainApplication 中添加原生模块。
MainActivity.java
public class MainActivity extends ReactActivity implements DefaultHardwareBackBtnHandler {
protected String getMainComponentName() {
// 这里返回的名字要与 JS 侧注册的 Component 名字一致
return "PushDemoApp";
protected void onPause() {
super.onPause();
JPushInterface.onPause(this);
protected void onResume() {
super.onResume();
JPushInterface.onResume(this);
接下来需要在 MainApplication 中增加原生模块
MainApplication.java
public class MainApplication extends Application implements ReactApplication {
private boolean SHUTDOWN_TOAST =
private boolean SHUTDOWN_LOG =
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
protected List&ReactPackage& getPackages() {
return Arrays.&ReactPackage&asList(
new MainReactPackage(),
new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
public ReactNativeHost getReactNativeHost() {
return mReactNativeH
这样就完成了。在 Android Studio 中 sync 一下,可以看到 jpush-react-native 作为 Library Module 导进来了。打开 JPushModule 类,看到其中的 onReceive 方法,通知的处理都在这一块。在极光推送后台发送通知(也可以使用 服务端 sdk )后,客户端 sdk 收到通知后会回调到 onReceive 方法,在 onReceive 中可以做一些定制化的操作。比如收到通知后,点击通知打开特定的界面:
public static class JPushReceiver extends BroadcastReceiver {
public JPushReceiver() {
HeadlessJsTaskService.acquireWakeLockNow(mRAC);
public void onReceive(Context context, Intent data) {
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(data.getAction())) {
Logger.d(TAG, "用户点击打开了通知");
Intent intent = new Intent();
intent.setClassName(context.getPackageName(), context.getPackageName() + ".MainActivity");
intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 如果需要跳转到指定的界面,那么需要同时启动 MainActivity 及指定界面(SecondActivity):
// If you need to open appointed Activity, you need to start MainActivity and
// appointed Activity at the same time.
Intent detailIntent = new Intent();
detailIntent.setClassName(context.getPackageName(), context.getPackageName() + ".SecondActivity");
detailIntent.putExtras(bundle);
Intent[] intents = {intent, detailIntent};
// 同时启动 MainActivity 以及 SecondActivity
context.startActivities(intents);
// 或者回调 JS 的某个方法
@ReactMethod
public void finishActivity() {
Activity activity = getCurrentActivity();
if (activity != null) {
activity.finish();
上面的例子中,我们在收到点击通知的事件时,打开一个特定的界面。这个界面在 Native 中创建(这样做的好处在于还可以实现一些特定的需求,比如收到通知后,如果存在 SecondActivity,则让位于 SecondActivity 之上的界面全部弹出,如果不存在,则创建等等之类的需求),但是还是用 JS 的代码来渲染界面,这对于熟悉 JS 的同学来说,再好不过。要做到这一点,首先我们创建一个 SecondActivity (与 MainActivity 同级)类:
SecondActivity.java
public class SecondActivity extends ReactActivity {
protected String getMainComponentName() {
// 注意这个名字与 JS 对应的 Component 中
// AppRegistry.registerComponent 方法的第一个参数相同
return "SecondActivity";
然后在 AndroidManifest 注册 SecondActivity:
AndroidManifest
&activity android:name=".SecondActivity" /&
在 React Native 项目下新建一个文件夹 react-native-android,专门用来存放 js 相关的文件。新建 second.js 文件:
'use strict';
import React from 'react';
import ReactNative from 'react-native';
AppRegistry,
TouchableHighlight,
StyleSheet,
NativeModules,
} = ReactN
var JPushModule = NativeModules.JPushM
export default class second extends React.Component {
constructor(props) {
super(props);
onBackPress = () =& {
let navigator = this.props.
if (navigator != undefined) {
this.props.navigator.pop();
console.log("finishing second activity");
JPushModule.finishActivity();
onButtonPress = () =& {
console.log("will jump to setting page");
let navigator = this.props.
if (navigator != undefined) {
this.props.navigator.push({
name: "setActivity"
render() {
&TouchableHighlight
style={styles.backBtn}
underlayColor = '#e4083f'
activeOpacity = {0.5}
onPress = {this.onBackPress}&
&/TouchableHighlight&
style={styles.welcome}&
&TouchableHighlight underlayColor = '#e4083f'
activeOpacity = {0.5}
style = {styles.btnStyle}
onPress = {this.onButtonPress}&
&Text style={styles.btnTextStyle}&
Jump To Setting page!
&/TouchableHighlight&
var styles = StyleSheet.create({
backBtn: {
padding: 10,
marginTop: 10,
marginLeft: 10,
borderWidth: 1,
borderColor: '#3e83d7',
backgroundColor: '#3e83d7',
borderRadius: 8,
alignSelf: 'flex-start'
welcome: {
textAlign: 'center',
margin: 10,
btnStyle: {
marginTop: 10,
borderWidth: 1,
borderColor: '#3e83d7',
borderRadius: 8,
backgroundColor: '#3e83d7',
alignSelf: 'center',
justifyContent: 'center'
btnTextStyle: {
textAlign: 'center',
fontSize: 25,
color: '#ffffff'
AppRegistry.registerComponent('SecondActivity', () =& second);
就这样,大功告成!接下来可以在 index.android.js 中注册路由,使得在 JS 中也可以跳转到这个界面。
以上就是在 React Native 中以混合的方式开发应用的大概过程。用这种方式可以马上使用丰富的原生平台第三方库,只是在 Native 部分需要写些代码,但是花费的代价远远小于自己用 JS 的方式再实现一遍。
作者:KenChoi - 极光( JPush 为极光团队账号,欢迎关注)
知乎专栏:
目前尚无回复
& · & 1004 人在线 & 最高记录 3541 & · &
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.1 · 22ms · UTC 17:31 · PVG 01:31 · LAX 10:31 · JFK 13:31? Do have faith in what you're doing.极光推送官方支持的 React Native 插件
npm install jpush-react-native --savenpm install jcore-react-native --save ## jpush-react-native 1.4.2 版本以后需要同时安装 jcore-react-native
一、自动配置部分(以下命令均在你的 REACT NATIVE PROJECT 目录下运行,自动配置后仍需手动配置一部分)
1.1执行脚本npm run configureJPush &yourAppKey& &yourModuleName&//module name 指的是你 Android 项目中的模块名字(对 iOS 没有影响,不填写的话默认值为 app,会影响到查找 AndroidManifest 问题,//如果没找到 AndroidManifest,则需要手动修改,参考下面的 AndroidManifest 配置相关说明)//举个例子:npm run configureJPush d4eefa51334f5 app1.2Link 项目//执行自动配置脚本后再执行 link 操作react-native link
二、手动操作部分 (3个步骤)
第一步:修改 app 下的 build.gradle 配置:your react native project/android/app/build.gradle&
defaultConfig {
applicationId "yourApplicationId"
manifestPlaceholders = [
JPUSH_APPKEY: "yourAppKey", //在此替换你的APPKey
APP_CHANNEL: "developer-default"
//应用渠道号
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile project(':jpush-react-native')
// 添加 jpush 依赖
compile project(':jcore-react-native')
// 添加 jcore 依赖
compile "com.facebook.react:react-native:+"
// From node_modules
将此处的 yourApplicationId 替换为你的项目的包名;yourAppKey 替换成你在官网上申请的应用的 AppKey。
检查是否导入以下配置项:检查一下 dependencies 中有没有添加 jpush-react-native 及 jcore-react-native 这两个依赖。
your react native project/android/app/build.gradle
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile project(':jpush-react-native')
// 添加 jpush 依赖
compile project(':jcore-react-native')
// 添加 jcore 依赖
compile "com.facebook.react:react-native:+"
// From node_modules
检查 android 项目下的 settings.gradle 配置有没有包含以下内容:
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')
检查一下 app 下的 AndroidManifest 配置,有没有增加 &meta-data& 部分。
your react native project/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&
2.3:加入 JPushPackage (找到 app 下的 MainApplication.java):
app/src.../MainApplication.java
private boolean SHUTDOWN_TOAST =
private boolean SHUTDOWN_LOG =
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
protected List&ReactPackage& getPackages() {
return Arrays.&ReactPackage&asList(
new MainReactPackage(),
//加入 JPushPackage
new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
上面 JPushPackage 的两个参数是 bool 类型的,第一个参数设置为 true 表示关闭 toast 提示,第二个设置为 true 表示关闭日志打印,建议在 debug 版本中打开。然后在 MainActivity 中加入一些初始化代码即可:
app/src.../MainActivity.java
public class MainActivity extends ReactActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
JPushInterface.init(this);
protected void onPause() {
super.onPause();
JPushInterface.onPause(this);
protected void onResume() {
super.onResume();
JPushInterface.onResume(this);
添加了此事件后,在收到推送时将会触发此事件。
需要注意的是,v1.6.6 版本以后,增加了&notifyJSDidLoad&方法,在监听所有相关事件之前要调用此方法,否则不会收到点击通知事件。
example/react-native-android/push_activity.js
import JPushModule from 'jpush-react-native';
export default class PushActivity extends React.Component {
componentDidMount() {
// 在收到点击事件之前调用此接口
JPushModule.notifyJSDidLoad((resultCode) =& {
if (resultCode === 0) {
JPushModule.addReceiveNotificationListener((map) =& {
console.log("alertContent: " + map.alertContent);
console.log("extras: " + map.extras);
// var extra = JSON.parse(map.extras);
// console.log(extra.key + ": " + extra.value);
在用户点击通知后,将会触发此事件。
componentDidMount() {
JPushModule.addReceiveOpenNotificationListener((map) =& {
console.log("Opening notification!");
console.log("map.extra: " + map.key);
得到 REGISTRATIONID
用户注册成功后(一般在用户启动应用后),如果订阅了这个事件,将会收到这个 registrationId。
componentDidMount() {
JPushModule.addGetRegistrationIdListener((registrationId) =& {
console.log("Device register succeed, registrationId " + registrationId);
清除所有通知
建议在用户退出前台后调用。
componentWillUnmount() {
console.log("Will clear all notifications");
JPushModule.clearAllNotifications();
example/react-native-android/set_activity.js
setTag() {
if (this.state.tag !== undefined) {
* 请注意这个接口要传一个数组过去,这里只是个简单的示范
JPushModule.setTags(["VIP", "NOTVIP"], () =& {
console.log("Set tag succeed");
}, () =& {
console.log("Set tag failed");
setAlias() {
if (this.state.alias !== undefined) {
JPushModule.setAlias(this.state.alias, () =& {
console.log("Set alias succeed");
}, () =& {
console.log("Set alias failed");
阅读(...) 评论()React Native 集成jpush-react-native的示例代码
转载 &更新时间:日 16:38:31 & 作者:Arno-su
这篇文章主要介绍了React Native 集成jpush-react-native的示例代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
jpush-React-native是极光推送官方维护的一个插件,github地址:
一.手动配置
1.集成插件到项目中
npm install jpush-react-native --save
rnpm link jpush-react-native
使用 android Studio import 你的 react Native 应用(选择你的 React Native 应用所在目录下的 android 文件夹即可)
修改 android 项目下的 settings.gradle 配置: settings.gradle
include ':app', ':jpush-react-native'
project(':jpush-react-native').projectDir = new File(rootProject.projectDir,'../node_modules/jpush-react-native/android')
修改 app 下的 AndroidManifest 配置,将 jpush 相关的配置复制到这个文件中,参考 demo 的 AndroidManifest:(增加了 部分)
your react native project/android/app/AndroidManifest.xml
&application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"&
android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="@string/app_name"&
&intent-filter&
&action android:name="android.intent.action.MAIN" /&
&category android:name="android.intent.category.LAUNCHER" /&
&/intent-filter&
&/activity&
&activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /&
&!-- 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&
修改 app 下的 build.gradle 配置: your react native project/android/app/build.gradle
修改 app 下的 build.gradle 配置:
your react native project/android/app/build.gradle
defaultConfig {
applicationId "yourApplicationId"
manifestPlaceholders = [
JPUSH_APPKEY: "yourAppKey", //在此替换你的APPKey
APP_CHANNEL: "developer-default" //应用渠道号
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile project(':jpush-react-native')
compile "com.facebook.react:react-native:+" // From node_modules
将此处的 yourApplicationId 替换为你的项目的包名;yourAppKey 替换成你在官网上申请的应用的 AppKey。
现在重新 sync 一下项目,应该能看到 jpush-react-native 作为一个 android Library 项目导进来了
重点来了,我在这个地方卡了一天,以上代码配置完成后,但是不管怎么样就是接收不到推送。
解决方案:找到项目/node_modules/jpush-react-native/android/src/main/AndroidManifest.xml,里面的 ${applicationId} 全部换成 你自己的项目包名
到此为止android的配置结束。
二.iOS配置
打开 ios 工程,在 rnpm link 之后,RCTJPushModule.xcodeproj 工程会自动添加到 Libraries 目录里面
在 iOS 工程 target 的 Build Phases-&Link Binary with Libraries 中加入如下库:
CFNetwork.framework
CoreFoundation.framework
CoreTelephony.framework
SystemConfiguration.framework
CoreGraphics.framework
Foundation.framework
UIKit.framework
Security.framework
libz.tbd (Xcode7以下版本是libz.dylib)
UserNotifications.framework (Xcode8及以上)
libresolv.tbd (JPush 2.2.0及以上版本需要, Xcode7以下版本是libresolv.dylib)
根据域名配置info.plist:
把需要的支持的域添加給NSExceptionDomains。其中jpush.cn作为Key,类型为字典类型。
每个域下面需要设置2个属性:NSIncludesSubdomains、NSExceptionAllowsInsecureHTTPLoads。
两个属性均为Boolean类型,值分别为YES、YES。
在 AppDelegate.h 文件中 填写如下代码,这里的的 appkey、channel、和 isProduction 填写自己的
static NSString *appKey = @”“; //填写appkey
static NSString *channel = @”“; //填写channel 一般为nil
static BOOL isProduction = //填写isProdurion 平时测试时为false ,生产时填写true
在AppDelegate.m 里面添加如下代码
1.引入依赖文件
#import &RCTJPushModule.h&
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import &UserNotifications/UserNotifications.h&
@interface AppDelegate()
2.在didFinishLaunchingWithOptions方法里添加
if ([[UIDevice currentDevice].systemVersion floatValue] &= 10.0) {
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionS
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}else if ([[UIDevice currentDevice].systemVersion floatValue] &= 8.0) {
//可以添加自定义categories
[JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
UNAuthorizationOptionSound |
UNAuthorizationOptionAlert)
categories:nil];
//categories 必须为nil
[JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
UNAuthorizationOptionSound |
UNAuthorizationOptionAlert)
categories:nil];
[JPUSHService setupWithOption:launchOptions appKey:appKey
channel:nil apsForProduction:isProduction];
3.加入jupush的代码
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[JPUSHService registerDeviceToken:deviceToken];
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 取得 APNs 标准信息内容
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
这个方法是清除icon角标
- (void)applicationWillEnterForeground:(UIApplication *)application {
[application setApplicationIconBadgeNumber:0];
// [application cancelAllLocalNotifications];
//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^) (UIBackgroundFetchResult))completionHandler {
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
// Required
NSDictionary * userInfo = notification.request.content.userI
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
// Required
NSDictionary * userInfo = response.notification.request.content.userI
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
completionHandler(); // 系统要求执行这个方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//Optional
NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
如果想要获取到自定义消息的话,需要在didFinishLaunchingWithOptions方法中添加一下代码:
//获取自定义消息
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(networkDidReceiveMess
还需要添加新的方法,以监听自定义消息的接受:
//#pragma mark 获取自定义消息内容
- (void)networkDidReceiveMessage:(NSNotification *)notification {
NSDictionary * userInfo = [notification userInfo];
NSString *content = [userInfo valueForKey:@"content"];
NSDictionary *extras = [userInfo valueForKey:@"extras"];
NSString *customizeField1 = [extras valueForKey:@"123456"]; //自定义参数,key是自己定义的
NSLog(@"自定义message:%@",userInfo);
NSLog(@"推%@",content);
NSLog(@"推%@",extras);
NSLog(@"推%@",customizeField1);
&配置代码,在Xcode中打开push的权限
往下滑动,配置:
到此为止,ios的配置结束。
然后在RN中配置调用jpush的代码:
import JPushModule from 'jpush-react-native';
constructor(props) {
super(props);
if(Platform.OS === 'android') JPushModule.initPush();
componentDidMount(){
if (Platform.OS === 'android') {
BackAndroid.addEventListener('hardwareBackPress', this._onBackAndroid);
//-----------jpush android start
// JPushModule.getInfo((map) =& {
console.log(map);
// JPushModule.addReceiveCustomMsgListener((message) =& {
JPushModule.addReceiveNotificationListener((message) =& {
console.log("receive notification: ");
console.log(message);
JPushModule.addReceiveOpenNotificationListener((map) =& {
console.log("Opening notification!");
console.log(map);
//-----------jpush android end
//-----------jpush ios start
if (Platform.OS === 'ios') {
this.subscription = NativeAppEventEmitter.addListener(
'ReceiveNotification',
(notification) =& {
console.log('-------------------收到推送----------------');
console.log(notification)
//-----------jpush ios end
componentWillUnmount(){
if (Platform.OS === 'android') {
BackAndroid.removeEventListener('hardwareBackPress', this._onBackAndroid);
JPushModule.removeReceiveCustomMsgListener();
JPushModule.removeReceiveNotificationListener();
this.subscription && this.subscription.remove();
&然后就可以去官方控制台,手动推送通知了
想要icon右上角角标显示的数字增加,如图:
加号为英文状态下的
大家集成的时候多看官方文档,将两端的官方demo下载下来,能发现很多有用的信息。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 极光推送锁屏显示消息 的文章

 

随机推荐