Wei Fang 5 年 前
コミット
2ec8a42920

+ 8 - 0
.gitignore

@@ -0,0 +1,8 @@
+android/build
+android/.settings
+android/.gradle
+.vscode
+android/.idea
+android/.project
+android/local.properties
+android/android.iml

ファイルの差分が大きいため隠しています
+ 53 - 0
LICENSE


+ 99 - 0
README.md

@@ -0,0 +1,99 @@
+Huawei Reactive-Native SDK
+Contents
+Introduction
+Installation Guide
+Reactive-Native SDK API Method Definition
+Configure description
+Licensing and Terms
+
+1. Introduction
+The Reactive-Native SDK code encapsulates the Huawei push client interface. It provides many APIs for your reference or use.
+The Reactive-Native SDK code package is described as follows:
+Android: core layer, bridging PushSDK bottom-layer code;
+src/RNMessageParser.js: parsing layer, which is used to parse the received Message message.
+index.js: external interface definition layer, which is used to define interface classes or reference files.
+
+2. Installation Guide
+Before using Reactive-Native SDK code, ensure that the RN development environment has been installed.
+Decompress the Reactive-Native SD compressed code package.
+Copy the decompressed react-native-hwpush package to the same path as the local directory.
+
+3. Reactive-Native SDK API method definition 
+   
+    HmsInstanceId   
+        getAAID(Callback callBack):string    
+        getId(Callback callBack): string 
+        getCreationTime(Callback callBack): long 
+        deleteAAID(Callback callBack):void   
+        getToken(Callback callBack): String    
+        deleteToken(Callback callBack): void  
+        
+    HmsMessaging    
+        isAutoInitEnabled(): boolean    
+        setAutoInitEnabled(boolean enable):void 
+        subscribe(String topic):Task<void>  
+        unsubscribe(String topic):Task<void>    
+        HmsMessageService com.huawei.hms.push   
+        onMessageReceived(RemoteMessage message):void   
+        onNewToken(String token): void  
+        onSendError(String msgId, Exception exception): void
+        onMessageSent(String msgId):void
+        onDeletedMessages(): void
+        
+    RNSendException
+        ERROR_UNKNOWN   
+        ERROR_INVALID_PARAMETERS    
+        ERROR_SIZE: 
+        ERROR_TTL_EXCEEDED  
+        ERROR_TOO_MANY_MESSAGES 
+        
+    RNMessagePriority   
+        PRIORITY_HIGH   
+        PRIORITY_NORMAL  
+        PRIORITY_UNKNOWN    
+        
+    RNRemoteMessage     
+        getCollapseKey(): indicates the collapse key. Its value is a character string.  
+        getDataOfMap:Map<String, String>    
+        getData(): indicates the data type. Its value is a character string.    
+        getToken(): indicates the token. Its value is a character string.   
+        getFrom(): string   
+        getMessageId(): indicates the message ID. Its value is a character string.  
+        getMessageType(): indicates the message type. Its value is a character string.  
+        getOriginalPriority():int   
+        getPriority():int   
+        getSentTime(): long 
+        getTo(): string 
+        getTtl(): int   
+        getBody(): string   
+        getBodyLocalizationArgs():String[]  
+        getBodyLocalizationKey(): indicates the localization key. Its value is a character string.  
+        getChannelId(): indicates the channel ID. Its value is a character string.  
+        getClickAction(): indicates the action. Its value is a character string.    
+        getIntentUri(): string  
+        getColor(): string  
+        getIcon(): indicates the ID of an Icon. Its value is a character string.    
+        getImageUrl(): URI  
+        getLink():Uri   
+        getSound(): string  
+        getTag(): indicates the tag type. Its value is a character string.  
+        getTitle(): string  
+        getTitleLocalizationArgs():String[] 
+        getTitleLocalizationKey():String    
+        getNotifyId(): int  
+        getDefaultLightSettings(): boolean  
+        getDefaultSound(): boolean  
+        getDefaultVibrateSettings(): boolean    
+        getEventTime(): Long    
+        getLightSettings(): int[]   
+        getLocalOnly(): boolean 
+        getNotificationCount(): Integer 
+        getNotificationPriority(): Integer  
+        getSticky(): boolean    
+        getTicker(): String 
+        getVibrateTimings(): long[] 
+        getVisibility(): Integer    
+4. Configure parameters.    
+No.
+5. Licensing and Terms  
+Huawei Reactive-Native SDK uses the Apache 2.0 license.

+ 49 - 0
android/build.gradle

