在接到需求后对如何实现进行了预研,发现有极光官网维护的 jpush-react-native 和 React Native 中文网维护的 react-native-jpush 供我们使用,我选择的是 jpush-react-native。
一,相关版本信息
{
"name": "app",
"version": "0.0.1",
"private": true,
"scripts": {
"configureJPush": "node node_modules/jpush-react-native/JPushConfiguration.js",
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.3.1",
"react-native": "0.54.4",
"react-navigation": "^1.0.0-beta.19",
"jpush-react-native": "^2.1.7",
……
},
"devDependencies": {
……
},
"jest": {
……
}
}
二、添加极光组件
运行命令:yarn add jpush-react-native 或 npm install jpush-react-native --save
并链接原生库:react-native link jpush-react-native
三、iOS端手动配置
3.1 打开 iOS 工程,会发现RCTJPushModule.xcodeproj 工程会自动添加到 Libraries 目录里面
在 iOS 工程 target 的 Build Phases->Link Binary with Libraries 中加入如下库
libz.tbd
CoreTelephony.framework
Security.framework
CFNetwork.framework
CoreFoundation.framework
SystemConfiguration.framework
Foundation.framework
UIKit.framework
UserNotifications.framework
libresolv.tbd
3.2 在 iOS 工程中设置 TARGETS-> BUILD Phases -> LinkBinary with Libraries 找到 UserNotifications.framework 把 status 设为 optional
3.3 在 iOS 工程中如果找不到头文件可能要在 TARGETS-> BUILD SETTINGS -> Search Paths -> Header Search Paths 添加如下路径 $(SRCROOT)/../node_modules/jpush-react-native/ios/RCTJPushModule
3.4 在 xcode8 之后需要点开推送选项: TARGETS -> Capabilities -> Push Notification 设为 on 状态
3.5 在 AppDelegate.h 文件中 填写如下代码,这里的的 appkey、channel、和 isProduction 填写自己的
static NSString *appKey = @""; //填写appkey
static NSString *channel = @""; //填写channel 一般为nil
static BOOL isProduction = false; //填写isProdurion 平时测试时为false ,生产时填写true
3.6 在AppDelegate.m 的didFinishLaunchingWithOptions 方法里面添加如下代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//可以添加自定义categories
[JPUSHService registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
} else {
//iOS 8以前 categories 必须为nil
[JPUSHService registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert) categories:nil];
}
[JPUSHService setupWithOption:launchOptions appKey:appKey channel:channel apsForProduction:isProduction];
}
在AppDelegate.m 的didRegisterForRemoteNotificationsWithDeviceToken 方法中添加 [JPUSHService registerDeviceToken:deviceToken];
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[JPUSHService registerDeviceToken:deviceToken];
}
为了在收到推送点击进入应用能够获取该条推送内容需要在 AppDelegate.m 的didReceiveRemoteNotification 方法里面添加
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
注意:这里需要在两个方法里面添加方法,一个是iOS7以前的、一个是iOS7即以后的,如果AppDelegate.m 没有这个两个方法则直接复制这两个方法;
在 iOS10 的设备则可以使用JPush 提供的两个方法;如下所示
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 取得 APNs 标准信息内容
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^) (UIBackgroundFetchResult))completionHandler {
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
// Required
NSDictionary * userInfo = notification.request.content.userInfo;
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
NSDictionary * userInfo = response.notification.request.content.userInfo;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
completionHandler(); // 系统要求执行这个方法
}
3.7 贴两张图
四、Android端手动配置
4.1 使用 Android Studio 打开 React Native 项目下的 Android 应用,修改 settings.gradle 配置。
include ':app', ':jpush-react-native'
project(':jpush-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jpush-react-native/android')
4.2 修改app 下的 AndroidManifest 配置,将 jpush 相关的配置添加到这个文件中。
<application
android:name="com.pateo.ma.windlink.MainApplication"
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/logo"
android:theme="@style/AppTheme">
<activity
android:name="com.pateo.ma.windlink.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:windowSoftInputMode="adjustPan|stateHidden">
……
</application>
4.3 修改 app 下的 build.gradle 配置
your react native project/android/app/build.gradle
android {
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。到此为止,配置完成
4.4 现在重新 同步 一下项目,应该能看到 jpush-react-native 作为一个 android Library 项目导进来了
4.5 打开 app 下的 MainActivity,路径:android/app/src/main/java/……/MainActivity.java,在 ReactInstanceManager 的 build 方法中加入 JPushPackage:
// 导入命名空间
import cn.jpush.android.api.JPushInterface;
// 添加方法
@Override
protected void onResume() {
super.onResume();
JPushInterface.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
JPushInterface.onPause(this);
}
4.6 打开 app 下的 MainApplication,路径:android/app/src/main/java/……/MainApplication.java,加入 JPushPackage:
private boolean SHUTDOWN_TOAST = false;
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(
MainReactPackage(),
new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
);
}
};
五、在RN上进行的操作
5.1 普通推送
componentDidMount() {
// ---------------------------------android start---------------------------------
JPushModule.addReceiveCustomMsgListener((message) => {
// 这是默认的通知消息
// this.setState({pushMsg:message});
});
JPushModule.addReceiveNotificationListener((map) => {
// 自定义推送的消息
// console.log("alertContent: " + map.alertContent);
// extra是可选配置上的附件字段
// console.log("extras: " + map.extras);
var message = JSON.parse(map.extras);
this.storeDB(message); // 我这里是把内容存在了数据库里面,你可以把这里的message放到state里面显示出来
// 这里面解析json数据,并存在数据库中,同时显示在通知栏上
})
// 点击通知进入应用的主页,相当于跳转到制定的页面
JPushModule.addReceiveOpenNotificationListener((map) => {
// console.log("Opening notification!");
this.props.navigator.replace({name: "HomePage",component:HomePage});
})
// ---------------------------------android end---------------------------------
// ---------------------------------ios start---------------------------------
NativeAppEventEmitter.addListener(
'ReceiveNotification',
(message) => {
// 下面就是发送过来的内容,可以用stringfy打印发来的消息
console.log("content: " + JSON.stringify(message));
// 下面的json就是我在极光推送上的附件字段内容就是上面的log打印出来的东西
// {
// "_j_msgid": 4572771355,
// "content": "日志第一天",
// "time": "2016-11-18/13:11:09",
// "aps": {
// "sound": "default",
// "badge": 1,
// "alert": "测试ios1"
// },
// "name": "刘成",
// "age": "28",
// "性别": "男",
// "qq":"674668211",
// "手机号":"674668211",
// }
// console.log("_j_msgid:" + message._j_msgid); // 这个是极光的消息id
// console.log("content:" + message.content); // 这是标题
// console.log("aps:" + message.aps.sound); // 这是声音
// console.log("aps:" + message.aps.badge); // 这是上标
// console.log("aps:" + message.aps.alert); // 这是发送通知的主内容 this.storeDB(message);
// }
// );
// ---------------------------------ios end---------------------------------
}
// 最后在组件卸载的时间取消监听
componentWillUnmount() {
JPushModule.removeReceiveCustomMsgListener();
JPushModule.removeReceiveNotificationListener();
BackAndroid.removeEventListener('hardwareBackPress');
NativeAppEventEmitter.removeAllListeners();
DeviceEventEmitter.removeAllListeners();
}
(1)android的推送内容都在message.content里面,附加的数据在message.extras,message就是发送过来的消息内容:addReceiveNotificationListener;
如果你没有附加的消息,只是显示消息内容,用这个方法就行了:addReceiveCustomMsgListener;
如果你要点击通知打开某个应用,用:addReceiveOpenNotificationListener
(2)ios的要用到注册监听事件:NativeAppEventEmitter.addListener,消息内容都在message里面,可以把这里的message
放到state里面显示出来。
5.2 别名推送
setAlias有三个参数,第一个是你要推送的别名,要注册到极光的,第二和第三个分别是设置成功的回调、设置失败的回调。
import JPushModule from 'jpush-react-native';
'您的别名' !== '' ? (JPushModule.setAlias('您的别名',this.success,this.fail)):null
success=()=>{
NativeAppEventEmitter.addListener( 'ReceiveNotification', (message) =>{JPushModule.setBadge(0,function(){
// console.log(message)
})} );
// ---------------------------------android start---------------------------------
JPushModule.addReceiveCustomMsgListener((message) => {
// 这是默认的通知消息
// console.log(message)
});
JPushModule.addReceiveNotificationListener((map) => {
// var message = JSON.parse(map.extras);
});
// 点击通知进入应用的主页
JPushModule.addReceiveOpenNotificationListener((map) => {
// ……
})
// ---------------------------------android end---------------------------------
}
fail=()=>{
}