React Native之通知栏消息提示(android)
一,需求分析与概述
1.1,推送作为手机应用的基本功能,是手机应用的重要部分,如果自己实现一套推送系统费时费力,所以大部分的应用都会选择使用第三方的推送服务,如极光推送。
1.2,jpush-react-native是极光推送官方开发的 React Native 版本插件,可以快速集成推送功能。现在最新版本的 JPush SDK 分离了 JPush 及 JCore,让开发者可以分开集成 JMessage 及 JPush(以前 JMessage 包含了 JPush)。
API:
#初始化JPush 必须先初始化才能执行其他操作(only android)
initPush getInfo #执行该方法后,无法接收到通知
stopPush #stopPush后,执行该方法,可接收通知(only android)
resumePush #参数是func,func的参数是registrationId
getRegistrationID #设置标签
setTags #添加标签
addTags #删除标签
deleteTags #检查标签的状态
checkTagBindState #清除所有标签
cleanTags #设置别名
setAlias #删除别名
deleteAlias #获取别名
getAlias #通知栏样式:Basic
setStyleBasic #通知栏样式:Custom
setStyleCustom
1.3,推送通知可以及时地提醒用户.
二,极光推送注册与集成
2.1,注册
首先,登录极光官网系统,如果还没有账号可以注册一个,登录成功我们就可以创建和管理我们的应用了。
2.2,集成(android)
第一步:安装
打开终端,进入项目根目录文件夹下,执行以下命令:
npm install jpush-react-native --save
jpush-react-native 1.4. 版本以后需要同时安装 jcore-react-native
npm install jcore-react-native --save
第二步:配置
自动关联配置
# 针对性的link,避免之前手动配置的其它插件重复配置造成报错
react-native link jpush-react-native
react-native link jcore-react-native
执行完 link 项目后可能会出现报错,这没关系,需要手动配置一下 build.gradle 文件。如自动配置没有成功或没有完善,可根据手动配置检查
手动配置
(1),检查 android 项目下的 settings.gradle 配置有没有包含以下内容(project/android/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),project/android/app/build.gradle:
android {
...
defaultConfig {
applicationId "yourApplicationId" // 此处改成你在极光官网上申请应用时填写的包名
...
manifestPlaceholders = [
JPUSH_APPKEY: "yourAppKey", //在此替换你极光官网上申请的 APPKey
APP_CHANNEL: "developer-default" //应用渠道号, 默认即可
]
}
}
...
dependencies {
compile project(':jpush-react-native') // 添加 jpush 依赖
compile project(':jcore-react-native') // 添加 jcore 依赖
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.facebook.react:react-native:+" // From node_modules
}
(3),检查一下 app 下的 AndroidManifest 配置,有没有增加 <meta-data> 部分。 project/android/app/src/main/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>
(4),打开 project/android/app/src/main/java/com/项目名/下的 MainApplication.java 文件,然后加入 JPushPackage
... import com.rt2zz.reactnativecontacts.ReactNativeContacts;
import cn.jpush.reactnativejpush.JPushPackage; ... public class MainApplication extends Application implements ReactApplication {
// 设置为 true 将不会弹出 toast
private boolean SHUTDOWN_TOAST = false;
// 设置为 true 将不会打印 log
private boolean SHUTDOWN_LOG = false;
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
} @Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
);
} ... }
(5),打开 project/android/app/src/main/java/com/项目名/下的MainActivity.java 文件,然后加入 如下代码:
... import android.os.Bundle;
import com.facebook.react.ReactActivity;
import cn.jpush.android.api.JPushInterface; public class MainActivity extends ReactActivity { ... @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();
}
}
(6),打开 project/android/app/src/main/下的AndroidManifest.xml 文件,然后添加访问通知的权限:
<!--添加通知权限,${ApplicationID}替换成你的applicationID!-->
<premission
android:name="${ApplicationID}.permission.JPUSH_MESSAGE"
android:protectionLevel="signature"/>
这样就基本完成了所有的配置。接下来就可以在 JS 中调用插件提供的 API 了。
三,使用与实现
3.1,使用
(1),在js中 1 import React, { PureComponent } from 'react';
import {
Linking,
Alert
} from 'react-native';
import JPushModule from 'jpush-react-native' ... componentDidMount() {
/****************************通知 start **************************************************/
if (Platform.OS === 'android') {
JPushModule.initPush()
// 新版本必需写回调函数
JPushModule.notifyJSDidLoad(resultCode => {
if (resultCode === 0) {
}
})
} else {
JPushModule.setupPush()
}
// 接收自定义消息
this.receiveCustomMsgListener = map => {
this.setState({
pushMsg: map.content
})
console.log('extras: ' + map.extras)
} // 接收自定义消息JPushModule.addReceiveCustomMsgListener(this.receiveCustomMsgListener)
this.receiveNotificationListener = map => {
console.log('alertContent: ' + map.alertContent)
console.log('extras: ' + map.extras)
}
// 接收推送通知
JPushModule.addReceiveNotificationListener(this.receiveNotificationListener)
// 打开通知
this.openNotificationListener = map => {
// console.log('Opening notification!')
// console.log('map.extra: ' + map.extras)
let webUrl= JSON.parse(map.extras).webUrl
let url = webUrl.replace(new RegExp("\/", 'g'), "/")
Linking.canOpenURL(url).then(supported => {
if (!supported) {
Alert.alert('您的系统不支持打开浏览器!')
} else {
return Linking.openURL(url);
}
}).catch(err => { }); }
JPushModule.addReceiveOpenNotificationListener(this.openNotificationListener) // this.getRegistrationIdListener = registrationId => {
// console.log('Device register succeed, registrationId ' + registrationId)
// }
// JPushModule.addGetRegistrationIdListener(this.getRegistrationIdListener)
/****************************通知 end **************************************************/ }
componentWillUnmount() {
JPushModule.removeReceiveCustomMsgListener(this.receiveCustomMsgListener)
JPushModule.removeReceiveNotificationListener(this.receiveNotificationListener)
JPushModule.removeReceiveOpenNotificationListener(this.openNotificationListener)
// JPushModule.removeGetRegistrationIdListener(this.getRegistrationIdListener)
// console.log('Will clear all notifications')
// JPushModule.clearAllNotifications()
} } ...
(2),在极光官网上推送
3.2,实现的效果
问题:
1,真机没接收到通知
解决:打开node_modules/jpush_react-native/android/src/AndroidManifest.xml,将所有的${applicationId}替换成你的包名。或将project/android/src/AndroidManifest.xml,的${applicationId}替换成你的包名。
... <application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
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> ... <!-- 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>
在.MainApplication和.MainActivity前添加包名