@@ -0,0 +1,49 @@
+
+buildscript {
+    repositories {
+        jcenter()
+        google()
+
+        maven { url 'https://developer.huawei.com/repo/' }
+
+    }
+
+    dependencies {
+        classpath ("com.android.tools.build:gradle:3.3.0")
+        classpath ("com.huawei.agconnect:agcp:1.2.1.300")
+    }
+}
+
+apply plugin: 'com.android.library'
+
+android {
+    compileSdkVersion 28
+
+    defaultConfig {
+        minSdkVersion 18
+        targetSdkVersion 28
+        versionCode 1
+        versionName "1.0"
+    }
+    lintOptions {
+        abortOnError false
+    }
+}
+
+repositories {
+    jcenter()
+    google()
+
+    maven { url 'https://developer.huawei.com/repo/' }
+
+}
+
+dependencies {
+    implementation fileTree(include: ['*.jar'], dir: 'libs')
+    implementation 'com.facebook.react:react-native:+'
+
+    // push kit
+    implementation 'com.huawei.hms:push:4.0.2.300'
+}
+
+apply plugin: 'com.huawei.agconnect'

+ 15 - 0
android/src/main/AndroidManifest.xml

@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.huawei.hms.push">
+    <application>
+        <service
+            android:name="com.huawei.hms.push.react.RNHmsMessageService"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
+            </intent-filter>
+        </service>
+
+    </application>
+
+</manifest>

+ 54 - 0
android/src/main/java/com/huawei/hms/push/RNHwPushPackage.java

@@ -0,0 +1,54 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package com.huawei.hms.push;
+
+import com.facebook.react.ReactPackage;
+import com.facebook.react.bridge.JavaScriptModule;
+import com.facebook.react.bridge.NativeModule;
+import com.facebook.react.bridge.ReactApplicationContext;
+import com.facebook.react.uimanager.ViewManager;
+import com.huawei.hms.push.react.RNHmsInstanceId;
+import com.huawei.hms.push.react.RNHmsMessaging;
+import com.huawei.hms.push.react.RNReceiver;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class RNHwPushPackage implements ReactPackage {
+    @Override
+    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
+
+        List<NativeModule> modules = new ArrayList<>();
+
+        modules.add(new RNHmsInstanceId(reactContext));
+        modules.add(new RNHmsMessaging(reactContext));
+        modules.add(new RNReceiver(reactContext));
+
+        return modules;
+    }
+
+    // Deprecated from RN 0.47
+    public List<Class<? extends JavaScriptModule>> createJSModules() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
+        return Collections.emptyList();
+    }
+}

+ 32 - 0
android/src/main/java/com/huawei/hms/push/react/ActivityUtils.java

@@ -0,0 +1,32 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package com.huawei.hms.push.react;
+
+import android.app.Activity;
+import android.content.Context;
+
+import com.facebook.react.bridge.ReactApplicationContext;
+
+public class ActivityUtils {
+
+    public static Context getRealActivity(Activity currentActivity, ReactApplicationContext mContext) {
+        if (currentActivity != null){
+            return currentActivity;
+        }
+        return mContext;
+    }
+}

+ 40 - 0
android/src/main/java/com/huawei/hms/push/react/Constants.java

@@ -0,0 +1,40 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package com.huawei.hms.push.react;
+
+import android.app.Activity;
+import android.content.Context;
+
+import com.facebook.react.bridge.ReactApplicationContext;
+
+public class Constants {
+
+    public final static String RESULT_SUCESS = "0";
+
+    // Unknown error. Contact Huawei technical support.
+    public final static String RESULT_FAIL = "907122045";
+
+    // The message contains invalid parameters.
+    public final static String PARAMETR_IS_EMPTY = "907122042";
+
+    public final static String PushMsgReceiverEvent = "PushMsgReceiverEvent";
+
+    public final static String PushXmppMsgReceiverEvent = "PushXmppMsgReceiverEvent";
+
+    public final static String PushTokenMsgReceiverEvent = "PushTokenMsgReceiverEvent";
+
+}

+ 131 - 0
android/src/main/java/com/huawei/hms/push/react/RNHmsInstanceId.java

