├── .gitignore
├── .npmignore
├── README.md
├── build.gradle
├── index.js
├── libs
└── MiPush_SDK_Client_3_1_2.jar
├── package.json
├── proguard-rules.pro
├── rn-mixpush-android.iml
└── src
└── main
├── AndroidManifest.xml
├── java
└── com
│ └── duanglink
│ ├── flymepush
│ ├── FlymePushManager.java
│ └── FlymePushMessageReceiver.java
│ ├── getui
│ ├── GeTuiManager.java
│ └── GeTuiMessageIntentService.java
│ ├── huaweipush
│ ├── HuaweiPushActivity.java
│ ├── HuaweiPushManager.java
│ └── HuaweiPushMessageReceiver.java
│ ├── mipush
│ ├── MiPushManager.java
│ └── MiPushMessageReceiver.java
│ └── rnmixpush
│ ├── HttpHelpers.java
│ ├── MixPushManager.java
│ ├── MixPushMoudle.java
│ └── MixPushReactPackage.java
└── res
└── values
└── strings.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .idea
3 | .gradle
4 | build
5 | local.properties
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-native-mixpush
2 |
3 | 集成小米推送、华为推送、魅族推送及个推推送的React-Native版本!
4 |
5 | 由于使用任何一种Android推送都很难在APP进程被杀死后收到推送,只有集成各厂商提供的系统级别推送才能完成此任务,故考虑小米、华为、魅族手机使用官方推送,其他手机使用个推推送!
6 |
7 | 注:本项目仅适用于android平台(ios统一的apns推送机制较为稳定,只需自行选择一种推送集成即可)。
8 |
9 |
10 | # 安装:
11 |
12 | npm install --save react-native-mixpush-android
13 |
14 | # 使用:
15 |
16 | ## 1、android/settings.gradle
17 |
18 | ...
19 | include ':react-native-mixpush-android'
20 | project(':react-native-mixpush-android').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mixpush-android')
21 |
22 | ## 2、app/build.gradle
23 |
24 | manifestPlaceholders = [
25 | PACKAGE_NAME : "你的包名",
26 | //测试环境
27 | GETUI_APP_ID : "个推APPID",
28 | GETUI_APP_KEY : "个推APPKEY",
29 | GETUI_APP_SECRET : "个推APPSECRE"
30 | ]
31 | dependencies {
32 | ...
33 | compile project(":react-native-mixpush-android")
34 | }
35 |
36 | ## 3、android/build.gradle
37 |
38 | allprojects {
39 | repositories {
40 | mavenLocal()
41 | jcenter()
42 | ...
43 | //个推
44 | maven {
45 | url "http://mvn.gt.igexin.com/nexus/content/repositories/releases/"
46 | }
47 | //华为推送
48 | maven {url 'http://developer.huawei.com/repo/'}
49 | }
50 | }
51 |
52 | ## 4、AndroidManifest.xml
53 |
54 | ### manifest节点下添加:
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
69 |
70 |
71 |
72 | ### application节点下添加:
73 |
74 |
75 |
79 |
80 | ## 5、注册推送
81 |
82 | ### MainApplication中引用组件:
83 |
84 | import com.duanglink.rnmixpush.MixPushReactPackage;
85 |
86 | protected List getPackages() {
87 | return Arrays.asList(
88 | new MainReactPackage(),
89 | ...
90 | new MixPushReactPackage()
91 | );
92 | }
93 | };
94 |
95 | ### MainActivity中注册推送:
96 |
97 | import com.duanglink.huaweipush.HuaweiPushActivity;
98 |
99 | public class MainActivity extends HuaweiPushActivity {
100 | @Override
101 | public void onCreate(Bundle savedInstanceState) {
102 | if(savedInstanceState==null){
103 | savedInstanceState=new Bundle();
104 | }
105 | savedInstanceState.putString("meizuAppId","魅族AppId");
106 | savedInstanceState.putString("meizuAppKey","魅族AppKey");
107 | savedInstanceState.putString("xiaomiAppId","小米AppId");
108 | savedInstanceState.putString("xiaomiAppKey","小米AppKey");
109 | super.onCreate(savedInstanceState);
110 | }
111 | ...
112 | }
113 |
114 | ## 6、React-Native客户端接收事件:
115 |
116 | var { NativeAppEventEmitter } = require('react-native');
117 | NativeAppEventEmitter.addListener(
118 | 'receiveRemoteNotification',
119 | (notification) => {
120 | Alert.alert('消息通知',notification);
121 | }
122 | );
123 |
124 | ## 7、React-Native客户端方法说明:
125 |
126 | import MixPush from 'react-native-mixpush-android';
127 |
128 | - MixPush.setAlias(alias); //设置别名
129 | - MixPush.unsetAlias(alias); //取消设置别名
130 | - MixPush.setTags(tags); //设置用户标签
131 | - MixPush.unsetTags(tags); //取消设置用户标签
132 | - MixPush.getClientId(); //获取客户端ID
133 |
134 | >以上方法均不支持华为手机
135 |
136 |
137 | 说明:getClientId获取到的ID为用户在推送平台的唯一标识(小米:regId,魅族:pushId;个推:clientId),用于定向推送;
138 |
139 |
140 | >此外,所有推送平台在APP推送注册成功后会往客户端发送一次注册成功事件(包含华为:deviceToken),事件名为:"receiveClientId",并携带clientId,可使用该事件与getClientId方法配合使用达到获取clientId的目的。
141 |
142 | 实例:
143 |
144 | //主动获取
145 | MixPush.getClientId((cid)=>{
146 | alert("cid:"+cid);//自行处理cid代码
147 | });
148 |
149 | //监听事件
150 | NativeAppEventEmitter.addListener(
151 | 'receiveClientId',
152 | (cid) => {
153 | alert("cid:"+cid);//自行处理cid代码
154 | }
155 | );
156 |
157 | ## 8、客户端推送示例
158 |
159 | #### 小米推送
160 |
161 | 
162 |
163 | ***
164 |
165 | #### 华为推送
166 |
167 | 
168 | 
169 |
170 | ***
171 |
172 | #### 魅族推送
173 |
174 | 
175 |
176 | ***
177 |
178 | #### 个推推送
179 |
180 | 
181 |
182 | ***
183 |
184 | # 特别说明
185 |
186 | 本项目参考了另外一个大神的开源项目 [joyrun/MixPush](https://github.com/joyrun/MixPush) !
187 |
188 | 由于本人非原生开发者,不妥之处请指正,邮箱:wangheng3751@qq.com !
189 |
190 | 目前项目处于持续完善更新中...
191 |
192 | >QQ交流群:516032289
193 |
194 | # 附录
195 | - [华为推送官方文档](http://developer.huawei.com/consumer/cn/service/hms/catalog/huaweipush_agent.html?page=hmssdk_huaweipush_devguide_client_agent) : http://developer.huawei.com/consumer/cn/service/hms/catalog/huaweipush_agent.html?page=hmssdk_huaweipush_devguide_client_agent
196 |
197 | - [小米推送官方文档](https://dev.mi.com/console/doc/detail?pId=41) : https://dev.mi.com/console/doc/detail?pId=41
198 |
199 | - [魅族推送官方文档](https://github.com/MEIZUPUSH/PushDemo) : https://github.com/MEIZUPUSH/PushDemo
200 |
201 | - [个推推送官方文档](http://docs.getui.com/getui/mobile/android/androidstudio_maven/) : http://docs.getui.com/getui/mobile/android/androidstudio_maven/
202 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | //compileSdkVersion 25
5 | //buildToolsVersion "25.0.3"
6 | compileSdkVersion 23
7 | buildToolsVersion "23.0.1"
8 |
9 | defaultConfig {
10 | minSdkVersion 16
11 | targetSdkVersion 22
12 | versionCode 1
13 | versionName "1.0"
14 | ndk {
15 | abiFilters "armeabi", "armeabi-v7a", "x86_64"
16 | }
17 | manifestPlaceholders = [
18 | //测试环境
19 | GETUI_APP_ID : "4PrFb29HZA7ROkO1wHNXB8",
20 | GETUI_APP_KEY : "W5s9oBaCLYAV6dPRFbBa1",
21 | GETUI_APP_SECRET : "YvmsRi08aU94oV92CQjlC"
22 | ]
23 | }
24 |
25 | buildTypes {
26 | release {
27 | minifyEnabled false
28 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
29 | }
30 | }
31 | }
32 |
33 | dependencies {
34 | compile fileTree(dir: 'libs', include: ['*.jar'])
35 | testCompile 'junit:junit:4.12'
36 | //compile 'com.android.support:appcompat-v7:25.3.1'
37 | compile "com.android.support:appcompat-v7:23.0.1"
38 | compile 'com.facebook.react:react-native:+'
39 | compile 'com.getui:sdk:2.11.1.0'
40 | compile 'com.meizu.flyme.internet:push-internal:3.4.2@aar'
41 | compile 'com.huawei.android.hms:push:2.5.2.300'
42 | }
43 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | const MixPush = require('react-native').NativeModules.MixPushModule;
2 | export default MixPush;
--------------------------------------------------------------------------------
/libs/MiPush_SDK_Client_3_1_2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangheng3751/react-native-mixpush/ee9298f98998f5ff8852f32d1e96c8e4a011b622/libs/MiPush_SDK_Client_3_1_2.jar
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-mixpush-android",
3 | "version": "1.0.7",
4 | "description": "集成小米推送、华为推送、魅族推送及个推推送的React-Native版本!",
5 | "main": "index.js",
6 | "keywords": [
7 | "push","mixpush","react-native-push"
8 | ],
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "repository": {
13 | "type": "git",
14 | "url": "git+https://github.com/wangheng3751/react-native-mixpush.git"
15 | },
16 | "author": "wangheng3751",
17 | "license": "ISC",
18 | "bugs": {
19 | "url": "https://github.com/wangheng3751/react-native-mixpush/issues"
20 | },
21 | "homepage": "https://github.com/wangheng3751/react-native-mixpush#readme"
22 | }
23 |
--------------------------------------------------------------------------------
/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Program Files\Java\android-sdk\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 | # huawei
19 | -ignorewarning
20 | -keepattributes *Annotation*
21 | -keepattributes Exceptions
22 | -keepattributes InnerClasses
23 | -keepattributes Signature
24 | -keepattributes SourceFile,LineNumberTable
25 | -keep class com.hianalytics.android.**{*;}
26 | -keep class com.huawei.updatesdk.**{*;}
27 | -keep class com.huawei.hms.**{*;}
--------------------------------------------------------------------------------
/rn-mixpush-android.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | generateDebugAndroidTestSources
19 | generateDebugSources
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
--------------------------------------------------------------------------------
/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
19 |
20 |
21 |
22 |
29 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/flymepush/FlymePushManager.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.flymepush;
2 |
3 | import android.content.Context;
4 |
5 | import com.duanglink.rnmixpush.MixPushManager;
6 | import com.meizu.cloud.pushsdk.PushManager;
7 |
8 | /**
9 | * Created by wangheng on 2017/11/22.
10 | */
11 | public class FlymePushManager implements MixPushManager {
12 | public static final String NAME = "meizuPush";
13 |
14 | private String appId;
15 | private String appKey;
16 |
17 | public FlymePushManager(String appId, String appKey) {
18 | this.appId = appId;
19 | this.appKey = appKey;
20 | }
21 |
22 | @Override
23 | public void registerPush(Context context) {
24 | PushManager.register(context, appId, appKey);
25 | }
26 |
27 | @Override
28 | public void unRegisterPush(Context context) {
29 | PushManager.unRegister(context, appId, appKey);
30 | }
31 |
32 | @Override
33 | public void setAlias(Context context, String alias) {
34 | PushManager.subScribeAlias(context, appId, appKey, PushManager.getPushId(context), alias);
35 | }
36 |
37 | @Override
38 | public void unsetAlias(Context context, String alias) {
39 | PushManager.unSubScribeAlias(context, appId, appKey, PushManager.getPushId(context), alias);
40 | }
41 |
42 | @Override
43 | public void setTags(Context context, String... tags) {
44 | for (String tag : tags) {
45 | PushManager.subScribeTags(context, appId, appKey, PushManager.getPushId(context), tag);
46 | }
47 | }
48 |
49 | @Override
50 | public void unsetTags(Context context, String... tags) {
51 | for (String tag : tags) {
52 | PushManager.unSubScribeTags(context, appId, appKey, PushManager.getPushId(context), tag);
53 | }
54 | }
55 |
56 | @Override
57 | public String getClientId(Context context) {
58 | return PushManager.getPushId(context);
59 | }
60 |
61 | @Override
62 | public String getName() {
63 | return NAME;
64 | }
65 |
66 | public static String sendPushMessage(String pushid){
67 | return "";
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/flymepush/FlymePushMessageReceiver.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.flymepush;
2 | import android.content.Context;
3 | import android.content.Intent;
4 | import android.util.Log;
5 | import com.duanglink.rnmixpush.MixPushMoudle;
6 | import com.meizu.cloud.pushinternal.DebugLogger;
7 | import com.meizu.cloud.pushsdk.MzPushMessageReceiver;
8 | import com.meizu.cloud.pushsdk.notification.PushNotificationBuilder;
9 | import com.meizu.cloud.pushsdk.platform.message.PushSwitchStatus;
10 | import com.meizu.cloud.pushsdk.platform.message.RegisterStatus;
11 | import com.meizu.cloud.pushsdk.platform.message.SubAliasStatus;
12 | import com.meizu.cloud.pushsdk.platform.message.SubTagsStatus;
13 | import com.meizu.cloud.pushsdk.platform.message.UnRegisterStatus;
14 |
15 | import java.util.Timer;
16 | import java.util.TimerTask;
17 |
18 | /**
19 | * Created by wangheng on 2017/11/22.
20 | */
21 | public class FlymePushMessageReceiver extends MzPushMessageReceiver {
22 | private static final String TAG = "MeizuPushMsgReceiver";
23 | private int mipush_notification;
24 | private int mipush_small_notification;
25 |
26 | @Override
27 | @Deprecated
28 | public void onRegister(Context context, String pushid) {
29 | Log.i(TAG, "得到pushId: " + pushid);
30 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_CLIENTID, pushid);
31 | //应用在接受返回的pushid
32 | }
33 |
34 | @Override
35 | public void onHandleIntent(Context context, Intent intent) {
36 | mipush_notification = context.getResources().getIdentifier("mipush_notification", "drawable", context.getPackageName());
37 | mipush_small_notification = context.getResources().getIdentifier("mipush_small_notification", "drawable", context.getPackageName());
38 | super.onHandleIntent(context, intent);
39 | }
40 |
41 | @Override
42 | public void onMessage(Context context, String s) {
43 | Log.i(TAG, "收到透传消息: " + s);
44 | //接收服务器推送的透传消息
45 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, s);
46 | }
47 |
48 | @Override
49 | @Deprecated
50 | public void onUnRegister(Context context, boolean b) {
51 | //调用PushManager.unRegister(context)方法后,会在此回调反注册状态
52 | }
53 |
54 | //设置通知栏小图标
55 | @Override
56 | public void onUpdateNotificationBuilder(PushNotificationBuilder pushNotificationBuilder) {
57 | if (mipush_notification > 0){
58 | pushNotificationBuilder.setmLargIcon(mipush_notification);
59 | Log.d(TAG,"设置通知栏大图标");
60 | }else {
61 | Log.e(TAG,"缺少drawable/mipush_notification.png");
62 | }
63 | if (mipush_small_notification > 0){
64 | pushNotificationBuilder.setmStatusbarIcon(mipush_small_notification);
65 | Log.d(TAG,"设置通知栏小图标");
66 | Log.e(TAG,"缺少drawable/mipush_small_notification.png");
67 | }
68 | }
69 |
70 | @Override
71 | public void onPushStatus(Context context,PushSwitchStatus pushSwitchStatus) {
72 | //检查通知栏和透传消息开关状态回调
73 | }
74 |
75 | @Override
76 | public void onRegisterStatus(Context context,RegisterStatus registerStatus) {
77 | //新版订阅回调
78 | String pushId= registerStatus.getPushId();
79 | Log.i(TAG, "得到pushId:" + pushId);
80 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_CLIENTID, pushId);
81 | }
82 |
83 | @Override
84 | public void onUnRegisterStatus(Context context,UnRegisterStatus unRegisterStatus) {
85 | Log.i(TAG,"onUnRegisterStatus "+unRegisterStatus);
86 | //新版反订阅回调
87 | }
88 |
89 | @Override
90 | public void onSubTagsStatus(Context context,SubTagsStatus subTagsStatus) {
91 | Log.i(TAG, "onSubTagsStatus " + subTagsStatus);
92 | //标签回调
93 | }
94 |
95 | @Override
96 | public void onSubAliasStatus(Context context,SubAliasStatus subAliasStatus) {
97 | Log.i(TAG, "onSubAliasStatus " + subAliasStatus);
98 | //别名回调
99 | }
100 | @Override
101 | public void onNotificationArrived(Context context, String title, String content, String selfDefineContentString) {
102 | //通知栏消息到达回调,flyme6基于android6.0以上不再回调
103 | DebugLogger.i(TAG,"onNotificationArrived title "+title + "content "+content + " selfDefineContentString "+selfDefineContentString);
104 | }
105 |
106 | @Override
107 | public void onNotificationClicked(Context context, String title, String content, String selfDefineContentString) {
108 | //通知栏消息点击回调
109 | Log.i(TAG, "点击通知栏消息:"+content+",自定义消息:"+selfDefineContentString);
110 | //MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, selfDefineContentString);
111 | final String msg=selfDefineContentString;
112 | TimerTask task = new TimerTask() {
113 | @Override
114 | public void run() {
115 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, msg);
116 | }
117 | };
118 | Timer timer = new Timer();
119 | timer.schedule(task, 1000);
120 | }
121 |
122 | @Override
123 | public void onNotificationDeleted(Context context, String title, String content, String selfDefineContentString) {
124 | //通知栏消息删除回调;flyme6基于android6.0以上不再回调
125 | DebugLogger.i(TAG,"onNotificationDeleted title "+title + "content "+content + " selfDefineContentString "+selfDefineContentString);
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/getui/GeTuiManager.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.getui;
2 |
3 | import android.content.Context;
4 | import android.util.Log;
5 | import android.widget.Toast;
6 | import com.duanglink.rnmixpush.HttpHelpers;
7 | import com.duanglink.rnmixpush.MixPushManager;
8 | import com.igexin.sdk.PushManager;
9 | import com.igexin.sdk.Tag;
10 | import org.json.JSONException;
11 | import org.json.JSONObject;
12 | import java.io.IOException;
13 | import java.net.URLEncoder;
14 | import java.sql.Timestamp;
15 | import java.text.MessageFormat;
16 | import java.text.SimpleDateFormat;
17 | import java.util.Calendar;
18 | import java.util.Date;
19 |
20 | /**
21 | * Created by wangheng on 2017/11/22.
22 | */
23 | public class GeTuiManager implements MixPushManager {
24 | public static final String NAME = "getui";
25 | private static String appId="4PrFb29HZA7ROkO1wHNXB8";
26 | private static String appKey="W5s9oBaCLYAV6dPRFbBa1";
27 | private static String masterSecret="FYzRODdJOaALrUYFlHb2V9";
28 | @Override
29 | public void registerPush(Context context) {
30 | PushManager.getInstance().initialize(context, null);
31 | PushManager.getInstance().registerPushIntentService(context, GeTuiMessageIntentService.class);
32 | }
33 |
34 | @Override
35 | public void unRegisterPush(Context context) {
36 | PushManager.getInstance().stopService(context);
37 | }
38 |
39 | @Override
40 | public void setAlias(Context context, String alias) {
41 | PushManager.getInstance().bindAlias(context, alias);
42 | }
43 |
44 | @Override
45 | public void unsetAlias(Context context, String alias) {
46 | PushManager.getInstance().unBindAlias(context, alias, false);
47 | }
48 |
49 | @Override
50 | public void setTags(Context context, String... tags) {
51 | Tag[] temps = new Tag[tags.length];
52 | for (int i = 0; i < tags.length; i++) {
53 | Tag tag = new Tag();
54 | tag.setName(tags[i]);
55 | temps[i] = tag;
56 | }
57 | PushManager.getInstance().setTag(context, temps, null);
58 | }
59 |
60 | @Override
61 | public void unsetTags(Context context, String... tags) {
62 | PushManager.getInstance().setTag(context, new Tag[0], null);
63 | }
64 |
65 | @Override
66 | public String getClientId(Context context) {
67 | return PushManager.getInstance().getClientid(context);
68 | }
69 |
70 | @Override
71 | public String getName() {
72 | return NAME;
73 | }
74 |
75 | public static String sendPushMessage(String cid) throws IOException,JSONException{
76 | String auth_sign=authSign();
77 | if(auth_sign=="")
78 | return "";
79 | String push_url=MessageFormat.format("https://restapi.getui.com/v1/{0}/push_single",appId);
80 | SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
81 | Calendar c = Calendar.getInstance();
82 |
83 | JSONObject message = new JSONObject();
84 | message.put("appkey",appKey);
85 | message.put("is_offline",false);
86 | message.put("msgtype","notification");
87 |
88 | JSONObject notification = new JSONObject();
89 | JSONObject style = new JSONObject();
90 | style.put("type",0);
91 | style.put("text","你收到一条来自个推的推送通知");
92 | style.put("title","个推测试");
93 | style.put("logo","push.png");
94 | style.put("logourl","");
95 | style.put("is_ring",true);
96 | style.put("is_vibrate",true);
97 | style.put("is_clearable",true);
98 | notification.put("style",style);
99 | notification.put("transmission_type",true);
100 | notification.put("transmission_content","这是透传的内容");
101 | notification.put("duration_begin",formater.format(c.getTime()));
102 | c.add(Calendar.DAY_OF_MONTH,1);//加一天
103 | notification.put("duration_end",formater.format(c.getTime()));
104 |
105 | Timestamp timestamp = new Timestamp(new Date().getTime());
106 | String postBody = MessageFormat.format(
107 | "message={0}¬ification={1}&cid={2}&requestid={3}",
108 | message.toString(),notification.toString(),cid,timestamp.toString());
109 | String result= HttpHelpers.sendPost(push_url, postBody);
110 | return result;
111 | }
112 |
113 | public static String authSign() throws JSONException {
114 | String time=new Date().getTime()+"";;
115 | String signUrl= MessageFormat.format("https://restapi.getui.com/v1/{0}/auth_sign",appId);
116 | String sign= HttpHelpers.getSHA256(appKey+time+masterSecret);
117 | String postBody = MessageFormat.format("sign={0}×tamp={1}&appkey={2}",sign ,time ,appKey);
118 | Log.i("GeTui", "postBody:"+postBody);
119 | String result= HttpHelpers.sendPost(signUrl, postBody);
120 | JSONObject obj= new JSONObject(result);;
121 | String ok = obj.getString("result");
122 | if(ok=="ok"){
123 | return obj.getString("auth_token");
124 | }
125 | Log.i("GeTui", "个推鉴权失败,code:"+ok);
126 | return "";
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/getui/GeTuiMessageIntentService.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.getui;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.util.Log;
6 | import android.widget.Toast;
7 |
8 | import com.duanglink.rnmixpush.MixPushMoudle;
9 | import com.facebook.react.bridge.Arguments;
10 | import com.facebook.react.bridge.WritableMap;
11 | import com.igexin.sdk.GTIntentService;
12 | import com.igexin.sdk.message.GTCmdMessage;
13 | import com.igexin.sdk.message.GTTransmitMessage;
14 |
15 | import org.json.JSONException;
16 | import org.json.JSONObject;
17 |
18 | import java.util.Timer;
19 | import java.util.TimerTask;
20 |
21 | /**
22 | * Created by wangheng on 2017/11/22.
23 | */
24 | public class GeTuiMessageIntentService extends GTIntentService {
25 | public GeTuiMessageIntentService() {
26 |
27 | }
28 |
29 | @Override
30 | public void onReceiveServicePid(Context context, int pid) {
31 | }
32 |
33 | @Override
34 | protected void onHandleIntent(Intent intent) {
35 | super.onHandleIntent(intent);
36 | }
37 |
38 | @Override
39 | public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
40 | //Toast.makeText(context, "收到消息", Toast.LENGTH_SHORT).show();
41 | final String message = new String(msg.getPayload());
42 | Log.e(TAG,"收到透传消息:"+message);
43 | //GetuiModule.sendEvent(GetuiModule.EVENT_RECEIVE_REMOTE_NOTIFICATION, param);
44 | //Toast.makeText(context, "sendEvent",Toast.LENGTH_SHORT).show();
45 | TimerTask task = new TimerTask() {
46 | @Override
47 | public void run() {
48 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, message);
49 | }
50 | };
51 | Timer timer = new Timer();
52 | timer.schedule(task, 1000);
53 | /*
54 | if (msg.getPayload() == null) {
55 | Log.e(TAG, "onReceiveMessageData -> " + "payload=null");
56 | return;
57 | }
58 | String data = new String(msg.getPayload());
59 | Log.e(TAG, "onReceiveMessageData -> " + "payload = " + data);
60 | try {
61 | JSONObject jsonObject = new JSONObject(data);
62 |
63 | } catch (JSONException e) {
64 | e.printStackTrace();
65 | }*/
66 | }
67 |
68 | @Override
69 | public void onReceiveClientId(Context context, String clientid) {
70 | //Toast.makeText(context,"onReceiveClientId -> " + "clientid = " + clientid, Toast.LENGTH_SHORT).show();
71 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_CLIENTID,clientid);
72 | Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
73 | }
74 |
75 | @Override
76 | public void onReceiveOnlineState(Context context, boolean online) {
77 |
78 | }
79 |
80 | @Override
81 | public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
82 | Log.e(TAG, "onReceiveCommandResult -> " + "action = " + cmdMessage.getAction());
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/huaweipush/HuaweiPushActivity.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.huaweipush;
2 | import android.content.DialogInterface;
3 | import android.os.Build;
4 | import android.os.Bundle;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 | import android.widget.Toast;
8 |
9 | import com.duanglink.flymepush.FlymePushManager;
10 | import com.duanglink.getui.GeTuiManager;
11 | import com.duanglink.mipush.MiPushManager;
12 | import com.duanglink.rnmixpush.MixPushMoudle;
13 | import com.facebook.react.BuildConfig;
14 | import com.facebook.react.ReactActivity;
15 | import com.facebook.react.ReactPackage;
16 | import com.facebook.soloader.SoLoader;
17 | import com.huawei.hms.api.ConnectionResult;
18 | import com.huawei.hms.api.HuaweiApiAvailability;
19 | import com.huawei.hms.api.HuaweiApiClient;
20 | import com.huawei.hms.support.api.client.PendingResult;
21 | import com.huawei.hms.support.api.client.ResultCallback;
22 | import com.huawei.hms.support.api.push.HuaweiPush;
23 | import com.huawei.hms.support.api.push.PushException;
24 | import com.huawei.hms.support.api.push.TokenResult;
25 | import com.duanglink.getui.GeTuiManager;
26 | import java.util.List;
27 |
28 | /**
29 | * Created by wangheng on 2017/11/27.
30 | */
31 | public class HuaweiPushActivity extends ReactActivity implements HuaweiApiClient.ConnectionCallbacks, HuaweiApiClient.OnConnectionFailedListener {
32 | public static final String TAG = "HuaweiPushActivity";
33 | //华为移动服务Client
34 | private HuaweiApiClient client;
35 | private static final int REQUEST_HMS_RESOLVE_ERROR = 1000;
36 |
37 | @Override
38 | public void onCreate(Bundle savedInstanceState) {
39 | super.onCreate(savedInstanceState);
40 | String brand= Build.BRAND.toLowerCase();
41 | //手机型号接入判断
42 | switch (brand){
43 | case "huawei":
44 | MixPushMoudle.pushManager=new HuaweiPushManager("","");
45 | //连接回调以及连接失败监听
46 | client = new HuaweiApiClient.Builder(this)
47 | .addApi(HuaweiPush.PUSH_API)
48 | .addConnectionCallbacks(this)
49 | .addOnConnectionFailedListener(this)
50 | .build();
51 | client.connect();
52 | break;
53 | case "xiaomi":
54 | MiPushManager mipush=new MiPushManager(savedInstanceState.getString("xiaomiAppId"),savedInstanceState.getString("xiaomiAppKey"));
55 | MixPushMoudle.pushManager=mipush;
56 | mipush.registerPush(this.getApplicationContext());
57 | break;
58 | case "meizu":
59 | FlymePushManager meizupush=new FlymePushManager(savedInstanceState.getString("meizuAppId"),savedInstanceState.getString("meizuAppKey"));
60 | MixPushMoudle.pushManager=meizupush;
61 | meizupush.registerPush(this.getApplicationContext());
62 | break;
63 | default:
64 | GeTuiManager getui=new GeTuiManager();
65 | MixPushMoudle.pushManager=getui;
66 | getui.registerPush(this.getApplicationContext());
67 | break;
68 | }
69 | }
70 |
71 | @Override
72 | protected String getMainComponentName() {
73 | return "mixpush";
74 | }
75 |
76 | @Override
77 | public void onConnected() {
78 | //华为移动服务client连接成功,在这边处理业务自己的事件
79 | Log.i(TAG, "HuaweiApiClient 连接成功");
80 | getTokenAsyn();
81 | }
82 |
83 | @Override
84 | public void onConnectionSuspended(int arg0) {
85 | //HuaweiApiClient异常断开连接
86 | //if (!this.isDestroyed() && !this.isFinishing()) {
87 | if (!this.isFinishing()) {
88 | client.connect();
89 | }
90 | Log.i(TAG, "HuaweiApiClient 连接断开");
91 | }
92 |
93 | @Override
94 | public void onConnectionFailed(ConnectionResult arg0) {
95 | Log.i(TAG, "HuaweiApiClient连接失败,错误码:" + arg0.getErrorCode());
96 | if(HuaweiApiAvailability.getInstance().isUserResolvableError(arg0.getErrorCode())) {
97 | HuaweiApiAvailability.getInstance().resolveError(this, arg0.getErrorCode(), REQUEST_HMS_RESOLVE_ERROR);
98 | } else {
99 | //其他错误码请参见开发指南或者API文档
100 | }
101 | }
102 |
103 | @Override
104 | protected void onDestroy() {
105 | super.onDestroy();
106 | //建议在onDestroy的时候停止连接华为移动服务
107 | //业务可以根据自己业务的形态来确定client的连接和断开的时机,但是确保connect和disconnect必须成对出现
108 | if(client!=null)client.disconnect();
109 | }
110 |
111 | private void getTokenAsyn() {
112 | PendingResult tokenResult = HuaweiPush.HuaweiPushApi.getToken(client);
113 | tokenResult.setResultCallback(new ResultCallback() {
114 | @Override
115 | public void onResult(TokenResult result) {
116 | if(result.getTokenRes().getRetCode() == 0) {
117 | Log.i(TAG, "获取Token成功");
118 | }
119 | else{
120 | Log.i(TAG, "获取Token失败");
121 | }
122 | }
123 | });
124 | }
125 |
126 | private void deleteToken(String token) {
127 | Log.i(TAG, "删除Token:" + token);
128 | if (!TextUtils.isEmpty(token)) {
129 | try {
130 | HuaweiPush.HuaweiPushApi.deleteToken(client, token);
131 | } catch (PushException e) {
132 | Log.i(TAG, "删除Token失败:" + e.getMessage());
133 | }
134 | }
135 | }
136 |
137 | private void getPushStatus() {
138 | Log.i(TAG, "开始获取PUSH连接状态");
139 | new Thread() {
140 | public void run() {
141 | HuaweiPush.HuaweiPushApi.getPushState(client);
142 | };
143 | }.start();
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/huaweipush/HuaweiPushManager.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.huaweipush;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.util.Log;
6 |
7 | import com.duanglink.rnmixpush.HttpHelpers;
8 | import com.duanglink.rnmixpush.MixPushManager;
9 | import com.huawei.hms.api.HuaweiApiClient;
10 | import com.huawei.hms.support.api.push.HuaweiPush;
11 | import com.xiaomi.mipush.sdk.MiPushClient;
12 |
13 | import org.json.JSONArray;
14 | import org.json.JSONException;
15 | import org.json.JSONObject;
16 |
17 | import java.io.IOException;
18 | import java.net.URLEncoder;
19 | import java.text.MessageFormat;
20 | import java.util.List;
21 |
22 | /**
23 | * Created by wangheng on 2017/11/22.
24 | */
25 | public class HuaweiPushManager implements MixPushManager {
26 | private static String appId="100147479";
27 | private static String appSecret="4fd1cf7269547184941d584ee6063f0d";
28 | public static final String NAME = "huaweipush";
29 |
30 | public HuaweiPushManager(String appId, String appSecret) {
31 | //this.appId = appId;
32 | //this.appSecret = appSecret;
33 | }
34 |
35 | @Override
36 | public void registerPush(Context context) {
37 |
38 | }
39 |
40 | @Override
41 | public void unRegisterPush(Context context) {
42 |
43 | }
44 |
45 | @Override
46 | public void setAlias(Context context, String alias) {
47 |
48 | }
49 |
50 | @Override
51 | public void unsetAlias(Context context, String alias) {
52 |
53 | }
54 |
55 | @Override
56 | public void setTags(Context context, String... tags) {
57 |
58 | }
59 |
60 | @Override
61 | public void unsetTags(Context context, String... tags) {
62 |
63 | }
64 |
65 | @Override
66 | public String getClientId(Context context) {
67 | return "";
68 | }
69 |
70 | @Override
71 | public String getName() {
72 | return NAME;
73 | }
74 |
75 | public static String refreshToken() throws IOException, JSONException
76 | {
77 | String tokenUrl="https://login.vmall.com/oauth2/token";
78 | String msgBody = MessageFormat.format("grant_type=client_credentials&client_secret={0}&client_id={1}", URLEncoder.encode(appSecret, "UTF-8"), appId);
79 | String response = HttpHelpers.sendPost(tokenUrl, msgBody);
80 | JSONObject obj= new JSONObject(response);;
81 | String accessToken = obj.getString("access_token");
82 | return accessToken;
83 | }
84 |
85 | //发送Push消息
86 | public static String sendPushMessage(String deviceToken) throws IOException,JSONException
87 | {
88 | String accessToken=refreshToken();
89 | String apiUrl="https://api.push.hicloud.com/pushsend.do";
90 | JSONArray deviceTokens = new JSONArray();//目标设备Token
91 | deviceTokens.put(deviceToken);
92 | //deviceTokens.put("0866936023001827300001100100CN01");//测试设备
93 | //deviceTokens.put("0A0000044270BAD0300001100100CN01");//测试设备
94 |
95 | JSONObject body = new JSONObject();//仅通知栏消息需要设置标题和内容,透传消息key和value为用户自定义
96 | body.put("title", "测试");//消息标题
97 | body.put("content", "测试华为通知");//消息内容体
98 |
99 | JSONObject param = new JSONObject();
100 | param.put("appPkgName", "com.mixpush");//定义需要打开的appPkgName
101 |
102 | JSONObject action = new JSONObject();
103 | action.put("type", 3);//类型3为打开APP,其他行为请参考接口文档设置
104 | action.put("param", param);//消息点击动作参数
105 |
106 | JSONObject msg = new JSONObject();
107 | msg.put("type", 3);//3: 通知栏消息,异步透传消息请根据接口文档设置
108 | msg.put("action", action);//消息点击动作
109 | msg.put("body", body);//通知栏消息body内容
110 |
111 | JSONObject ext = new JSONObject();//扩展信息,含BI消息统计,特定展示风格,消息折叠。
112 | ext.put("biTag", "Trump");//设置消息标签,如果带了这个标签,会在回执中推送给CP用于检测某种类型消息的到达率和状态
113 | ext.put("icon", "http://pic.qiantucdn.com/58pic/12/38/18/13758PIC4GV.jpg");//自定义推送消息在通知栏的图标,value为一个公网可以访问的URL
114 | JSONObject hps = new JSONObject();//华为PUSH消息总结构体
115 | hps.put("msg", msg);
116 | hps.put("ext", ext);
117 |
118 | JSONObject payload = new JSONObject();
119 | payload.put("hps", hps);
120 |
121 | String postBody = MessageFormat.format(
122 | "access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
123 | URLEncoder.encode(accessToken,"UTF-8"),
124 | URLEncoder.encode("openpush.message.api.send","UTF-8"),
125 | URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000),"UTF-8"),
126 | URLEncoder.encode(deviceTokens.toString(),"UTF-8"),
127 | URLEncoder.encode(payload.toString(),"UTF-8"));
128 |
129 | String postUrl = apiUrl + "?nsp_ctx=" + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + appId + "\"}", "UTF-8");
130 | String result= HttpHelpers.sendPost(postUrl, postBody);
131 | Log.i("HuaWeiPush", "PushResult:" + result);
132 | return result;
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/huaweipush/HuaweiPushMessageReceiver.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.huaweipush;
2 |
3 | import android.app.NotificationManager;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.util.Log;
8 | import android.widget.Toast;
9 |
10 | import com.duanglink.rnmixpush.MixPushMoudle;
11 | import com.huawei.hms.support.api.push.PushReceiver;
12 | import com.igexin.sdk.PushManager;
13 |
14 | import org.json.JSONArray;
15 | import org.json.JSONException;
16 | import org.json.JSONObject;
17 |
18 | import java.lang.reflect.Array;
19 | import java.util.Iterator;
20 | import java.util.Timer;
21 | import java.util.TimerTask;
22 |
23 | /**
24 | * Created by wangheng on 2017/11/22.
25 | */
26 | public class HuaweiPushMessageReceiver extends PushReceiver {
27 | public static final String TAG = "HuaweiPushRevicer";
28 |
29 | public static final String ACTION_UPDATEUI = "action.updateUI";
30 | @Override
31 | public void onToken(Context context, String token, Bundle extras) {
32 | Log.i(TAG, "得到Token为:" + token);
33 | //Toast.makeText(context, "Token为:" + token, Toast.LENGTH_SHORT).show();
34 | //MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_CLIENTID, token);
35 | //延时1秒后再发送事件,防止RN客户端还未初始化完成时在注册前就发送了事件
36 | final String stoken =token;
37 | TimerTask task = new TimerTask() {
38 | @Override
39 | public void run() {
40 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_CLIENTID, stoken);
41 | }
42 | };
43 | Timer timer = new Timer();
44 | timer.schedule(task, 1000);
45 | }
46 |
47 | @Override
48 | public boolean onPushMsg(Context context, byte[] msg, Bundle bundle) {
49 | try {
50 | //CP可以自己解析消息内容,然后做相应的处理
51 | String content = new String(msg, "UTF-8");
52 | Log.i(TAG, "收到PUSH透传消息,消息内容为:" + content);
53 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, content);
54 | } catch (Exception e) {
55 | e.printStackTrace();
56 | }
57 | return false;
58 | }
59 |
60 | public void onEvent(Context context, Event event, Bundle extras) {
61 | if (Event.NOTIFICATION_OPENED.equals(event) || Event.NOTIFICATION_CLICK_BTN.equals(event)) {
62 | String message = extras.getString(BOUND_KEY.pushMsgKey);
63 | final String content=parseMessage(message);
64 | int notifyId = extras.getInt(BOUND_KEY.pushNotifyId, 0);
65 | Log.i(TAG, "收到通知栏消息点击事件,notifyId:" + notifyId+",message:"+content);
66 | TimerTask task = new TimerTask() {
67 | @Override
68 | public void run() {
69 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, content);
70 | }
71 | };
72 | Timer timer = new Timer();
73 | timer.schedule(task, 1000);
74 |
75 | if (0 != notifyId) {
76 | NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
77 | manager.cancel(notifyId);
78 | }
79 | }
80 | super.onEvent(context, event, extras);
81 | }
82 |
83 | @Override
84 | public void onPushState(Context context, boolean pushState) {
85 | Log.i(TAG, "Push连接状态为:" + pushState);
86 | //Toast.makeText(context, "Push连接状态为:" + pushState, Toast.LENGTH_SHORT).show();
87 | Intent intent = new Intent();
88 | intent.setAction(ACTION_UPDATEUI);
89 | intent.putExtra("type", 2);
90 | intent.putExtra("pushState", pushState);
91 | context.sendBroadcast(intent);
92 | }
93 |
94 | private String parseMessage(String message){
95 | JSONObject info = new JSONObject();
96 | try {
97 | JSONArray json = new JSONArray(message);
98 | if(json.length()>0){
99 | for(int i=0;i sIterator = job.keys();
102 | while(sIterator.hasNext()){
103 | String key = sIterator.next();
104 | String value = job.getString(key);
105 | info.put(key,value);
106 | }
107 | }
108 | }
109 | }
110 | catch (JSONException e){
111 |
112 | }
113 | return info.toString();
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/mipush/MiPushManager.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by wangheng on 2017/11/22.
3 | */
4 | package com.duanglink.mipush;
5 |
6 | import android.content.Context;
7 |
8 | import com.duanglink.rnmixpush.MixPushManager;
9 | import com.xiaomi.mipush.sdk.MiPushClient;
10 |
11 | import java.util.List;
12 |
13 | public class MiPushManager implements MixPushManager {
14 | public static final String NAME = "mipush";
15 | private String appId;
16 | private String appKey;
17 |
18 | public MiPushManager(String appId, String appKey) {
19 | this.appId = appId;
20 | this.appKey = appKey;
21 | }
22 |
23 | @Override
24 | public void registerPush(Context context) {
25 | MiPushClient.registerPush(context.getApplicationContext(), appId, appKey);
26 | }
27 |
28 | @Override
29 | public void unRegisterPush(Context context) {
30 | unsetAlias(context, null);
31 | MiPushClient.unregisterPush(context.getApplicationContext());
32 | }
33 |
34 | @Override
35 | public void setAlias(Context context, String alias) {
36 | if (!MiPushClient.getAllAlias(context).contains(alias)) {
37 | MiPushClient.setAlias(context, alias, null);
38 | }
39 | }
40 |
41 | @Override
42 | public void unsetAlias(Context context, String alias) {
43 | List allAlias = MiPushClient.getAllAlias(context);
44 | for (int i = 0; i < allAlias.size(); i++) {
45 | MiPushClient.unsetAlias(context, allAlias.get(i), null);
46 | }
47 | }
48 |
49 | @Override
50 | public void setTags(Context context, String... tags) {
51 | for (String tag : tags){
52 | MiPushClient.subscribe(context, tag, null);
53 | }
54 |
55 | }
56 |
57 | @Override
58 | public void unsetTags(Context context, String... tags) {
59 | for (String tag : tags) {
60 | MiPushClient.unsubscribe(context, tag, null);
61 | }
62 | }
63 |
64 | @Override
65 | public String getClientId(Context context) {
66 | return MiPushClient.getRegId(context);
67 | }
68 |
69 | @Override
70 | public String getName() {
71 | return NAME;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/mipush/MiPushMessageReceiver.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.mipush;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.util.Log;
6 | import com.duanglink.rnmixpush.MixPushMoudle;
7 | import com.xiaomi.mipush.sdk.ErrorCode;
8 | import com.xiaomi.mipush.sdk.MiPushClient;
9 | import com.xiaomi.mipush.sdk.MiPushCommandMessage;
10 | import com.xiaomi.mipush.sdk.MiPushMessage;
11 | import com.xiaomi.mipush.sdk.PushMessageReceiver;
12 | import org.json.JSONException;
13 | import org.json.JSONObject;
14 | import java.util.List;
15 | import java.util.Map;
16 | import java.util.Timer;
17 | import java.util.TimerTask;
18 |
19 | /**
20 | * Created by wangheng on 2017/11/22.
21 | */
22 | public class MiPushMessageReceiver extends PushMessageReceiver {
23 | private static final String TAG = "MiPushMessageReceiver";
24 | private String mRegId;
25 | private long mResultCode = -1;
26 | private String mReason;
27 | private String mCommand;
28 | private String mMessage;
29 | private String mTopic;
30 | private String mAlias;
31 | private String mUserAccount;
32 | private String mStartTime;
33 | private String mEndTime;
34 | @Override
35 | public void onReceivePassThroughMessage(Context context, MiPushMessage message) {
36 | mMessage = message.getContent();
37 | Log.i(TAG, "收到透传消息: " + mMessage);
38 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, mMessage);
39 | }
40 | @Override
41 | public void onNotificationMessageClicked(Context context, MiPushMessage message) {
42 | mMessage = message.getContent();
43 | try {
44 | final String extra=mapToJsonString(message.getExtra());
45 | //JSONObject.
46 | Log.i(TAG, "点击通知栏消息: " + mMessage+",透传消息:"+extra);
47 | //启动应用
48 | Intent launchIntent = context.getPackageManager().
49 | getLaunchIntentForPackage(context.getPackageName());
50 | launchIntent.setFlags(
51 | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
52 | context.startActivity(launchIntent);
53 | //发送事件
54 | //MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, mMessage);
55 | //todo
56 | //延时1秒再发送事件 等待app初始化完成 1s这个事件待定
57 | TimerTask task = new TimerTask() {
58 | @Override
59 | public void run() {
60 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_REMOTE_NOTIFICATION, extra);
61 | }
62 | };
63 | Timer timer = new Timer();
64 | timer.schedule(task, 1000);
65 |
66 | }catch (JSONException e){
67 |
68 | }
69 | }
70 | @Override
71 | public void onNotificationMessageArrived(Context context, MiPushMessage message) {
72 | mMessage = message.getContent();
73 | Log.i(TAG, "收到通知栏消息: " + mMessage);
74 | }
75 |
76 | @Override
77 | public void onCommandResult(Context context, MiPushCommandMessage message) {
78 | String command = message.getCommand();
79 | List arguments = message.getCommandArguments();
80 | String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
81 | String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
82 | if (MiPushClient.COMMAND_REGISTER.equals(command)) {
83 | if (message.getResultCode() == ErrorCode.SUCCESS) {
84 | mRegId = cmdArg1;
85 | }
86 | } else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {
87 | if (message.getResultCode() == ErrorCode.SUCCESS) {
88 | mAlias = cmdArg1;
89 | }
90 | } else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {
91 | if (message.getResultCode() == ErrorCode.SUCCESS) {
92 | mAlias = cmdArg1;
93 | }
94 | } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {
95 | if (message.getResultCode() == ErrorCode.SUCCESS) {
96 | mTopic = cmdArg1;
97 | }
98 | } else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {
99 | if (message.getResultCode() == ErrorCode.SUCCESS) {
100 | mTopic = cmdArg1;
101 | }
102 | } else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {
103 | if (message.getResultCode() == ErrorCode.SUCCESS) {
104 | mStartTime = cmdArg1;
105 | mEndTime = cmdArg2;
106 | }
107 | }
108 | }
109 |
110 | @Override
111 | public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {
112 | String command = message.getCommand();
113 | List arguments = message.getCommandArguments();
114 | String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
115 | String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
116 | if (MiPushClient.COMMAND_REGISTER.equals(command)) {
117 | if (message.getResultCode() == ErrorCode.SUCCESS) {
118 | mRegId = cmdArg1;
119 | Log.i(TAG, "得到RegId: " + mRegId);
120 | MixPushMoudle.sendEvent(MixPushMoudle.EVENT_RECEIVE_CLIENTID,mRegId);
121 | }
122 | }
123 | }
124 |
125 | private String mapToJsonString(Map map) throws JSONException{
126 | JSONObject info = new JSONObject();
127 | for (Map.Entry entry : map.entrySet()) {
128 | info.put(entry.getKey(),entry.getValue());
129 | }
130 | return info.toString();
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/src/main/java/com/duanglink/rnmixpush/HttpHelpers.java:
--------------------------------------------------------------------------------
1 | package com.duanglink.rnmixpush;
2 |
3 | import com.facebook.common.util.Hex;
4 |
5 | import java.io.BufferedReader;
6 | import java.io.IOException;
7 | import java.io.InputStreamReader;
8 | import java.io.PrintWriter;
9 | import java.io.UnsupportedEncodingException;
10 | import java.net.URL;
11 | import java.net.URLConnection;
12 | import java.security.MessageDigest;
13 | import java.security.NoSuchAlgorithmException;
14 |
15 | /**
16 | * Created by wangheng on 2017/12/5.
17 | */
18 | public class HttpHelpers {
19 | public static String sendPost(String url, String param) {
20 | PrintWriter out = null;
21 | BufferedReader in = null;
22 | String result = "";
23 | try {
24 | URL realUrl = new URL(url);
25 | // 打开和URL之间的连接
26 | URLConnection conn = realUrl.openConnection();
27 | // 设置通用的请求属性
28 | conn.setRequestProperty("accept", "*/*");
29 | //conn.setRequestProperty("Content-Type", "application/json");
30 | conn.setRequestProperty("connection", "Keep-Alive");
31 | conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
32 | // 发送POST请求必须设置如下两行
33 | conn.setDoOutput(true);
34 | conn.setDoInput(true);
35 | // 获取URLConnection对象对应的输出流
36 | out = new PrintWriter(conn.getOutputStream());
37 | // 发送请求参数
38 | out.print(param);
39 | // flush输出流的缓冲
40 | out.flush();
41 | // 定义BufferedReader输入流来读取URL的响应
42 | in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
43 | String line;
44 | while ((line = in.readLine()) != null) {
45 | result += line;
46 | }
47 | } catch (Exception e) {
48 | System.out.println("发送 POST 请求出现异常!"+e);
49 | e.printStackTrace();
50 | }
51 | //使用finally块来关闭输出流、输入流
52 | finally{
53 | try{
54 | if(out!=null){
55 | out.close();
56 | }
57 | if(in!=null){
58 | in.close();
59 | }
60 | }
61 | catch(IOException ex){
62 | ex.printStackTrace();
63 | }
64 | }
65 | return result;
66 | }
67 |
68 | public static String getSHA256Str(String str){
69 | MessageDigest messageDigest;
70 | String encdeStr = "";
71 | try {
72 | messageDigest = MessageDigest.getInstance("SHA-256");
73 | byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
74 | encdeStr = Hex.encodeHex(hash,true);//true?false
75 | } catch (NoSuchAlgorithmException e) {
76 | e.printStackTrace();
77 | } catch (UnsupportedEncodingException e) {
78 | e.printStackTrace();
79 | }
80 | return encdeStr;
81 | }
82 |
83 | public static String getSHA256(String str){
84 | MessageDigest messageDigest;
85 | String encodeStr = "";
86 | try {
87 | messageDigest = MessageDigest.getInstance("SHA-256");
88 | messageDigest.update(str.getBytes("UTF-8"));
89 | encodeStr = byte2Hex(messageDigest.digest());
90 | } catch (NoSuchAlgorithmException e) {
91 | e.printStackTrace();
92 | } catch (UnsupportedEncodingException e) {
93 | e.printStackTrace();
94 | }
95 | return encodeStr;
96 | }
97 |
98 | private static String byte2Hex(byte[] bytes){
99 | StringBuffer stringBuffer = new StringBuffer();
100 | String temp = null;
101 | for (int i=0;i> createJSModules() {
19 | return Collections.emptyList();
20 | }
21 |
22 | @Override
23 | public List createViewManagers(ReactApplicationContext reactContext) {
24 | return Collections.emptyList();
25 | }
26 |
27 | @Override
28 | public List createNativeModules(
29 | ReactApplicationContext reactContext) {
30 | List modules = new ArrayList<>();
31 | modules.add(new MixPushMoudle(reactContext));
32 | return modules;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Rn-mixpush-android
3 |
4 |
--------------------------------------------------------------------------------