1.注冊阿里雲移動推送服務

2.項目引用組件
yarn add react-native-aliyun-push react-native link
3.android配置
在Project根目錄下build.gradle文件中配置maven庫URL:
allprojects {
repositories {
mavenLocal()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
// 下面是添加的代碼
maven {
url "http://maven.aliyun.com/nexus/content/repositories/releases/"
}
flatDir {
dirs project(':react-native-aliyun-push').file('libs')
}
// 添加結束
}
}
確保settings.gradle中被添加如下代碼:
include ':react-native-aliyun-push' project(':react-native-aliyun-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-aliyun-push/android')
確保app/build.gradle中被添加如下代碼:
dependencies { //下面是被添加的代碼 compile project(':react-native-aliyun-push') //添加結束 }
確保MainApplication.java中被添加如下代碼
// 下面是被添加的代碼
import org.wonday.aliyun.push.AliyunPushPackage;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
// 添加結束
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
//下面是被添加的代碼
new AliyunPushPackage()
//添加結束
);
}
};
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
//下面是添加的代碼
this.initCloudChannel();
//添加結束
}
// 下面是推送添加的代碼
/**
* 初始化阿里雲推送通道
* @param applicationContext
*/
private void initCloudChannel() {
PushServiceFactory.init(this.getApplicationContext());
CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.setNotificationSmallIcon(R.mipmap.ic_launcher);//設置通知欄小圖標, 需要自行添加,注意這里是ic_launcher而不是ic_launcher_s
pushService.register(this.getApplicationContext(),"阿里雲appKey", "阿里雲appSecret", new CommonCallback() {
@Override public void onSuccess(String responnse) {
// success
}
@Override public void onFailed(String code, String message) {
// failed
}
});
// 注冊方法會自動判斷是否支持小米系統推送,如不支持會跳過注冊。
MiPushRegister.register(this.getApplicationContext(), "小米AppID", "小米AppKey");
// 注冊方法會自動判斷是否支持華為系統推送,如不支持會跳過注冊。
HuaWeiRegister.register(this.getApplicationContext()); }
// 添加結束
4.ios
去蘋果開發者那里弄推送證書。。。(不多說了)
xcode-Capabilities打開下面兩個


添加node_modules/react-native-aliyun-push/ios/RCTAliyunPush.xcodeproj到xcode項目工程
拖拽node_modules/react-native-aliyun-push/ios/libs下列目錄到xcode工程的frameworks目錄下,將copy items if needed打勾。 注意:從阿里雲下載的SDK中UTDID.framework有問題,編譯會報錯,請使用react-native-aliyun-push中內置的版本。
- AlicloudUtils.framework
- CloudPushSDK.framework
- UTDID.framework
- UTMini.framework

- 點擊項目根節點,在targets app的BuildPhase的Link Binary With Libraries中添加公共包依賴
- libz.tbd
- libresolv.tbd
- libsqlite3.tbd
- CoreTelephony.framework
- SystemConfiguration.framework
- UserNotifications.framework
同時確保targets app的BuildPhase的Link Binary With Libraries包含
- AlicloudUtils.framework
- CloudPushSDK.framework
- UTDID.framework
- UTMini.framework
- 修改AppDelegate.m添加如下代碼/** * Copyright (c) 2015-present, Facebook, Inc.
* * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import "AppDelegate.h" #import <React/RCTBundleURLProvider.h> #import <React/RCTRootView.h> #import "AliyunPushManager.h"// 添加的代碼 @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *jsCodeLocation; // 原來的jsCodeLocation保留在這里 //jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; //開發環境 // jsCodeLocation = [NSURL URLWithString:@"http://192.168.1.96:8081/index.bundle?platform=ios&dev=true&minify=false"]; //生產環境 jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"AppDome" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; // 下面是添加的代碼 [[AliyunPushManager sharedInstance] setParams:@"阿里appKey" appSecret:@"阿里AppSecret" lauchOptions:launchOptions createNotificationCategoryHandler:^{ //create customize notification category here }]; // 添加結束 return YES; } // 下面是添加的代碼 // APNs注冊成功回調,將返回的deviceToken上傳到CloudPush服務器 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"test:%@",deviceToken); [[AliyunPushManager sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } // APNs注冊失敗回調 - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [[AliyunPushManager sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error]; } // 打開/刪除通知回調 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler { [[AliyunPushManager sharedInstance] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } // 請求注冊設定后,回調 - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [[AliyunPushManager sharedInstance] application:application didRegisterUserNotificationSettings:notificationSettings]; } // 添加結束 @end
5.項目代碼
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppState, Platform, StyleSheet, Text, View } from 'react-native'; import AliyunPush from 'react-native-aliyun-push'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); type Props = {}; export default class App extends Component<Props> { componentDidMount() { //監聽推送事件 AliyunPush.addListener(this.handleAliyunPushMessage); //獲取deviceId AliyunPush.getDeviceId() .then((deviceId) => { console.log("deviceId:" + deviceId); }) .catch((error) => { console.log("getDeviceId() failed"); }); //根據用戶賬號推送 AliyunPush.bindAccount("granty") .then((data) => { console.log("bindAccount success"); console.log(JSON.stringify(data)); }) .catch((error) => { console.log("bindAccount error"); console.log(JSON.stringify(error)); }); // AliyunPush.listTags('137') // .then((result)=>{ // console.log("listTags success"); // console.log(JSON.stringify(result)); // }) // .catch((error)=>{ // console.log("listTags error"); // console.log(JSON.stringify(error)); // }); //桌面應用圖標角標 AliyunPush.setApplicationIconBadgeNumber(5); AliyunPush.getApplicationIconBadgeNumber((num)=>{ console.log("ApplicationIconBadgeNumber:" + num); }); //獲取用戶是否開啟通知設定 (ios 10.0+支持) AliyunPush.getAuthorizationStatus((result)=>{ console.log("是否開啟通知設定:" + result); }); } componentWillUnmount() { // if (Platform.OS === 'android') { // BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid); // } AliyunPush.removeListener(this.handleAliyunPushMessage); } handleAliyunPushMessage = (e) => { console.log("Message Received. " + JSON.stringify(e)); if (e.actionIdentifier == "opened") { alert("我的點擊好像生效了") } //e結構說明: //e.type: "notification":通知 或者 "message":消息 //e.title: 推送通知/消息標題 //e.body: 推送通知/消息具體內容 //e.actionIdentifier: "opened":用戶點擊了通知, "removed"用戶刪除了通知, 其他非空值:用戶點擊了自定義action(僅限ios) //e.extras: 用戶附加的{key:value}的對象 }; render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit App.js </Text> <Text style={styles.instructions}> {instructions} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