@@ -0,0 +1,131 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package com.huawei.hms.push.react;
+
+import android.util.Log;
+
+import com.facebook.react.bridge.Callback;
+import com.facebook.react.bridge.ReactApplicationContext;
+import com.facebook.react.bridge.ReactContextBaseJavaModule;
+import com.facebook.react.bridge.ReactMethod;
+import com.huawei.hmf.tasks.OnFailureListener;
+import com.huawei.hmf.tasks.OnSuccessListener;
+import com.huawei.hmf.tasks.Task;
+import com.huawei.hms.aaid.HmsInstanceId;
+import com.huawei.hms.aaid.entity.AAIDResult;
+import com.huawei.hms.common.ApiException;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.huawei.agconnect.config.AGConnectServicesConfig;
+
+public class RNHmsInstanceId extends ReactContextBaseJavaModule {
+
+    private static ReactApplicationContext mContext;
+
+    public RNHmsInstanceId(ReactApplicationContext reactContext) {
+        super(reactContext);
+        mContext = reactContext;
+    }
+
+    @Override
+    public String getName() {
+        return "RNHmsInstanceId";
+    }
+
+    @Override
+    public Map<String, Object> getConstants() {
+        final Map<String, Object> constants = new HashMap<>();
+        return constants;
+    }
+
+
+    @ReactMethod
+    public void getToken(Callback callBack) {
+        try {
+            String appId = AGConnectServicesConfig.fromContext(mContext).getString("client/app_id");
+            String token = HmsInstanceId.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).getToken(appId, "HCM");
+            callBack.invoke(Constants.RESULT_SUCESS, token);
+            Log.d("token", token);
+        } catch (ApiException e) {
+            callBack.invoke(e.getStatusCode(), e.getStatusCode());
+        }
+
+    }
+
+    @ReactMethod
+    public void getId(Callback callBack) {
+        try {
+            String instanceId = HmsInstanceId.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).getId();
+            callBack.invoke(Constants.RESULT_SUCESS, instanceId);
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+    @ReactMethod
+    public void getAAID(final Callback callBack) {
+        Task<AAIDResult> idResult = HmsInstanceId.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).getAAID();
+        idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
+
+            @Override
+            public void onSuccess(AAIDResult aaidResult) {
+                callBack.invoke(Constants.RESULT_SUCESS, aaidResult.getId());
+            }
+        }).addOnFailureListener(new OnFailureListener() {
+            @Override
+            public void onFailure(Exception e) {
+                callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+            }
+        });
+
+    }
+
+    @ReactMethod
+    public void getCreationTime(Callback callBack) {
+        try {
+            String createTime = HmsInstanceId.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).getCreationTime() + "";
+            callBack.invoke(Constants.RESULT_SUCESS, createTime);
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+    @ReactMethod
+    public void deleteAAID(Callback callBack) {
+        try {
+            HmsInstanceId.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).deleteAAID();
+            callBack.invoke(Constants.RESULT_SUCESS);
+        } catch (ApiException e) {
+            callBack.invoke(e.getStatusCode(), e.getMessage());
+        }
+    }
+
+    @ReactMethod
+    public void deleteToken(Callback callBack) {
+        try {
+            String appId = AGConnectServicesConfig.fromContext(mContext).getString("client/app_id");
+            HmsInstanceId.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).deleteToken(appId, "HCM");
+            callBack.invoke(Constants.RESULT_SUCESS);
+        } catch (ApiException e) {
+            callBack.invoke(e.getStatusCode(), e.getMessage());
+        }
+
+    }
+
+}

+ 70 - 0
android/src/main/java/com/huawei/hms/push/react/RNHmsMessageService.java

@@ -0,0 +1,70 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+
+package com.huawei.hms.push.react;
+
+import android.util.Log;
+
+import com.huawei.hms.push.HmsMessageService;
+import com.huawei.hms.push.RemoteMessage;
+import com.huawei.hms.push.SendException;
+
+
+public class RNHmsMessageService extends HmsMessageService {
+    private static final String TAG = "RNHmsMessageService";
+
+    @Override
+    public void onMessageReceived(RemoteMessage message) {
+        Log.w(TAG,"** onMessageReceived **");
+
+        RNReceiver.sendMsgEvent(message);
+    }
+
+    @Override
+    public void onDeletedMessages() {
+        Log.w(TAG,"** onDeletedMessages **");
+    }
+
+    @Override
+    public void onMessageSent(String msgId) {
+        Log.w(TAG,"** onMessageSent **");
+
+        RNReceiver.sendXmppMsgEvent(msgId, 0, "");
+    }
+
+    @Override
+    public void onSendError(String msgId, Exception exception) {
+        Log.w(TAG,"** onSendError **");
+
+        int errCode = ((SendException) exception).getErrorCode();
+        String errInfo = exception.getMessage();
+        RNReceiver.sendXmppMsgEvent(msgId, errCode, errInfo);
+    }
+
+    @Override
+    public void onNewToken(String token) {
+        try {
+            super.onNewToken(token);
+            Log.w(TAG,"** onNewToken **");
+            RNReceiver.sendTokenMsgEvent(token);
+        } catch (Exception e) {
+            Log.e(TAG, e.getMessage());
+        }
+    }
+
+
+}

+ 155 - 0
android/src/main/java/com/huawei/hms/push/react/RNHmsMessaging.java

