react-native app集成阿里雲推送

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

 

2.項目引用組件node

yarn add react-native-aliyun-push 

react-native link

3.android配置react

在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.iosandroid

去蘋果開發者那裏弄推送證書。。。(很少說了)ios

xcode-Capabilities打開下面兩個git

添加node_modules/react-native-aliyun-push/ios/RCTAliyunPush.xcodeproj到xcode項目工程github

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

  • AlicloudUtils.framework
  • CloudPushSDK.framework
  • UTDID.framework
  • UTMini.framework

  1. 點擊項目根節點,在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包含npm

  • AlicloudUtils.framework
  • CloudPushSDK.framework
  • UTDID.framework
  • UTMini.framework
  1. 修改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.項目代碼react-native

/**
 * 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,
  },
});
    
相關文章
相關標籤/搜索