@@ -0,0 +1,155 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package com.huawei.hms.push.react;
+
+import com.facebook.react.bridge.Callback;
+import com.facebook.react.bridge.ReactApplicationContext;
+import com.facebook.react.bridge.ReactContextBaseJavaModule;
+import com.facebook.react.bridge.ReactMethod;
+import com.huawei.hmf.tasks.OnCompleteListener;
+import com.huawei.hmf.tasks.Task;
+import com.huawei.hms.push.HmsMessaging;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class RNHmsMessaging extends ReactContextBaseJavaModule {
+
+    private static ReactApplicationContext mContext;
+
+    public RNHmsMessaging(ReactApplicationContext reactContext) {
+        super(reactContext);
+        mContext = reactContext;
+    }
+
+    @Override
+    public String getName() {
+        return "RNHmsMessaging";
+    }
+
+    @Override
+    public Map<String, Object> getConstants() {
+        final Map<String, Object> constants = new HashMap<>();
+        return constants;
+    }
+
+    @ReactMethod
+    public void isAutoInitEnabled(Callback callBack) {
+        try {
+            String autoInit = HmsMessaging.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).isAutoInitEnabled() + "";
+            callBack.invoke(Constants.RESULT_SUCESS, autoInit);
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+    @ReactMethod
+    public void setAutoInitEnabled(boolean enabled, Callback callBack) {
+        try {
+            HmsMessaging.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).setAutoInitEnabled(enabled);
+            callBack.invoke(Constants.RESULT_SUCESS, enabled);
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+    @ReactMethod
+    public void turnOnPush(final Callback callBack) {
+        try {
+            HmsMessaging.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).turnOnPush().addOnCompleteListener(new OnCompleteListener<Void>() {
+                @Override
+                public void onComplete(Task<Void> task) {
+                    if (task.isSuccessful()) {
+                        callBack.invoke(Constants.RESULT_SUCESS);
+                    } else {
+                        callBack.invoke(Constants.RESULT_FAIL, task.getException().getMessage());
+                    }
+                }
+            });
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+
+    @ReactMethod
+    public void turnOffPush(final Callback callBack) {
+        try {
+            HmsMessaging.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).turnOffPush().addOnCompleteListener(new OnCompleteListener<Void>() {
+                @Override
+                public void onComplete(Task<Void> task) {
+                    if (task.isSuccessful()) {
+                        callBack.invoke(Constants.RESULT_SUCESS);
+                    } else {
+                        callBack.invoke(Constants.RESULT_FAIL, task.getException().getMessage());
+                    }
+                }
+            });
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+
+    @ReactMethod
+    public void subscribe(String topic, final Callback callBack) {
+
+        if (topic == null || topic.toString().equals("")) {
+            callBack.invoke(Constants.PARAMETR_IS_EMPTY, "topic is empty!");
+            return;
+        }
+        try {
+            HmsMessaging.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).subscribe(topic).
+                    addOnCompleteListener(new OnCompleteListener<Void>() {
+                        @Override
+                        public void onComplete(Task<Void> task) {
+                            if (task.isSuccessful()) {
+                                callBack.invoke(Constants.RESULT_SUCESS);
+                            } else {
+                                callBack.invoke(Constants.RESULT_FAIL, task.getException().getMessage());
+                            }
+                        }
+                    });
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+    @ReactMethod
+    public void unsubscribe(String topic, final Callback callBack) {
+        if (topic == null || topic.toString().equals("")) {
+            callBack.invoke(Constants.PARAMETR_IS_EMPTY, "topic is empty!");
+            return;
+        }
+        try {
+            HmsMessaging.getInstance(ActivityUtils.getRealActivity(getCurrentActivity(), mContext)).unsubscribe(topic).
+                    addOnCompleteListener(new OnCompleteListener<Void>() {
+                        @Override
+                        public void onComplete(Task<Void> task) {
+                            if (task.isSuccessful()) {
+                                callBack.invoke(Constants.RESULT_SUCESS);
+                            } else {
+                                callBack.invoke(Constants.RESULT_FAIL, task.getException().getMessage());
+                            }
+                        }
+                    });
+        } catch (Exception e) {
+            callBack.invoke(Constants.RESULT_FAIL, e.getMessage());
+        }
+    }
+
+}

+ 130 - 0
android/src/main/java/com/huawei/hms/push/react/RNReceiver.java

@@ -0,0 +1,130 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+package com.huawei.hms.push.react;
+
+import android.util.Log;
+
+import com.facebook.react.bridge.Arguments;
+import com.facebook.react.bridge.ReactApplicationContext;
+import com.facebook.react.bridge.ReactContextBaseJavaModule;
+import com.facebook.react.bridge.WritableMap;
+import com.facebook.react.modules.core.DeviceEventManagerModule;
+import com.huawei.hms.push.RemoteMessage;
+
+import java.util.Arrays;
+
+public class RNReceiver extends ReactContextBaseJavaModule {
+    private static ReactApplicationContext mContext;
+    private static String TAG = RNReceiver.class.toString();
+
+    public RNReceiver(ReactApplicationContext reactContext) {
+        super(reactContext);
+        mContext = reactContext;
+    }
+
+
+    @Override
+    public String getName() {
+        return "RNReceiver";
+    }
+
+    public static void sendXmppMsgEvent(String msgId, int statusCode, String errInfo) {
+        WritableMap params = Arguments.createMap();
+        params.putString("result", statusCode + "");
+        params.putString("msgId", msgId);
+        params.putString("resultInfo", errInfo);
+
+        Log.d(TAG, "send Msg Xmpp Event params:" + params);
+        mContext
+                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
+                .emit(Constants.PushXmppMsgReceiverEvent, params);
+    }
+
+    public static void sendTokenMsgEvent(String token) {
+        WritableMap params = Arguments.createMap();
+        params.putString("token", token);
+
+        Log.d(TAG, "send Msg TokenEvent params:" + params);
+        mContext
+                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
+                .emit(Constants.PushTokenMsgReceiverEvent, params);
+    }
+
+
+    public static void sendMsgEvent(
+            RemoteMessage message) {
+        Log.d(TAG, "send Msg Event data:" + message.getData());
+        WritableMap params = Arguments.createMap();
+        params.putMap("msg", convertRmToMap(message));
+
+        mContext
+                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
+                .emit(Constants.PushMsgReceiverEvent, params);
+    }
+
+    private static WritableMap convertRmToMap(RemoteMessage message) {
+
+        WritableMap params = Arguments.createMap();
+
+        params.putString("collapseKey", message.getCollapseKey());
+        params.putString("data", message.getData());
+        params.putString("dataOfMap", message.getDataOfMap() + "");
+        params.putString("messageId", message.getMessageId());
+        params.putString("messageType", message.getMessageType());
+        params.putString("originalUrgency", message.getOriginalUrgency() + "");
+        params.putString("urgency", message.getUrgency() + "");
+        params.putString("ttl", message.getTtl() + "");
+        params.putString("sentTime", message.getSentTime() + "");
+        params.putString("to", message.getTo());
+        params.putString("from", message.getFrom());
+        params.putString("token", message.getToken());
+
+        if (message.getNotification() != null) {
+            RemoteMessage.Notification notification = message.getNotification();
+            params.putString("title", notification.getTitle());
+            params.putString("titleLocalizationKey", notification.getTitleLocalizationKey());
+            params.putString("titleLocalizationArgs", Arrays.toString(notification.getTitleLocalizationArgs()));
+            params.putString("bodyLocalizationKey", notification.getBodyLocalizationKey());
+            params.putString("bodyLocalizationArgs", Arrays.toString(notification.getBodyLocalizationArgs()));
+            params.putString("body", notification.getBody());
+            params.putString("icon", notification.getIcon());
+            params.putString("Sound", notification.getSound());
+            params.putString("Tag", notification.getTag());
+            params.putString("Color", notification.getColor());
+            params.putString("ClickAction", notification.getClickAction());
+            params.putString("ChannelId", notification.getChannelId());
+            params.putString("ImageUrl", notification.getImageUrl() + "");
+            params.putString("Link", notification.getLink() + "");
+            params.putString("NotifyId", notification.getNotifyId() + "");
+            params.putString("When", notification.getWhen() + "");
+            params.putString("LightSettings", Arrays.toString(notification.getLightSettings()));
+            params.putString("BadgeNumber", notification.getBadgeNumber() + "");
+            params.putString("Importance", notification.getImportance() + "");
+            params.putString("Ticker", notification.getTicker());
+            params.putString("vibrateConfig", Arrays.toString(notification.getVibrateConfig()));
+            params.putString("visibility", notification.getVisibility() + "");
+            params.putString("intentUri", notification.getIntentUri());
+            params.putString("isAutoCancel", notification.isAutoCancel() + "");
+            params.putString("isLocalOnly", notification.isLocalOnly() + "");
+            params.putString("isDefaultLight", notification.isDefaultLight() + "");
+            params.putString("isDefaultSound", notification.isDefaultSound() + "");
+            params.putString("isDefaultVibrate", notification.isDefaultVibrate() + "");
+        }
+
+        return params;
+    }
+}

+ 27 - 0
index.js

@@ -0,0 +1,27 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+import { NativeModules } from 'react-native';
+
+const { RNHmsInstanceId } = NativeModules;
+export default RNHmsInstanceId;
+
+export const { RNHmsMessaging } = NativeModules;
+
+export { RNRemoteMessage, RNReceiverEvent,RNErrorEnum} from './src/RNMessageParser';
+
+
+
+

+ 18 - 0
package.json

@@ -0,0 +1,18 @@
+
+{
+  "name": "react-native-hwpush",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "keywords": [
+    "react-native"
+  ],
+  "author": "",
+  "license": "",
+  "peerDependencies": {
+    "react-native": "^0.61.5"
+  }
+}

+ 500 - 0
src/RNMessageParser.js

@@ -0,0 +1,500 @@
+/*
+Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+export class RNRemoteMessage {
+
+    static INSTANCE_ID_SCOPE = 'HCM';
+
+    static PRIORITY_UNKNOWN = 0;
+    static PRIORITY_HIGH = 1;
+    static PRIORITY_NORMAL = 2;
+
+    static COLLAPSEKEY= 'collapseKey';
+    static DATA= 'data';
+    static DATAOFMAP= 'dataOfMap';
+    static MESSAGEID= 'messageId';
+    static MESSAGETYPE= 'messageType';
+    static ORIGINALURGENCY= 'originalUrgency';
+    static URGENCY=  'urgency';
+    static TTL= 'ttl';
+    static SENTTIME=  'sentTime';
+    static TO= 'to';
+    static FROM= 'from';
+    static TOKEN=  'token';
+
+    static NOTIFICATION = {
+        TITLE: 'title',
+        TITLELOCALIZATIONKEY: 'titleLocalizationKey',
+        TITLELOCALIZATIONARGS: 'titleLocalizationArgs',
+        BODYLOCALIZATIONKEY: 'bodyLocalizationKey',
+        BODYLOCALIZATIONARGS: 'bodyLocalizationArgs',
+        BODY: 'body',
+        ICON: 'icon',
+        SOUND: 'Sound',
+        TAG: 'Tag',
+        COLOR: 'Color',
+        CLICKACTION: 'ClickAction',
+        CHANNELID: 'ChannelId',
+        IMAGEURL: 'ImageUrl',
+        LINK: 'Link',
+        NOTIFYID: 'NotifyId',
+        WHEN: 'When',
+        LIGHTSETTINGS: 'LightSettings',
+        BADGENUMBER: 'BadgeNumber',
+        IMPORTANCE: 'Importance',
+        TICKER: 'Ticker',
+        VIBRATECONFIG: 'vibrateConfig',
+        VISIBILITY: 'visibility',
+        INTENTURI: 'intentUri',
+        ISAUTOCANCEL: 'isAutoCancel',
+        ISLOCALONLY: 'isLocalOnly',
+        ISDEFAULTLIGHT: 'isDefaultLight',
+        ISDEFAULTSOUND: 'isDefaultSound',
+        ISDEFAULTVIBRATE: 'isDefaultVibrate',
+    };
+
+
+    constructor(options = {}) {
+        this.remoteMsg = options;
+    }
+
+    /*
+     * parse all element,unordered
+     */
+    parseMsgAllAttribute() {
+        let pushResult = '';
+        for (const key in this.remoteMsg) {
+            pushResult = pushResult + key + ' : ' + this.remoteMsg[key] + '\n';
+        }
+        return pushResult;
+    }
+
+    /*
+     * getCollapseKey() Obtains the classification identifier (collapse key) of a message.
+     */
+    getCollapseKey() {
+        return this.remoteMsg[RNRemoteMessage.COLLAPSEKEY];
+    }
+
+    /*
+     * getData() Obtains valid content data of a message.
+     */
+    getData() {
+        return this.remoteMsg[RNRemoteMessage.DATA];
+    }
+
+    /*
+     * getDataOfMap() a message map.
+     */
+    getDataOfMap() {
+        return this.remoteMsg[RNRemoteMessage.DATAOFMAP];
+    }
+
+    /*
+     * getMessageId() Obtains the ID of a message.
+     */
+    getMessageId() {
+        return this.remoteMsg[RNRemoteMessage.MESSAGEID];
+    }
+
+    /*
+     * getMessageType() Obtains the type of a message.
+     */
+    getMessageType() {
+        return this.remoteMsg[RNRemoteMessage.MESSAGETYPE];
+    }
+
+    /*
+     * getOriginalUrgency() Obtains the original priority of a message.
+     */
+    getOriginalUrgency() {
+        return this.remoteMsg[RNRemoteMessage.ORIGINALURGENCY];
+    }
+
+    /*
+     * getUrgency() Obtains priority of a message.
+     */
+    getUrgency() {
+        return this.remoteMsg[RNRemoteMessage.URGENCY];
+    }
+
+    /*
+     * getTtl() Obtains valid getTtl of a message.
+     */
+    getTtl() {
+        return this.remoteMsg[RNRemoteMessage.TTL];
+    }
+
+    /*
+     * getSentTime() Obtains the time when a message is sent from the server.
+     */
+    getSentTime() {
+        return this.remoteMsg[RNRemoteMessage.SENTTIME];
+    }
+
+    /*
+     * getTo() Obtains the recipient of a message.
+     */
+    getTo() {
+        return this.remoteMsg[RNRemoteMessage.TO];
+    }
+
+    /*
+     * getFrom() Obtains the sender of a message.
+     */
+    getFrom() {
+        return this.remoteMsg[RNRemoteMessage.FROM];
+    }
+
+    /*
+     * getToken() Obtains valid token
+     */
+    getToken() {
+        return this.remoteMsg[RNRemoteMessage.TOKEN];
+    }
+
+    /*
+     * Notification:getTitle() Obtains the title of a message
+     */
+    getNotificationTitle() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.TITLE];
+    }
+
+    /*
+     * Notification:getTitleLocalizationKey() Obtains the key of the displayed title of a notification message
+     */
+    getTitleLocalizationKey() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.TITLELOCALIZATIONKEY];
+    }
+
+    /*
+     * Notification:getTitleLocalizationArgs() Obtains variable parameters of the displayed title of a message
+     */
+    getTitleLocalizationArgs() {
+        return this.remoteMsg[
+            RNRemoteMessage.NOTIFICATION.TITLELOCALIZATIONARGS
+            ];
+    }
+
+    /*
+     * Notification:getBodyLocalizationKey() Obtains the key of the displayed content of a message
+     */
+    getBodyLocalizationKey() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.BODYLOCALIZATIONKEY];
+    }
+
+    /*
+     * Notification:getBodyLocalizationArgs() Obtains variable parameters of the displayed content of a message
+     */
+    getBodyLocalizationArgs() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.BODYLOCALIZATIONARGS];
+    }
+
+    /*
+     * Notification:getBody() Obtains the body of a message
+     */
+    getBody() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.BODY];
+    }
+
+    /*
+     * Notification:getIcon() Obtains the icon of a message
+     */
+    getIcon() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.ICON];
+    }
+
+    /*
+     * Notification:getSound() Obtains the sound from a message
+     */
+    getSound() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.SOUND];
+    }
+
+    /*
+     * Notification:getTag() Obtains the tag from a message for message overwriting
+     */
+    getTag() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.TAG];
+    }
+
+    /*
+     * Notification:getColor() Obtains the colors of icons in a message
+     */
+    getColor() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.COLOR];
+    }
+
+    /*
+     * Notification:getClickAction() Obtains actions triggered by message tapping
+     */
+    getClickAction() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.CLICKACTION];
+    }
+
+    /*
+     * Notification:getChannelId() Obtains IDs of channels that support the display of messages
+     */
+    getChannelId() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.CHANNELID];
+    }
+
+    /*
+     * Notification:getImageUrl() Obtains the image URL from a message
+     */
+    getImageUrl() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.IMAGEURL];
+    }
+
+    /*
+     * Notification:getLink() Obtains the URL to be accessed from a message
+     */
+    getLink() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.LINK];
+    }
+
+    /*
+     * Notification:getNotifyId() Obtains the unique ID of a message
+     */
+    getNotifyId() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.NOTIFYID];
+    }
+
+    /*
+     * Notification:getWhen()
+     */
+    getWhen() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.WHEN];
+    }
+
+    /*
+     * Notification:getLightSettings()
+     */
+    getLightSettings() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.LIGHTSETTINGS];
+    }
+
+    /*
+     * Notification:getBadgeNumber()
+     */
+    getBadgeNumber() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.BADGENUMBER];
+    }
+
+    /*
+     * Notification:getImportance()
+     */
+    getImportance() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.IMPORTANCE];
+    }
+
+    /*
+     * Notification:getTicker()
+     */
+    getTicker() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.TICKER];
+    }
+
+    /*
+     * Notification:getVibrateConfig()
+     */
+    getVibrateConfig() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.VIBRATECONFIG];
+    }
+
+    /*
+     * Notification:getVisibility()
+     */
+    getVisibility() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.VISIBILITY];
+    }
+
+    /*
+     * Notification:getIntentUri()
+     */
+    getIntentUri() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.INTENTURI];
+    }
+
+    /*
+     * Notification:isAutoCancel()
+     */
+    isAutoCancel() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.ISAUTOCANCEL];
+    }
+
+    /*
+     * Notification:getIntentUri()
+     */
+    isLocalOnly() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.ISLOCALONLY];
+    }
+
+    /*
+     * Notification:isDefaultLight()
+     */
+    isDefaultLight() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.ISDEFAULTLIGHT];
+    }
+
+    /*
+     * Notification:isDefaultSound()
+     */
+    isDefaultSound() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.ISDEFAULTSOUND];
+    }
+
+    /*
+     * Notification:isDefaultVibrate()
+     */
+    isDefaultVibrate() {
+        return this.remoteMsg[RNRemoteMessage.NOTIFICATION.ISDEFAULTVIBRATE];
+    }
+}
+
+
+export const RNReceiverEvent = {
+    PushMsgReceiverEvent: 'PushMsgReceiverEvent',
+    PushXmppMsgReceiverEvent: 'PushXmppMsgReceiverEvent',
+    PushTokenMsgReceiverEvent: 'PushTokenMsgReceiverEvent',
+}
+
+export const RNErrorEnum = {
+    SUCCESS: 0,
+
+    // You do not have a token. Apply for a token.
+    ERROR_NO_TOKEN: 907122030,
+
+    // The current network is unavailable. Check the network connection.
+    ERROR_NO_NETWORK: 907122031,
+
+    // The token has expired. Delete the token and apply for a new one.
+    ERROR_TOKEN_INVALID: 907122032,
+
+    // If the Push service is unavailable, contact Huawei technical support.
+    ERROR_SERVICE_NOT_AVAILABLE: 907122046,
+
+    // If the Push server returns an error, contact Huawei technical support.
+    ERROR_PUSH_SERVER: 907122047,
+
+    // Unknown error. Contact Huawei technical support.
+    ERROR_UNKNOWN: 907122045,
+
+    // The number of subscribed topics exceeds 2000.
+    ERROR_TOPIC_EXCEED: 907122034,
+
+    // Failed to send the subscription topic. Contact Huawei technical support.
+    ERROR_TOPIC_SEND: 907122035,
+
+    // Push rights are not enabled. Enable the service and set push service parameters at AppGallery Connect.
+    ERROR_NO_RIGHT: 907122036,
+
+    // Failed to apply for the token. Contact Huawei technical support.
+    ERROR_GET_TOKEN_ERR: 907122037,
+
+    // No storage location is selected for the application or the storage location is invalid.
+    ERROR_STORAGE_LOCATION_EMPTY: 907122038,
+
+    // Failed to apply for a token. Cross-region token application is not allowed.
+    ERROR_NOT_ALLOW_CROSS_APPLY: 907122053,
+
+    // The message body size exceeds the maximum.
+    ERROR_SIZE: 907122041,
+
+    // The message contains invalid parameters.
+    ERROR_INVALID_PARAMETERS: 907122042,
+
+    // The number of sent messages reaches the upper limit. The messages will be discarded.
+    ERROR_TOO_MANY_MESSAGES: 907122043,
+
+    // The message lifetime expires before the message is successfully sent to the APP server.
+    ERROR_TTL_EXCEEDED: 907122044,
+
+    //  Huawei Mobile Services (APK) can't connect  Huawei Push  Kit.
+    ERROR_HMS_CLIENT_API: 907122048,
+
+    // The current EMUI version is too early to use the capability.
+    ERROR_OPERATION_NOT_SUPPORTED: 907122049,
+
+    // The operation cannot be performed in the main thread.
+    ERROR_MAIN_THREAD: 907122050,
+
+    // The device certificate authentication fails.
+    ERROR_HMS_DEVICE_AUTH_FAILED_SELF_MAPPING: 907122051,
+
+    // Failed to bind the service.
+    ERROR_BIND_SERVICE_SELF_MAPPING: 907122052,
+
+    // The SDK is being automatically initialized. Try again later.
+    ERROR_AUTO_INITIALIZING: 907122054,
+
+    /*The input parameter is incorrect. Check whether the related configuration information is correct.
+     * Example: app_id in the agconnect - services.json file;
+     * Check whether the build.gradle file is configured with the certificate signature.
+     */
+    ERROR_ARGUMENTS_INVALID: 907135000,
+    // Internal Push error. Contact Huawei technical support engineers.
+    ERROR_INTERNAL_ERROR: 907135001,
+    // The service does not exist. The invoked interface does not exist.
+    ERROR_NAMING_INVALID: 907135002,
+    // The ApiClient object is invalid.
+    ERROR_CLIENT_API_INVALID: 907135003,
+    // Invoking AIDL times out. Contact Huawei technical support.
+    ERROR_EXECUTE_TIMEOUT: 907135004,
+    // The current area does not support this service.
+    ERROR_NOT_IN_SERVICE: 907135005,
+    // If the AIDL connection session is invalid, contact Huawei technical support.
+    ERROR_SESSION_INVALID: 907135006,
+    // An error occurred when invoking an unspecified API.
+    ERROR_API_NOT_SPECIFIED: 1002,
+
+    /* Failed to invoke the gateway to query the application scope.
+     * Check whether the current app has been created and enabled in AppGallery Connect.
+     * If yes, contact Huawei technical support.
+     */
+    ERROR_GET_SCOPE_ERROR: 907135700,
+    /* Scope is not configured on the AppGallery Connect.
+     * Check whether the current app has been created and enabled in AppGallery Connect.
+     * If yes, contact Huawei technical support.
+     */
+    ERROR_SCOPE_LIST_EMPTY: 907135701,
+
+    /* The certificate fingerprint is not configured on the AppGallery Connect.
+     * 1. Check whether your phone can access the Internet.
+     * 2. Check whether the correct certificate fingerprint is configured in AppGallery Connect. For details, see AppGallery Connect configuration in Development Preparations.
+     * 3. If the check result is correct, contact Huawei technical support.
+     */
+    ERROR_CERT_FINGERPRINT_EMPTY: 907135702,
+
+    //Permission is not configured on the AppGallery Connect.
+    ERROR_PERMISSION_LIST_EMPTY: 907135703,
+
+    // The authentication information of the application does not exist.
+    ERROR_AUTH_INFO_NOT_EXIST: 6002,
+
+    // An error occurred during certificate fingerprint verification. Check whether the correct certificate fingerprint is configured in AppGallery Connect. For details, see AppGallery Connect configuration in Development Preparations.
+    ERROR_CERT_FINGERPRINT_ERROR: 6003,
+
+    // Interface authentication: The permission does not exist and is not applied for in AppGallery Connect.
+    ERROR_PERMISSION_NOT_EXIST: 6004,
+
+    // Interface authentication: unauthorized.
+    ERROR_PERMISSION_NOT_AUTHORIZED: 6005,
+
+    // Interface authentication: The authorization expires.
+    ERROR_PERMISSION_EXPIRED: 6006,
+
+}