Compare commits

...

20 Commits

Author SHA1 Message Date
Pikachu 8dba1a4c5e Update JPushPlugin.m
1.修复 iOS8 以下不能注册推送的bug
2016-03-25 19:43:10 +08:00
Hevin d7fc0d2248 update arm64-v8a file
update arm64-v8a/libjpush210.so
2016-03-16 11:59:04 +08:00
Hevin 66729b7337 support android 6.0 2016-03-15 15:09:40 +08:00
Hevin a3082d0475 fix #75 2016-03-15 11:06:14 +08:00
E.B 3868e0be35 iOS - 修复因cordova版本不同导致的bug
1.因低版本cordova中AppDelegate继承自NSObject导致找不到 super
didFinishLaunchingWithOptions的问题。
2016-03-14 17:26:53 +08:00
Hevin 40c98f4f04 优化代码 2016-03-12 22:46:59 +08:00
Hevin 032b6f5d0c 添加之前缺少的导入代码 2016-03-12 16:50:51 +08:00
Hevin b4c02a96d5 修复应用在后台不能触发事件监听函数的 Bug 2016-03-11 20:28:08 +08:00
E.B 381395acaf Merge branch 'dev' 2016-03-11 13:21:32 +08:00
E.B cf39b64bfc iOS - update
1.更新api说明
2.代码处理null
2016-03-11 13:16:47 +08:00
Hevin c74b8372c0 修改 android 的具体 api 文档 2016-03-11 11:19:42 +08:00
Pikachuode 41bb3f871e Update iOS_detail_api.md
1.修正原先的小错误
2.添加新的接口:本地推送等。
2016-03-11 10:59:03 +08:00
Hevin ff090d63f6 替换已废弃的方法 2016-03-10 13:44:24 +08:00
Hevin c5c6b3da06 优化代码 2016-03-10 13:42:09 +08:00
E.B 6cee953edd iOS-添加功能
1.add crash日志      接口
2.add 本地通知        相关接口
3.add 地理位置上报 接口
2016-03-09 13:18:09 +08:00
E.B afe2230ed9 iOS优化代码
1.优化、简化了 AppDelegate+JPush.m 和 JPushPlugin.m 中的代码。
2.整理了JPushPlugin.h中的方法与注释。
2016-03-08 16:46:12 +08:00
Hevin 5c5d7c7848 修改 Android 手动安装文档 2016-03-04 15:57:12 +08:00
Hevin 416e41cb00 修改导入包 2016-03-04 15:36:07 +08:00
Hevin 7d4b6acacd 添加控制统计分析功能的API
添加控制统计分析的api,并修改了相关文档和示例代码,开发者可通过 js 代码直接控制是否启用统计分析功能。
2016-03-04 15:20:45 +08:00
Hevin dde913b922 Merge branch 'master' into dev 2016-03-04 13:49:13 +08:00
23 changed files with 1278 additions and 1264 deletions
+9 -4
View File
@@ -88,7 +88,7 @@ jpush-phonegap-plugin 支持 iOS,Android 的推送插件。
具体的API请参考这里 具体的API请参考这里
#### iOS和adnroid通用API简介 #### iOS和android通用API简介
+ 停止与恢复推送服务 API + 停止与恢复推送服务 API
@@ -152,7 +152,7 @@ jpush-phonegap-plugin 支持 iOS,Android 的推送插件。
[iOS API详细说明](document/iOS_detail_api.md) [iOS API详细说明](document/iOS_detail_api.md)
#### adnroid API简介 #### android API简介
+ 获取集成日志 + 获取集成日志
window.plugins.jPushPlugin.setDebugMode(mode) window.plugins.jPushPlugin.setDebugMode(mode)
@@ -165,7 +165,12 @@ jpush-phonegap-plugin 支持 iOS,Android 的推送插件。
+ 统计分析 API + 统计分析 API
onResume / onPause(java api) window.plugins.jPushPlugin.setStatisticsOpen(boolean)
或在 MainActivity 中的 onPause() 和 onResume() 方法中分别调用
JPushInterface.onResume(this) 和 JPushInterface.onPause(this) 来启用统计分析功能,
如果使用这种方式启用统计分析功能,则window.plugins.jPushPlugin.setStatisticsOpen(boolean)
方法不再有效,建议不要同时使用。
+ 清除通知 API + 清除通知 API
@@ -195,7 +200,7 @@ jpush-phonegap-plugin 支持 iOS,Android 的推送插件。
###常见问题 ###常见问题
####1. androd ####1. android
eclipse中phonegap工程import之后出现:`Type CallbackContext cannot be resolved to a type` eclipse中phonegap工程import之后出现:`Type CallbackContext cannot be resolved to a type`
解决方案:eclipse中右键单击工程名,Build Path->Config Build Path->Projects->选中 工程名称-CordovaLib->点击 add 解决方案:eclipse中右键单击工程名,Build Path->Config Build Path->Projects->选中 工程名称-CordovaLib->点击 add
+13 -2
View File
@@ -80,6 +80,19 @@
JPushInterface.onPause(this); JPushInterface.onPause(this);
} }
#### API - setStatisticsOpen(boolean)
用于在 js 中控制是否打开应用的统计分析功能,但如果已经添加了上面的 onResume/onPause 方法,
就不能再通过这个方法来控制统计分析功能了。
#### 接口定义
window.plugins.jPushPlugin.setStatisticsOpen(boolean)
#### 参数说明
- boolean
-true : 打开统计分析功能
-false: 关闭统计分析功能
#### API - reportNotificationOpened #### API - reportNotificationOpened
@@ -181,5 +194,3 @@
- notificaitonID 设置本地通知的ID - notificaitonID 设置本地通知的ID
- broadcastTime 设置本地通知触发时间,为距离当前时间的数值,单位是毫秒 - broadcastTime 设置本地通知触发时间,为距离当前时间的数值,单位是毫秒
- extras 设置额外的数据信息extras为json字符串 - extras 设置额外的数据信息extras为json字符串
+1 -1
View File
@@ -4,7 +4,7 @@
1. 复制:`$JPUSH_PLUGIN_DIR`/src/android/*.java 到cn/jpush/phonega/目录下(即:cn.jpush.phonegap的包下) 1. 复制:`$JPUSH_PLUGIN_DIR`/src/android/*.java 到cn/jpush/phonega/目录下(即:cn.jpush.phonegap的包下)
2. 复制:`$JPUSH_PLUGIN_DIR`/src/android/armeabi/libjpush.so 到lib/armeabi/ 2. 复制:`$JPUSH_PLUGIN_DIR`/src/android/armeabi/libjpush.so 到lib/armeabi/
3. 复制:`$JPUSH_PLUGIN_DIR`/src/android/jpush-sdk-release1.5.0.jar 到lib/ 3. 复制:`$JPUSH_PLUGIN_DIR`/src/android/jpush-sdk-release2.0.6.jar 到lib/
4. 复制:`$JPUSH_PLUGIN_DIR`/src/android/test_notification_layout.xml到res/layout/ 4. 复制:`$JPUSH_PLUGIN_DIR`/src/android/test_notification_layout.xml到res/layout/
5. 复制:`$JPUSH_PLUGIN_DIR`/src/android/jpush_notification_icon.png到res/drawable/ 5. 复制:`$JPUSH_PLUGIN_DIR`/src/android/jpush_notification_icon.png到res/drawable/
6. 修改 AndroidManifest.xml 在 manifest 节点下添加以下权限 6. 修改 AndroidManifest.xml 在 manifest 节点下添加以下权限
+107 -20
View File
@@ -16,7 +16,7 @@
- data 是一个js字符串使用如下代码解析,js具体key根据应用内消息来确定 - data 是一个js字符串使用如下代码解析,js具体key根据应用内消息来确定
var bToObj = JSON.parse(data); var bToObj = JSON.parse(data)
#####返回值 #####返回值
@@ -30,9 +30,9 @@
本 API 用于“用户指定页面使用时长”的统计,并上报到服务器,在 Portal 上展示给开发者。页面统计集成正确,才能够获取正确的页面访问路径、访问深度(PV)的数据。 本 API 用于“用户指定页面使用时长”的统计,并上报到服务器,在 Portal 上展示给开发者。页面统计集成正确,才能够获取正确的页面访问路径、访问深度(PV)的数据。
##### 接口定义 ##### 接口定义
window.plugins.jPushPlugin.startLogPageView = function(pageName) window.plugins.jPushPlugin.prototype.startLogPageView = function(pageName)
window.plugins.jPushPlugin.stopLogPageView = function(pageName) window.plugins.jPushPlugin.prototype.stopLogPageView = function(pageName)
window.plugins.jPushPlugin.beginLogPageView = function(pageName,duration) window.plugins.jPushPlugin.prototype.beginLogPageView = function(pageName,duration)
#####参数说明 #####参数说明
pageName 需要统计页面自定义名称 pageName 需要统计页面自定义名称
duration 自定义的页面时间 duration 自定义的页面时间
@@ -44,11 +44,10 @@ duration 自定义的页面时间
#####代码示例 #####代码示例
if(window.plugins.jPushPlugin.isPlatformIOS()){
window.plugins.jPushPlugin.beginLogPageView("newPage",5); window.plugins.jPushPlugin.beginLogPageView("newPage",5);
window.plugins.jPushPlugin.startLogPageView("onePage"); window.plugins.jPushPlugin.startLogPageView("onePage");
window.plugins.jPushPlugin.stopLogPageView("onePage"); window.plugins.jPushPlugin.stopLogPageView("onePage");
}
### 设置Badge ### 设置Badge
#### API - setBadge,resetBadge #### API - setBadge,resetBadge
@@ -58,8 +57,8 @@ duration 自定义的页面时间
实际应用中,开发者可以直接对badge值做增减操作,无需自己维护用户与badge值之间的对应关系。 实际应用中,开发者可以直接对badge值做增减操作,无需自己维护用户与badge值之间的对应关系。
##### 接口定义 ##### 接口定义
window.plugins.jPushPlugin.setBadge(value) window.plugins.jPushPlugin.prototype.setBadge(value)
window.plugins.jPushPlugin.reSetBadge() window.plugins.jPushPlugin.prototype.reSetBadge()
`resetBadge相当于setBadge(0)` `resetBadge相当于setBadge(0)`
##### 参数说明 ##### 参数说明
@@ -68,10 +67,8 @@ value 取值范围:[0,99999]
无,控制台会有log打印设置结果 无,控制台会有log打印设置结果
#####代码示例 #####代码示例
if(window.plugins.jPushPlugin.isPlatformIOS()){
window.plugins.jPushPlugin.setBadge(5); window.plugins.jPushPlugin.setBadge(5);
window.plugins.jPushPlugin.reSetBadge(); window.plugins.jPushPlugin.reSetBadge();
}
#### API - setApplicationIconBadgeNumber #### API - setApplicationIconBadgeNumber
@@ -80,7 +77,7 @@ value 取值范围:[0,99999]
##### 接口定义 ##### 接口定义
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(badge) window.plugins.jPushPlugin.prototype.setApplicationIconBadgeNumber(badge)
##### 参数说明 ##### 参数说明
@@ -89,9 +86,7 @@ value 取值范围:[0,99999]
#####代码示例 #####代码示例
if(window.plugins.jPushPlugin.isPlatformIOS()){
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0); window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
}
#### API - getApplicationIconBadgeNumber #### API - getApplicationIconBadgeNumber
@@ -100,7 +95,7 @@ value 取值范围:[0,99999]
##### 接口定义 ##### 接口定义
window.plugins.jPushPlugin.getApplicationIconBadgeNumber(callback) window.plugins.jPushPlugin.prototype.getApplicationIconBadgeNumber(callback)
##### 参数说明 ##### 参数说明
@@ -116,6 +111,55 @@ window.plugins.jPushPlugin.getApplicationIconBadgeNumber(function(data){
``` ```
### 本地通知 ### 本地通知
#### API - addLocalNotificationForIOS
API用于注册本地通知
最多支持64个
##### 接口定义
window.plugins.jPushPlugin.prototype.addLocalNotificationForIOS(delayTime,content,badge,notificationID,extras)
##### 参数说明
- delayTime 本地推送延迟多长时间后显示,数值类型或纯数字的字符型均可
- content 本地推送需要显示的内容
- badge 角标的数字。如果不需要改变角标传-1。数值类型或纯数字的字符型均可
- notificationID 本地推送标识符,字符串。
- extras 自定义参数,可以用来标识推送和增加附加信息。字典类型。
#####代码示例
window.plugins.jPushPlugin.addLocalNotificationForIOS(6*60*60,"本地推送内容",1,"notiId",{"key":"value"});
#### API - deleteLocalNotificationWithIdentifierKeyInIOS
API删除本地推送定义
##### 接口定义
window.plugins.jPushPlugin.prototype.deleteLocalNotificationWithIdentifierKeyInIOS(identifierKey)
##### 参数说明
- identifierKey 本地推送标识符
#####代码示例
window.plugins.jPushPlugin.deleteLocalNotificationWithIdentifierKeyInIOS("identifier");
#### API - clearAllLocalNotifications
API清除所有本地推送对象
##### 接口定义
window.plugins.jPushPlugin.prototype.clearAllLocalNotifications()
#####代码示例
window.plugins.jPushPlugin.clearAllLocalNotifications();
### 日志等级设置 ### 日志等级设置
#### API - setDebugModeFromIos #### API - setDebugModeFromIos
@@ -124,13 +168,11 @@ API 用于开启Debug模式,显示更多的日志信息
建议调试时开启这个选项,不调试的时候注释这句代码,这个函数setLogOFF是相反的一对 建议调试时开启这个选项,不调试的时候注释这句代码,这个函数setLogOFF是相反的一对
##### 接口定义 ##### 接口定义
window.plugins.jPushPlugin.reSetBadge.setDebugModeFromIos() window.plugins.jPushPlugin.prototype.setDebugModeFromIos()
#####代码示例 #####代码示例
if(window.plugins.jPushPlugin.isPlatformIOS()){
window.plugins.jPushPlugin.setDebugModeFromIos(); window.plugins.jPushPlugin.setDebugModeFromIos();
}
#### API - setLogOFF #### API - setLogOFF
@@ -140,11 +182,56 @@ API用来关闭日志信息(除了必要的错误信息)
##### 接口定义 ##### 接口定义
window.plugins.jPushPlugin.reSetBadge.setLogOFF () window.plugins.jPushPlugin.prototype.setLogOFF()
#####代码示例
window.plugins.jPushPlugin.setLogOFF();
#### API - setCrashLogON
API用于统计用户应用崩溃日志
如果需要统计Log信息,调用该接口。当你需要自己收集错误信息时,切记不要调用该接口。
##### 接口定义
window.plugins.jPushPlugin.prototype.setCrashLogON()
#####代码示例
window.plugins.jPushPlugin.setCrashLogON();
### 地理位置上报
#### API - setLocation
API 用于统计用户地理信息
##### 接口定义
window.plugins.jPushPlugin.prototype.setLocation(latitude,longitude)
##### 参数说明
- latitude 地理位置纬度,数值类型或纯数字的字符型均可
- longitude 地理位置精度,数值类型或纯数字的字符型均可
#####代码示例
window.plugins.jPushPlugin.setLocation(39.26,115.25);
### 设备平台判断
#### API - isPlatformIOS
API 用于区分iOS、Android平台,以便不同设置
##### 接口定义
window.plugins.jPushPlugin.prototype.isPlatformIOS()
#####代码示例 #####代码示例
if(window.plugins.jPushPlugin.isPlatformIOS()){ if(window.plugins.jPushPlugin.isPlatformIOS()){
window.plugins.jPushPlugin.setLogOFF(); //iOS
}else{
//Android
} }
+1 -2
View File
@@ -105,6 +105,7 @@
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0); window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
} else { } else {
window.plugins.jPushPlugin.setDebugMode(true); window.plugins.jPushPlugin.setDebugMode(true);
window.plugins.jPushPlugin.setStatisticsOpen(true);
} }
} }
catch (exception) { catch (exception) {
@@ -220,5 +221,3 @@
</div> </div>
</body> </body>
</html> </html>
+6 -4
View File
@@ -163,10 +163,12 @@
<meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/> <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/>
<meta-data android:name="JPUSH_APPKEY" android:value="$API_KEY"/> <meta-data android:name="JPUSH_APPKEY" android:value="$API_KEY"/>
</config-file> </config-file>
<source-file src="src/android/jpush-android-2.0.6.jar" target-dir="libs"/> <source-file src="src/android/jpush-android-2.1.0.jar" target-dir="libs"/>
<source-file src="src/android/armeabi/libjpush206.so" target-dir="libs/armeabi"/> <source-file src="src/android/armeabi/libjpush210.so" target-dir="libs/armeabi"/>
<source-file src="src/android/armeabi-v7a/libjpush206.so" target-dir="libs/armeabi-v7a"/> <source-file src="src/android/armeabi-v7a/libjpush210.so" target-dir="libs/armeabi-v7a"/>
<source-file src="src/android/arm64-v8a/libjpush206.so" target-dir="libs/arm64-v8a"/> <source-file src="src/android/arm64-v8a/libjpush210.so" target-dir="libs/arm64-v8a"/>
<source-file src="src/android/x86/libjpush210.so" target-dir="libs/x86"/>
<source-file src="src/android/x86_64/libjpush210.so" target-dir="libs/x86_64"/>
<!--<source-file src="src/android/JPushPlugin.java" target-dir="src/cn/jpush/phonegap"/>--> <!--<source-file src="src/android/JPushPlugin.java" target-dir="src/cn/jpush/phonegap"/>-->
<source-file src="src/android/MyReceiver.java" target-dir="src/cn/jpush/phonegap"/> <source-file src="src/android/MyReceiver.java" target-dir="src/cn/jpush/phonegap"/>
+138 -160
View File
@@ -1,14 +1,13 @@
package cn.jpush.phonegap; package cn.jpush.phonegap;
import java.lang.reflect.Method; import android.app.Activity;
import java.util.Arrays; import android.app.Notification;
import java.util.HashMap; import android.content.ComponentName;
import java.util.HashSet; import android.content.Intent;
import java.util.List; import android.content.Context;
import java.util.Map; import android.util.Log;
import java.util.Set;
import java.util.concurrent.ExecutorService; import __PACKAGE_NAME__.R;
import java.util.concurrent.Executors;
import org.apache.cordova.CallbackContext; import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaInterface;
@@ -17,17 +16,23 @@ import org.apache.cordova.CordovaWebView;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Map.Entry;
import __PACKAGE_NAME__.R; import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import cn.jpush.android.api.BasicPushNotificationBuilder; import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder; import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification;
import cn.jpush.android.api.TagAliasCallback; import cn.jpush.android.api.TagAliasCallback;
import android.util.Log; import cn.jpush.android.data.JPushLocalNotification;
public class JPushPlugin extends CordovaPlugin { public class JPushPlugin extends CordovaPlugin {
private final static List<String> methodList = private final static List<String> methodList =
@@ -54,20 +59,22 @@ public class JPushPlugin extends CordovaPlugin {
"clearLocalNotifications", "clearLocalNotifications",
"onResume", "onResume",
"onPause", "onPause",
"reportNotificationOpened"); "reportNotificationOpened",
"setStatisticsOpen");
private ExecutorService threadPool = Executors.newFixedThreadPool(1); private ExecutorService threadPool = Executors.newFixedThreadPool(1);
private static JPushPlugin instance; private static JPushPlugin instance;
private static Activity cordovaActivity;
private static String TAG = "JPushPlugin"; private static String TAG = "JPushPlugin";
private static boolean shouldCacheMsg = false; private static boolean shouldCacheMsg = false;
private static boolean isStatisticsOpened = true; // 是否开启统计分析功能
public static String notificationAlert; public static String notificationAlert;
public static Map<String, Object> notificationExtras = new HashMap<String, Object>(); public static Map<String, Object> notificationExtras = new HashMap<String, Object>();
public static String openNotificationAlert; public static String openNotificationAlert;
public static Map<String, Object> openNotificationExtras = new HashMap<String, Object>(); public static Map<String, Object> openNotificationExtras = new HashMap<String, Object>();
public JPushPlugin() { public JPushPlugin() {
instance = this; instance = this;
} }
@@ -76,45 +83,53 @@ public class JPushPlugin extends CordovaPlugin {
public void initialize(CordovaInterface cordova, CordovaWebView webView) { public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView); super.initialize(cordova, webView);
Log.i(TAG, "---------------- initialize"+"-"+JPushPlugin.openNotificationAlert + "-" + JPushPlugin.notificationAlert); Log.i(TAG, "---------------- initialize" + "-"
+ JPushPlugin.openNotificationAlert + "-"
+ JPushPlugin.notificationAlert);
shouldCacheMsg = false; cordovaActivity = this.cordova.getActivity();
//如果同时缓存了打开事件openNotificationAlert 和 消息事件notificationAlert,只向UI 发 打开事件。 //如果同时缓存了打开事件openNotificationAlert 和 消息事件notificationAlert,只向UI 发 打开事件。
//这样做是为了和iOS 统一 //这样做是为了和iOS 统一
if (JPushPlugin.openNotificationAlert != null) { if (JPushPlugin.openNotificationAlert != null) {
JPushPlugin.notificationAlert = null; JPushPlugin.notificationAlert = null;
JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert, JPushPlugin.openNotificationExtras); JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert,
JPushPlugin.openNotificationExtras);
} }
if (JPushPlugin.notificationAlert != null) { if (JPushPlugin.notificationAlert != null) {
JPushPlugin.transmitReceive(JPushPlugin.notificationAlert, JPushPlugin.notificationExtras); JPushPlugin.transmitReceive(JPushPlugin.notificationAlert,
JPushPlugin.notificationExtras);
} }
//JPushInterface.init(cordova.getActivity().getApplicationContext()); //JPushInterface.init(cordova.getActivity().getApplicationContext());
} }
public void onPause(boolean multitasking) { public void onPause(boolean multitasking) {
Log.i(TAG, "---------------- onPause"); Log.i(TAG, "---------------- onPause");
shouldCacheMsg = true; shouldCacheMsg = true;
if (isStatisticsOpened) {
JPushInterface.onPause(cordovaActivity);
}
} }
public void onResume(boolean multitasking) { public void onResume(boolean multitasking) {
shouldCacheMsg = false; shouldCacheMsg = false;
Log.i(TAG, "---------------- onResume"+"-"+JPushPlugin.openNotificationAlert + "-" + JPushPlugin.notificationAlert); Log.i(TAG, "---------------- onResume" + "-"
+ JPushPlugin.openNotificationAlert + "-"
+ JPushPlugin.notificationAlert);
if (isStatisticsOpened) {
JPushInterface.onResume(cordovaActivity);
}
if (JPushPlugin.openNotificationAlert != null) { if (JPushPlugin.openNotificationAlert != null) {
JPushPlugin.notificationAlert = null; JPushPlugin.notificationAlert = null;
JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert, JPushPlugin.openNotificationExtras); JPushPlugin.transmitOpen(JPushPlugin.openNotificationAlert,
JPushPlugin.openNotificationExtras);
} }
if (JPushPlugin.notificationAlert != null) { if (JPushPlugin.notificationAlert != null) {
JPushPlugin.transmitReceive(JPushPlugin.notificationAlert, JPushPlugin.notificationExtras); JPushPlugin.transmitReceive(JPushPlugin.notificationAlert,
JPushPlugin.notificationExtras);
} }
} }
private static JSONObject notificationObject(String message, private static JSONObject notificationObject(String message,
Map<String, Object> extras) { Map<String, Object> extras) {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
@@ -129,12 +144,11 @@ public class JPushPlugin extends CordovaPlugin {
jExtras.put(entry.getKey(), entry.getValue()); jExtras.put(entry.getKey(), entry.getValue());
} }
} }
if(jExtras.length()>0) if (jExtras.length() > 0) {
{
data.put("extras", jExtras); data.put("extras", jExtras);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace();
} }
return data; return data;
} }
@@ -153,93 +167,63 @@ public class JPushPlugin extends CordovaPlugin {
jExtras.put(entry.getKey(), entry.getValue()); jExtras.put(entry.getKey(), entry.getValue());
} }
} }
if(jExtras.length()>0) if (jExtras.length() > 0) {
{
data.put("extras", jExtras); data.put("extras", jExtras);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace();
} }
return data; return data;
} }
static void transmitPush(String message, Map<String, Object> extras) { static void transmitPush(String message, Map<String, Object> extras) {
if (instance == null) { if (instance == null) {
return; return;
} }
JSONObject data = notificationObject(message, extras); JSONObject data = notificationObject(message, extras);
String js = String String format = "window.plugins.jPushPlugin.receiveMessageInAndroidCallback(%s);";
.format("window.plugins.jPushPlugin.receiveMessageInAndroidCallback('%s');", final String js = String.format(format, data.toString());
data.toString()); cordovaActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
try { instance.webView.loadUrl("javascript:" + js);
instance.webView.sendJavascript(js);
// String jsEvent=String
// .format("cordova.fireDocumentEvent('jpush.receiveMessage',%s)",
// data.toString());
// instance.webView.sendJavascript(jsEvent);
} catch (NullPointerException e) {
} catch (Exception e) {
} }
});
} }
static void transmitOpen(String alert, Map<String, Object> extras) { static void transmitOpen(String alert, Map<String, Object> extras) {
if (instance == null) { if (instance == null) {
return; return;
} }
if (JPushPlugin.shouldCacheMsg) { if (JPushPlugin.shouldCacheMsg) {
return; return;
} }
Log.i(TAG, "---------------- transmitOpen");
JSONObject data = openNotificationObject(alert, extras); JSONObject data = openNotificationObject(alert, extras);
String js = String String format = "window.plugins.jPushPlugin.openNotificationInAndroidCallback(%s);";
.format("window.plugins.jPushPlugin.openNotificationInAndroidCallback('%s');", final String js = String.format(format, data.toString());
data.toString()); cordovaActivity.runOnUiThread(new Runnable() {
@Override
try { public void run() {
instance.webView.sendJavascript(js); instance.webView.loadUrl("javascript:" + js);
// String jsEvent=String
// .format("cordova.fireDocumentEvent('jpush.openNotification',%s)",
// data.toString());
// instance.webView.sendJavascript(jsEvent);
} catch (NullPointerException e) {
} catch (Exception e) {
} }
});
JPushPlugin.openNotificationAlert = null; JPushPlugin.openNotificationAlert = null;
} }
static void transmitReceive(String alert, Map<String, Object> extras) { static void transmitReceive(String alert, Map<String, Object> extras) {
if (instance == null) { if (instance == null) {
return; return;
} }
if(JPushPlugin.shouldCacheMsg){
return;
}
JSONObject data = openNotificationObject(alert, extras); JSONObject data = openNotificationObject(alert, extras);
String js = String String format = "window.plugins.jPushPlugin.receiveNotificationInAndroidCallback(%s);";
.format("window.plugins.jPushPlugin.receiveNotificationInAndroidCallback('%s');", final String js = String.format(format, data.toString());
data.toString()); cordovaActivity.runOnUiThread(new Runnable() {
@Override
try { public void run() {
instance.webView.loadUrl("javascript:" + js);
instance.webView.sendJavascript(js);
} catch (NullPointerException e) {
} catch (Exception e) {
} }
});
JPushPlugin.notificationAlert = null; JPushPlugin.notificationAlert = null;
} }
@Override @Override
@@ -264,7 +248,7 @@ public class JPushPlugin extends CordovaPlugin {
} }
void init(JSONArray data, CallbackContext callbackContext) { void init(JSONArray data, CallbackContext callbackContext) {
JPushInterface.init(this.cordova.getActivity().getApplicationContext()); JPushInterface.init(cordovaActivity.getApplicationContext());
//callbackContext.success(); //callbackContext.success();
} }
@@ -272,34 +256,26 @@ public class JPushPlugin extends CordovaPlugin {
boolean mode; boolean mode;
try { try {
mode = data.getBoolean(0); mode = data.getBoolean(0);
// if (mode.equals("true")) {
// JPushInterface.setDebugMode(true);
// } else if (mode.equals("false")) {
// JPushInterface.setDebugMode(false);
// } else {
// callbackContext.error("error mode");
// }
JPushInterface.setDebugMode(mode); JPushInterface.setDebugMode(mode);
callbackContext.success(); callbackContext.success();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace();
} }
} }
void stopPush(JSONArray data, void stopPush(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){ JPushInterface.stopPush(cordovaActivity.getApplicationContext());
JPushInterface.stopPush(this.cordova.getActivity().getApplicationContext());
callbackContext.success(); callbackContext.success();
} }
void resumePush(JSONArray data, void resumePush(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){ JPushInterface.resumePush(cordovaActivity.getApplicationContext());
JPushInterface.resumePush(this.cordova.getActivity().getApplicationContext());
callbackContext.success(); callbackContext.success();
} }
void isPushStopped(JSONArray data, void isPushStopped(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){ boolean isStopped = JPushInterface.isPushStopped(
boolean isStopped =JPushInterface.isPushStopped(this.cordova.getActivity().getApplicationContext()); cordovaActivity.getApplicationContext());
if (isStopped) { if (isStopped) {
callbackContext.success(1); callbackContext.success(1);
} else { } else {
@@ -307,8 +283,7 @@ public class JPushPlugin extends CordovaPlugin {
} }
} }
void setLatestNotificationNum(JSONArray data, void setLatestNotificationNum(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){
int num = -1; int num = -1;
try { try {
num = data.getInt(0); num = data.getInt(0);
@@ -317,14 +292,14 @@ public class JPushPlugin extends CordovaPlugin {
callbackContext.error("error reading num json"); callbackContext.error("error reading num json");
} }
if (num != -1) { if (num != -1) {
JPushInterface.setLatestNotificationNumber(this.cordova.getActivity().getApplicationContext(), num); JPushInterface.setLatestNotificationNumber(
cordovaActivity.getApplicationContext(), num);
} else { } else {
callbackContext.error("error num"); callbackContext.error("error num");
} }
} }
void setPushTime(JSONArray data, void setPushTime(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){
Set<Integer> days = new HashSet<Integer>(); Set<Integer> days = new HashSet<Integer>();
JSONArray dayArray; JSONArray dayArray;
int startHour = -1; int startHour = -1;
@@ -344,43 +319,44 @@ public class JPushPlugin extends CordovaPlugin {
} catch (JSONException e) { } catch (JSONException e) {
callbackContext.error("error reading hour json"); callbackContext.error("error reading hour json");
} }
JPushInterface.setPushTime(this.cordova.getActivity().getApplicationContext(), days, startHour, endHour); Context context = cordovaActivity.getApplicationContext();
JPushInterface.setPushTime(context, days, startHour, endHour);
callbackContext.success(); callbackContext.success();
} }
void getRegistrationID(JSONArray data, CallbackContext callbackContext) { void getRegistrationID(JSONArray data, CallbackContext callbackContext) {
String regID= JPushInterface.getRegistrationID(this.cordova.getActivity().getApplicationContext()); Context context = cordovaActivity.getApplicationContext();
String regID = JPushInterface.getRegistrationID(context);
callbackContext.success(regID); callbackContext.success(regID);
}
}
void onResume(JSONArray data, CallbackContext callbackContext) { void onResume(JSONArray data, CallbackContext callbackContext) {
JPushInterface.onResume(this.cordova.getActivity()); JPushInterface.onResume(cordovaActivity);
} }
void onPause(JSONArray data, CallbackContext callbackContext) { void onPause(JSONArray data, CallbackContext callbackContext) {
JPushInterface.onPause(this.cordova.getActivity()); JPushInterface.onPause(cordovaActivity);
} }
void reportNotificationOpened(JSONArray data, CallbackContext callbackContext) { void reportNotificationOpened(JSONArray data, CallbackContext callbackContext) {
try { try {
String msgID; String msgID;
msgID = data.getString(0); msgID = data.getString(0);
JPushInterface.reportNotificationOpened(this.cordova.getActivity(),msgID); JPushInterface.reportNotificationOpened(cordovaActivity, msgID);
} catch (JSONException e) { } catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
void setTags(JSONArray data, CallbackContext callbackContext) {
void setTags(JSONArray data, CallbackContext callbackContext) {
try { try {
HashSet<String> tags = new HashSet<String>(); HashSet<String> tags = new HashSet<String>();
for (int i = 0; i < data.length(); i++) { for (int i = 0; i < data.length(); i++) {
tags.add(data.getString(i)); tags.add(data.getString(i));
} }
JPushInterface.setTags(this.cordova.getActivity() JPushInterface.setTags(cordovaActivity.getApplicationContext(),
.getApplicationContext(), tags,mTagWithAliasCallback); tags, mTagWithAliasCallback);
callbackContext.success(); callbackContext.success();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
callbackContext.error("Error reading tags JSON"); callbackContext.error("Error reading tags JSON");
@@ -390,8 +366,8 @@ public class JPushPlugin extends CordovaPlugin {
void setAlias(JSONArray data, CallbackContext callbackContext) { void setAlias(JSONArray data, CallbackContext callbackContext) {
try { try {
String alias = data.getString(0); String alias = data.getString(0);
JPushInterface.setAlias(this.cordova.getActivity() JPushInterface.setAlias(cordovaActivity.getApplicationContext(),
.getApplicationContext(), alias,mTagWithAliasCallback); alias, mTagWithAliasCallback);
callbackContext.success(); callbackContext.success();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
@@ -408,9 +384,8 @@ public class JPushPlugin extends CordovaPlugin {
for (int i = 0; i < tagsArray.length(); i++) { for (int i = 0; i < tagsArray.length(); i++) {
tags.add(tagsArray.getString(i)); tags.add(tagsArray.getString(i));
} }
JPushInterface.setAliasAndTags(cordovaActivity.getApplicationContext(),
JPushInterface.setAliasAndTags(this.cordova.getActivity() alias, tags, mTagWithAliasCallback);
.getApplicationContext(), alias, tags,mTagWithAliasCallback);
callbackContext.success(); callbackContext.success();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
@@ -439,7 +414,7 @@ public class JPushPlugin extends CordovaPlugin {
void setBasicPushNotificationBuilder(JSONArray data, void setBasicPushNotificationBuilder(JSONArray data,
CallbackContext callbackContext) { CallbackContext callbackContext) {
BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder( BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(
this.cordova.getActivity()); cordovaActivity);
builder.developerArg0 = "Basic builder 1"; builder.developerArg0 = "Basic builder 1";
JPushInterface.setPushNotificationBuilder(1, builder); JPushInterface.setPushNotificationBuilder(1, builder);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@@ -454,7 +429,7 @@ public class JPushPlugin extends CordovaPlugin {
void setCustomPushNotificationBuilder(JSONArray data, void setCustomPushNotificationBuilder(JSONArray data,
CallbackContext callbackContext) { CallbackContext callbackContext) {
CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder( CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(
this.cordova.getActivity(), R.layout.test_notification_layout, cordovaActivity, R.layout.test_notification_layout,
R.id.icon, R.id.title, R.id.text); R.id.icon, R.id.title, R.id.text);
builder.developerArg0 = "Custom Builder 1"; builder.developerArg0 = "Custom Builder 1";
builder.layoutIconDrawable = R.drawable.jpush_notification_icon; builder.layoutIconDrawable = R.drawable.jpush_notification_icon;
@@ -468,14 +443,12 @@ public class JPushPlugin extends CordovaPlugin {
//callbackContext.success(obj); //callbackContext.success(obj);
} }
void clearAllNotification(JSONArray data, void clearAllNotification(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){ JPushInterface.clearAllNotifications(cordovaActivity);
JPushInterface.clearAllNotifications(this.cordova.getActivity());
//callbackContext.success(); //callbackContext.success();
} }
void clearNotificationById(JSONArray data, void clearNotificationById(JSONArray data, CallbackContext callbackContext) {
CallbackContext callbackContext){
int notificationId = -1; int notificationId = -1;
try { try {
notificationId = data.getInt(0); notificationId = data.getInt(0);
@@ -484,15 +457,15 @@ public class JPushPlugin extends CordovaPlugin {
callbackContext.error("error reading id json"); callbackContext.error("error reading id json");
} }
if (notificationId != -1) { if (notificationId != -1) {
JPushInterface.clearNotificationById(this.cordova.getActivity(), notificationId); JPushInterface.clearNotificationById(cordovaActivity, notificationId);
} else { } else {
callbackContext.error("error id"); callbackContext.error("error id");
} }
} }
void addLocalNotification(JSONArray data,
CallbackContext callbackContext) throws JSONException{
//builderId,content,title,notificaitonID,broadcastTime,extras
void addLocalNotification(JSONArray data, CallbackContext callbackContext)
throws JSONException {
//builderId,content,title,notificaitonID,broadcastTime,extras
int builderId = data.getInt(0); int builderId = data.getInt(0);
String content = data.getString(1); String content = data.getString(1);
String title = data.getString(2); String title = data.getString(2);
@@ -508,51 +481,56 @@ public class JPushPlugin extends CordovaPlugin {
ln.setBroadcastTime(System.currentTimeMillis() + broadcastTime); ln.setBroadcastTime(System.currentTimeMillis() + broadcastTime);
ln.setExtras(extras.toString()); ln.setExtras(extras.toString());
JPushInterface.addLocalNotification(this.cordova.getActivity(), ln); JPushInterface.addLocalNotification(cordovaActivity, ln);
} }
void removeLocalNotification(JSONArray data,
CallbackContext callbackContext) throws JSONException{
void removeLocalNotification(JSONArray data, CallbackContext callbackContext)
throws JSONException {
int notificationID = data.getInt(0); int notificationID = data.getInt(0);
JPushInterface.removeLocalNotification(this.cordova.getActivity(),notificationID); JPushInterface.removeLocalNotification(cordovaActivity, notificationID);
} }
void clearLocalNotifications(JSONArray data,
CallbackContext callbackContext){
JPushInterface.clearLocalNotifications(this.cordova.getActivity()); void clearLocalNotifications(JSONArray data, CallbackContext callbackContext) {
JPushInterface.clearLocalNotifications(cordovaActivity);
}
/**
* 决定是否启用统计分析功能。
* @param data
* @param callbackContext
*/
void setStatisticsOpen(JSONArray data, CallbackContext callbackContext) {
try {
isStatisticsOpened = data.getBoolean(0);
} catch (JSONException e) {
e.printStackTrace();
}
} }
private final TagAliasCallback mTagWithAliasCallback = new TagAliasCallback() { private final TagAliasCallback mTagWithAliasCallback = new TagAliasCallback() {
@Override @Override
public void gotResult(int code, String alias, Set<String> tags) { public void gotResult(int code, String alias, Set<String> tags) {
if (instance == null) { if (instance == null) {
return; return;
} }
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
try { try {
data.put("resultCode", code); data.put("resultCode", code);
data.put("tags", tags); data.put("tags", tags);
data.put("alias", alias); data.put("alias", alias);
final String jsEvent = String.format(
String jsEvent=String "cordova.fireDocumentEvent('jpush.setTagsWithAlias',%s)",
.format("cordova.fireDocumentEvent('jpush.setTagsWithAlias',%s)",
data.toString()); data.toString());
instance.webView.sendJavascript(jsEvent); cordovaActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
instance.webView.loadUrl("javascript:" + jsEvent);
}
});
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace();
} }
} }
}; };
} }
+27 -27
View File
@@ -13,69 +13,70 @@ import android.util.Log;
public class MyReceiver extends BroadcastReceiver { public class MyReceiver extends BroadcastReceiver {
private static String TAG = "JPushPlugin"; private static String TAG = "JPushPlugin";
private static final List<String> IGNORED_EXTRAS_KEYS =
Arrays.asList(
"cn.jpush.android.TITLE",
"cn.jpush.android.MESSAGE",
"cn.jpush.android.APPKEY",
"cn.jpush.android.NOTIFICATION_CONTENT_TITLE"
);
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(action)) {
// }else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())){
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
handlingReceivedMessage(intent); handlingReceivedMessage(intent);
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(action)) {
handlingNotificationReceive(context, intent); handlingNotificationReceive(context, intent);
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(action)) {
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
handlingNotificationOpen(context, intent); handlingNotificationOpen(context, intent);
} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
} else { } else {
Log.d(TAG, "Unhandled intent - " + intent.getAction()); Log.d(TAG, "Unhandled intent - " + action);
}
} }
}
private void handlingReceivedMessage(Intent intent) { private void handlingReceivedMessage(Intent intent) {
String msg = intent.getStringExtra(JPushInterface.EXTRA_MESSAGE); String msg = intent.getStringExtra(JPushInterface.EXTRA_MESSAGE);
Map<String, Object> extras = getNotificationExtras(intent); Map<String, Object> extras = getNotificationExtras(intent);
JPushPlugin.transmitPush(msg, extras); JPushPlugin.transmitPush(msg, extras);
} }
private void handlingNotificationOpen(Context context, Intent intent) { private void handlingNotificationOpen(Context context, Intent intent) {
Log.i(TAG, "---------------- handlingNotificationOpen"); Log.i(TAG, "---------------- handlingNotificationOpen");
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT); String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
Map<String,Object> extras = getNotificationExtras(intent);
Intent launch = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
launch.addCategory(Intent.CATEGORY_LAUNCHER);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
JPushPlugin.openNotificationAlert = alert; JPushPlugin.openNotificationAlert = alert;
Map<String, Object> extras = getNotificationExtras(intent);
JPushPlugin.openNotificationExtras = extras; JPushPlugin.openNotificationExtras = extras;
JPushPlugin.transmitOpen(alert, extras); JPushPlugin.transmitOpen(alert, extras);
Intent launch = context.getPackageManager().getLaunchIntentForPackage(
context.getPackageName());
launch.addCategory(Intent.CATEGORY_LAUNCHER);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(launch); context.startActivity(launch);
} }
private void handlingNotificationReceive(Context context, Intent intent) { private void handlingNotificationReceive(Context context, Intent intent) {
Log.i(TAG, "---------------- handlingNotificationReceive"); Log.i(TAG, "---------------- handlingNotificationReceive");
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
Map<String,Object> extras = getNotificationExtras(intent);
Intent launch = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); Intent launch = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
launch.addCategory(Intent.CATEGORY_LAUNCHER); launch.addCategory(Intent.CATEGORY_LAUNCHER);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
JPushPlugin.notificationAlert = alert; JPushPlugin.notificationAlert = alert;
Map<String, Object> extras = getNotificationExtras(intent);
JPushPlugin.notificationExtras = extras; JPushPlugin.notificationExtras = extras;
JPushPlugin.transmitReceive(alert, extras); JPushPlugin.transmitReceive(alert, extras);
} }
private Map<String, Object> getNotificationExtras(Intent intent) { private Map<String, Object> getNotificationExtras(Intent intent) {
Map<String, Object> extrasMap = new HashMap<String, Object>(); Map<String, Object> extrasMap = new HashMap<String, Object>();
for (String key : intent.getExtras().keySet()) { for (String key : intent.getExtras().keySet()) {
if (!IGNORED_EXTRAS_KEYS.contains(key)) { if (!IGNORED_EXTRAS_KEYS.contains(key)) {
Log.e("key", "key:" + key); Log.e("key", "key:" + key);
@@ -88,6 +89,5 @@ public class MyReceiver extends BroadcastReceiver {
} }
return extrasMap; return extrasMap;
} }
private static final List<String> IGNORED_EXTRAS_KEYS =
Arrays.asList("cn.jpush.android.TITLE","cn.jpush.android.MESSAGE","cn.jpush.android.APPKEY","cn.jpush.android.NOTIFICATION_CONTENT_TITLE");
} }
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-2
View File
@@ -10,6 +10,4 @@
@interface AppDelegate (JPush) @interface AppDelegate (JPush)
//@property(nonatomic,strong)NSDictionary *luanchOption;
@end @end
+5 -32
View File
@@ -7,26 +7,21 @@
// //
#import "AppDelegate+JPush.h" #import "AppDelegate+JPush.h"
#import <objc/runtime.h>
#import "JPushPlugin.h" #import "JPushPlugin.h"
#import "JPUSHService.h" #import "JPUSHService.h"
#import <objc/runtime.h>
//static char launchNotificationKey;
@implementation AppDelegate (JPush) @implementation AppDelegate (JPush)
+(void)load{ +(void)load{
Method origin; Method origin;
Method swizzle; Method swizzle;
origin=class_getInstanceMethod([self class],@selector(init)); origin=class_getInstanceMethod([self class],@selector(init));
swizzle=class_getInstanceMethod([self class], @selector(init_plus)); swizzle=class_getInstanceMethod([self class], @selector(init_plus));
method_exchangeImplementations(origin, swizzle); method_exchangeImplementations(origin, swizzle);
} }
-(instancetype)init_plus{ -(instancetype)init_plus{
[[NSNotificationCenter defaultCenter] addObserver:self [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidLaunch:) selector:@selector(applicationDidLaunch:)
name:@"UIApplicationDidFinishLaunchingNotification" name:@"UIApplicationDidFinishLaunchingNotification"
@@ -35,59 +30,37 @@
} }
-(void)applicationDidLaunch:(NSNotification*)notification{ -(void)applicationDidLaunch:(NSNotification*)notification{
if (notification) { if (notification) {
[JPushPlugin setLaunchOptions:notification.userInfo]; [JPushPlugin setLaunchOptions:notification.userInfo];
} }
} }
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[JPUSHService registerDeviceToken:deviceToken]; [JPUSHService registerDeviceToken:deviceToken];
} }
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
[JPUSHService handleRemoteNotification:userInfo]; [JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification [[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification object:userInfo];
object:userInfo];
} }
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{ -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
[JPUSHService handleRemoteNotification:userInfo]; [JPUSHService handleRemoteNotification:userInfo];
[[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification [[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification object:userInfo];
object:userInfo];
completionHandler(UIBackgroundFetchResultNewData); completionHandler(UIBackgroundFetchResultNewData);
} }
- (void)application:(UIApplication *)application - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
didReceiveLocalNotification:(UILocalNotification *)notification {
[JPUSHService showLocalNotificationAtFront:notification identifierKey:nil]; [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
} }
- (void)applicationWillEnterForeground:(UIApplication *)application { - (void)applicationWillEnterForeground:(UIApplication *)application {
// [application setApplicationIconBadgeNumber:0]; // [application setApplicationIconBadgeNumber:0];
// [application cancelAllLocalNotifications]; // [application cancelAllLocalNotifications];
} }
- (void)applicationDidEnterBackground:(UIApplication *)application { - (void)applicationDidEnterBackground:(UIApplication *)application {
// [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
} }
//delegate里不能声明变量,所以采用关联对象这种技术绕过这个限制
//-(NSDictionary *)luanchOption{
// return objc_getAssociatedObject(self, &launchNotificationKey);
//}
//-(void)setLuanchOption:(NSDictionary *)luanchOption{
// objc_setAssociatedObject(self, &launchNotificationKey, luanchOption, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//}
//-(void)dealloc{
// self.luanchOption=nil;
//}
@end @end
+35 -4
View File
@@ -15,24 +15,55 @@
} }
+(void)setLaunchOptions:(NSDictionary *)theLaunchOptions; +(void)setLaunchOptions:(NSDictionary *)theLaunchOptions;
//以下为js中可调用接口
//设置标签、别名
-(void)setTagsWithAlias:(CDVInvokedUrlCommand*)command; -(void)setTagsWithAlias:(CDVInvokedUrlCommand*)command;
-(void)setTags:(CDVInvokedUrlCommand*)command; -(void)setTags:(CDVInvokedUrlCommand*)command;
-(void)setAlias:(CDVInvokedUrlCommand*)command; -(void)setAlias:(CDVInvokedUrlCommand*)command;
//获取 RegistrationID
-(void)getRegistrationID:(CDVInvokedUrlCommand*)command; -(void)getRegistrationID:(CDVInvokedUrlCommand*)command;
//页面统计
-(void)startLogPageView:(CDVInvokedUrlCommand*)command; -(void)startLogPageView:(CDVInvokedUrlCommand*)command;
-(void)stopLogPageView:(CDVInvokedUrlCommand*)command; -(void)stopLogPageView:(CDVInvokedUrlCommand*)command;
-(void)beginLogPageView:(CDVInvokedUrlCommand*)command;
// 设置角标到服务器, 服务器下一次发消息时会设置成这个值 //设置角标到服务器,服务器下一次发消息时,会设置成这个值
//本接口不会改变应用本地的角标值. //本接口不会改变应用本地的角标值.
-(void)setBadge:(CDVInvokedUrlCommand*)command; -(void)setBadge:(CDVInvokedUrlCommand*)command;
//相当于 [setBadge:0] //相当于 [setBadge:0]
-(void)resetBadge:(CDVInvokedUrlCommand*)command; -(void)resetBadge:(CDVInvokedUrlCommand*)command;
//应用本地的角标值设置/获取
//改变应用本地的角标值.
-(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command; -(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command;
//获取应用本地的角标值.
-(void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command; -(void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand*)command;
//停止与恢复推送
-(void)stopPush:(CDVInvokedUrlCommand*)command;
-(void)resumePush:(CDVInvokedUrlCommand*)command;
-(void)isPushStopped:(CDVInvokedUrlCommand*)command;
//开关日志
-(void)setDebugModeFromIos:(CDVInvokedUrlCommand*)command;
-(void)setLogOFF:(CDVInvokedUrlCommand*)command;
-(void)crashLogON:(CDVInvokedUrlCommand*)command;
//本地推送
-(void)setLocalNotification:(CDVInvokedUrlCommand*)command;
-(void)deleteLocalNotificationWithIdentifierKey:(CDVInvokedUrlCommand*)command;
-(void)clearAllLocalNotifications:(CDVInvokedUrlCommand*)command;
//地理位置上报 [latitude,longitude]
-(void)setLocation:(CDVInvokedUrlCommand*)command;
/*
* 以下为js中可监听到的事件
* jpush.openNotification 点击推送消息唤醒或启动app
* jpush.setTagsWithAlias 设置标签、别名完成
* jpush.receiveMessage 收到自定义消息
* jpush.receiveNotification 前台收到推送消息
*/
@end @end
+109 -186
View File
@@ -10,69 +10,24 @@
#import "JPUSHService.h" #import "JPUSHService.h"
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
static NSString *const JM_APP_KEY = @"APP_KEY"; static NSString *const JM_APP_KEY = @"APP_KEY";
static NSString *const JM_APP_CHANNEL = @"CHANNEL"; static NSString *const JM_APP_CHANNEL = @"CHANNEL";
static NSString *const JM_APP_ISPRODUCTION = @"IsProduction"; static NSString *const JM_APP_ISPRODUCTION = @"IsProduction";
static NSString *const JPushConfigFileName = @"PushConfig";
static NSString *const JMessageConfigFileName = @"PushConfig";
static NSDictionary *_luanchOptions = nil; static NSDictionary *_luanchOptions = nil;
@implementation JPushPlugin @implementation JPushPlugin
#pragma mark- 外部接口
+(void)setLaunchOptions:(NSDictionary *)theLaunchOptions{
_luanchOptions=theLaunchOptions;
[JPUSHService setDebugMode];
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//可以添加自定义categories
[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert)
categories:nil];
} else {
//categories 必须为nil
[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
}
//read appkey and channel from JMessageConfig.plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:JMessageConfigFileName ofType:@"plist"];
if (plistPath == nil) {
NSLog(@"error: PushConfig.plist not found");
assert(0);
}
NSMutableDictionary *plistData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSString * appkey = [plistData valueForKey:JM_APP_KEY];
NSString * channel = [plistData valueForKey:JM_APP_CHANNEL];
NSNumber * isProduction = [plistData valueForKey:JM_APP_ISPRODUCTION];
if (!appkey || appkey.length == 0) {
NSLog(@"error: app key not found in JMessageConfig.plist ");
assert(0);
}
[JPUSHService setupWithOption:_luanchOptions appKey:appkey
channel:channel apsForProduction:[isProduction boolValue] ];
}
-(void)stopPush:(CDVInvokedUrlCommand*)command{ -(void)stopPush:(CDVInvokedUrlCommand*)command{
[[UIApplication sharedApplication]unregisterForRemoteNotifications]; [[UIApplication sharedApplication]unregisterForRemoteNotifications];
} }
-(void)resumePush:(CDVInvokedUrlCommand*)command{ -(void)resumePush:(CDVInvokedUrlCommand*)command{
[JPushPlugin registerForRemoteNotification];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1 +(void)registerForRemoteNotification{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//可以添加自定义categories //可以添加自定义categories
[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
@@ -86,40 +41,23 @@ static NSDictionary *_luanchOptions=nil;
UIRemoteNotificationTypeAlert) UIRemoteNotificationTypeAlert)
categories:nil]; categories:nil];
} }
#else
//categories 必须为nil
[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
#endif
} }
-(void)isPushStopped:(CDVInvokedUrlCommand*)command{ -(void)isPushStopped:(CDVInvokedUrlCommand*)command{
NSNumber *result; NSNumber *result;
if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) { if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
result = @(0); result = @(0);
}else{ }else{
result = @(1); result = @(1);
} }
CDVPluginResult * pushResult=[self pluginResultForValue:result]; [self hanleResultWithValue:result command:command];
if (pushResult) {
[self succeedWithPluginResult:pushResult withCallbackID:command.callbackId];
} else {
[self failWithCallbackID:command.callbackId];
} }
}
-(void)initial:(CDVInvokedUrlCommand*)command{ -(void)initial:(CDVInvokedUrlCommand*)command{
//do nithng,because Cordova plugin use lazy load mode. //do nithng,because Cordova plugin use lazy load mode.
} }
#ifdef __CORDOVA_4_0_0 #ifdef __CORDOVA_4_0_0
- (void)pluginInitialize { - (void)pluginInitialize {
@@ -133,7 +71,6 @@ static NSDictionary *_luanchOptions=nil;
NSLog(@"### initWithWebView "); NSLog(@"### initWithWebView ");
if (self=[super initWithWebView:theWebView]) { if (self=[super initWithWebView:theWebView]) {
[self initNotifications]; [self initNotifications];
} }
return self; return self;
} }
@@ -141,10 +78,7 @@ static NSDictionary *_luanchOptions=nil;
#endif #endif
-(void)initNotifications { -(void)initNotifications {
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self [defaultCenter addObserver:self
selector:@selector(networkDidReceiveMessage:) selector:@selector(networkDidReceiveMessage:)
@@ -164,7 +98,6 @@ static NSDictionary *_luanchOptions=nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) { if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.openNotification',%@)",jsonString]]; [self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.openNotification',%@)",jsonString]];
}); });
@@ -175,95 +108,51 @@ static NSDictionary *_luanchOptions=nil;
} }
} }
-(void)setTagsWithAlias:(CDVInvokedUrlCommand*)command{ -(void)setTagsWithAlias:(CDVInvokedUrlCommand*)command{
NSArray *arguments = command.arguments; NSArray *arguments = command.arguments;
NSString *alias;
NSArray *tags;
if (!arguments || [arguments count] < 2) { if (!arguments || [arguments count] < 2) {
NSLog(@"#### setTagsWithAlias param is less"); NSLog(@"#### setTagsWithAlias param is less");
return ; return ;
}else{
alias = arguments[0];
tags = arguments[1];
} }
NSString *alias=[arguments objectAtIndex:0];
NSArray *arrayTags=[arguments objectAtIndex:1];
NSLog(@"#### setTagsWithAlias alias is %@, tags is %@",alias,arrayTags); NSLog(@"#### setTagsWithAlias alias is %@, tags is %@",alias,tags);
NSSet* set=[NSSet setWithArray:arrayTags]; [JPUSHService setTags:[NSSet setWithArray:tags]
[JPUSHService setTags:set
alias:alias alias:alias
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:) callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self]; object:self];
} }
-(void)setTags:(CDVInvokedUrlCommand *)command{ -(void)setTags:(CDVInvokedUrlCommand *)command{
NSArray *tags = command.arguments;
NSArray *arguments=[command arguments];
NSString *tags=[arguments objectAtIndex:0];
NSLog(@"#### setTags %@",tags); NSLog(@"#### setTags %@",tags);
NSArray *array=[tags componentsSeparatedByString:@","]; [JPUSHService setTags:[NSSet setWithArray:tags]
[JPUSHService setTags:[NSSet setWithArray:array]
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:) callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self]; object:self];
} }
-(void)setAlias:(CDVInvokedUrlCommand *)command{ -(void)setAlias:(CDVInvokedUrlCommand *)command{
NSArray *arguments=[command arguments]; NSLog(@"#### setAlias %@",command.arguments);
NSLog(@"#### setAlias %@",arguments); [JPUSHService setAlias:command.arguments[0]
[JPUSHService setAlias:[arguments objectAtIndex:0]
callbackSelector:@selector(tagsWithAliasCallback:tags:alias:) callbackSelector:@selector(tagsWithAliasCallback:tags:alias:)
object:self]; object:self];
} }
-(void)getRegistrationID:(CDVInvokedUrlCommand*)command{ -(void)getRegistrationID:(CDVInvokedUrlCommand*)command{
NSString* registrationID = [JPUSHService registrationID]; NSString* registrationID = [JPUSHService registrationID];
NSLog(@"### getRegistrationID %@",registrationID); NSLog(@"### getRegistrationID %@",registrationID);
[self hanleResultWithValue:registrationID command:command];
CDVPluginResult *result=[self pluginResultForValue:registrationID];
if (result) {
[self succeedWithPluginResult:result withCallbackID:command.callbackId];
} else {
[self failWithCallbackID:command.callbackId];
} }
}
-(void)tagsWithAliasCallback:(int)resultCode tags:(NSSet *)tags alias:(NSString *)alias{
NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:resultCode],@"resultCode",
tags==nil?[NSNull null]:[tags allObjects],@"tags",
alias==nil?[NSNull null]:alias,@"alias",nil];
NSMutableDictionary *data = [NSMutableDictionary dictionary];
[data setObject:[NSNumber numberWithInt:resultCode] forKey:@"resultCode"];
[data setObject:tags==nil?[NSNull null]:[tags allObjects] forKey:@"tags"];
[data setObject:alias==nil?[NSNull null]:alias forKey:@"alias"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.setTagsWithAlias',%@)",jsonString]];
// [self writeJavascript:[NSString stringWithFormat:@"window.plugins.jPushPlugin.pushCallback('%@')",jsonString]];
});
}
-(void)startLogPageView:(CDVInvokedUrlCommand*)command{ -(void)startLogPageView:(CDVInvokedUrlCommand*)command{
NSArray *arguments = command.arguments; NSArray *arguments = command.arguments;
@@ -271,60 +160,52 @@ static NSDictionary *_luanchOptions=nil;
NSLog(@"startLogPageView argument error"); NSLog(@"startLogPageView argument error");
return ; return ;
} }
NSString * pageName=[arguments objectAtIndex:0]; NSString * pageName = arguments[0];
if (pageName) { if (pageName) {
[JPUSHService startLogPageView:pageName]; [JPUSHService startLogPageView:pageName];
} }
} }
-(void)stopLogPageView:(CDVInvokedUrlCommand*)command{ -(void)stopLogPageView:(CDVInvokedUrlCommand*)command{
NSArray *arguments = command.arguments; NSArray *arguments = command.arguments;
if (!arguments || [arguments count] < 1) { if (!arguments || [arguments count] < 1) {
NSLog(@"stopLogPageView argument error"); NSLog(@"stopLogPageView argument error");
return ; return ;
} }
NSString * pageName=[arguments objectAtIndex:0]; NSString * pageName = arguments[0];
if (pageName) { if (pageName) {
[JPUSHService stopLogPageView:pageName]; [JPUSHService stopLogPageView:pageName];
} }
} }
-(void)beginLogPageView:(CDVInvokedUrlCommand*)command{ -(void)beginLogPageView:(CDVInvokedUrlCommand*)command{
NSArray *arguments = command.arguments; NSArray *arguments = command.arguments;
if (!arguments || [arguments count] < 2) { if (!arguments || [arguments count] < 2) {
NSLog(@"beginLogPageView argument error"); NSLog(@"beginLogPageView argument error");
return ; return ;
} }
NSString * pageName=[arguments objectAtIndex:0]; NSString * pageName = arguments[0];
int duration=[[arguments objectAtIndex:0]intValue]; int duration = [arguments[0] intValue];
if (pageName) { if (pageName) {
[JPUSHService beginLogPageView:pageName duration:duration]; [JPUSHService beginLogPageView:pageName duration:duration];
} }
} }
-(void)setBadge:(CDVInvokedUrlCommand*)command{ -(void)setBadge:(CDVInvokedUrlCommand*)command{
NSArray *argument = command.arguments; NSArray *argument = command.arguments;
if ([argument count] < 1) { if ([argument count] < 1) {
NSLog(@"setBadge argument error!"); NSLog(@"setBadge argument error!");
return; return;
} }
NSNumber *badge=[argument objectAtIndex:0]; NSNumber *badge = argument[0];
[JPUSHService setBadge:[badge intValue]]; [JPUSHService setBadge:[badge intValue]];
} }
-(void)resetBadge:(CDVInvokedUrlCommand*)command{ -(void)resetBadge:(CDVInvokedUrlCommand*)command{
[JPUSHService resetBadge]; [JPUSHService resetBadge];
} }
-(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command{ -(void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command{
// //
NSArray *argument = command.arguments; NSArray *argument = command.arguments;
@@ -336,74 +217,119 @@ static NSDictionary *_luanchOptions=nil;
[UIApplication sharedApplication].applicationIconBadgeNumber = [badge intValue]; [UIApplication sharedApplication].applicationIconBadgeNumber = [badge intValue];
} }
-(void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command { -(void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command {
NSInteger num = [UIApplication sharedApplication].applicationIconBadgeNumber; NSInteger num = [UIApplication sharedApplication].applicationIconBadgeNumber;
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:num]; NSNumber *number = [NSNumber numberWithInteger:num];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId]; [self hanleResultWithValue:number command:command];
} }
-(void)setDebugModeFromIos:(CDVInvokedUrlCommand*)command{ -(void)setDebugModeFromIos:(CDVInvokedUrlCommand*)command{
[JPUSHService setDebugMode]; [JPUSHService setDebugMode];
} }
-(void)setLogOFF:(CDVInvokedUrlCommand*)command{ -(void)setLogOFF:(CDVInvokedUrlCommand*)command{
[JPUSHService setLogOFF]; [JPUSHService setLogOFF];
} }
-(void)crashLogON:(CDVInvokedUrlCommand*)command{
[JPUSHService crashLogON];
- (void)failWithCallbackID:(NSString *)callbackID {
CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
[self.commandDelegate sendPluginResult:result callbackId:callbackID];
} }
-(void)setLocalNotification:(CDVInvokedUrlCommand*)command{
NSArray *arguments = command.arguments;
- (void)succeedWithPluginResult:(CDVPluginResult *)result withCallbackID:(NSString *)callbackID { NSDate *date = arguments[0] == [NSNull null] ? nil : [NSDate dateWithTimeIntervalSinceNow:[((NSString*)arguments[0]) intValue]];
[self.commandDelegate sendPluginResult:result callbackId:callbackID]; NSString *alertBody = arguments[1] == [NSNull null] ? nil : (NSString*)arguments[1];
int badge = arguments[2] == [NSNull null] ? 0 : [(NSString*)arguments[2] intValue];
NSString *idKey = arguments[3] == [NSNull null] ? nil : (NSString*)arguments[3];
NSDictionary *dict = arguments[4] == [NSNull null] ? nil : (NSDictionary*)arguments[4];
[JPUSHService setLocalNotification:date alertBody:alertBody badge:badge alertAction:nil identifierKey:idKey userInfo:dict soundName:nil];
} }
-(void)deleteLocalNotificationWithIdentifierKey:(CDVInvokedUrlCommand*)command{
[JPUSHService deleteLocalNotificationWithIdentifierKey:(NSString*)command.arguments[0]];
}
-(void)clearAllLocalNotifications:(CDVInvokedUrlCommand*)command{
[JPUSHService clearAllLocalNotifications];
}
-(void)setLocation:(CDVInvokedUrlCommand*)command{
[JPUSHService setLatitude:[((NSString*)command.arguments[0]) doubleValue] longitude:[((NSString*)command.arguments[1]) doubleValue]];
}
- (CDVPluginResult *)pluginResultForValue:(id)value { #pragma mark- 内部方法
+(void)setLaunchOptions:(NSDictionary *)theLaunchOptions{
_luanchOptions = theLaunchOptions;
[JPUSHService setDebugMode];
[JPushPlugin registerForRemoteNotification];
//read appkey and channel from PushConfig.plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:JPushConfigFileName ofType:@"plist"];
if (plistPath == nil) {
NSLog(@"error: PushConfig.plist not found");
assert(0);
}
NSMutableDictionary *plistData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSString * appkey = [plistData valueForKey:JM_APP_KEY];
NSString * channel = [plistData valueForKey:JM_APP_CHANNEL];
NSNumber * isProduction = [plistData valueForKey:JM_APP_ISPRODUCTION];
if (!appkey || appkey.length == 0) {
NSLog(@"error: app key not found in PushConfig.plist ");
assert(0);
}
[JPUSHService setupWithOption:_luanchOptions appKey:appkey
channel:channel apsForProduction:[isProduction boolValue] ];
}
#pragma mark 将参数返回给js
-(void)hanleResultWithValue:(id)value command:(CDVInvokedUrlCommand*)command{
CDVPluginResult *result = nil;
CDVCommandStatus status = CDVCommandStatus_OK;
CDVPluginResult *result;
if ([value isKindOfClass:[NSString class]]) { if ([value isKindOfClass:[NSString class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK value = [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
messageAsString:[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
} else if ([value isKindOfClass:[NSNumber class]]) {
CFNumberType numberType = CFNumberGetType((CFNumberRef)value);
//note: underlyingly, BOOL values are typedefed as char
if (numberType == kCFNumberIntType || numberType == kCFNumberCharType) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:[value intValue]];
} else {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:[value doubleValue]];
}
} else if ([value isKindOfClass:[NSArray class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:value];
} else if ([value isKindOfClass:[NSDictionary class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:value];
} else if ([value isKindOfClass:[NSNull class]]) { } else if ([value isKindOfClass:[NSNull class]]) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; value = nil;
}
if ([value isKindOfClass:[NSObject class]]) {
result = [CDVPluginResult resultWithStatus:status messageAsString:value];//NSObject 类型都可以
} else { } else {
NSLog(@"Cordova callback block returned unrecognized type: %@", NSStringFromClass([value class])); NSLog(@"Cordova callback block returned unrecognized type: %@", NSStringFromClass([value class]));
return nil; result = nil;
}
return result;
} }
if (!result) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
#pragma mark 设置标签及别名回调
-(void)tagsWithAliasCallback:(int)resultCode tags:(NSSet *)tags alias:(NSString *)alias{
NSDictionary *dict = @{@"resultCode":[NSNumber numberWithInt:resultCode],
@"tags" :tags == nil ? [NSNull null] : [tags allObjects],
@"alias" :alias == nil ? [NSNull null] : alias
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
[self.commandDelegate evalJs:[NSString stringWithFormat:@"cordova.fireDocumentEvent('jpush.setTagsWithAlias',%@)",jsonString]];
});
}
- (void)networkDidReceiveMessage:(NSNotification *)notification { - (void)networkDidReceiveMessage:(NSNotification *)notification {
if (notification) {
NSDictionary *userInfo = [notification userInfo]; NSDictionary *userInfo = [notification userInfo];
//NSLog(@"%@",userInfo); //NSLog(@"%@",userInfo);
@@ -419,12 +345,9 @@ static NSDictionary *_luanchOptions=nil;
[self.commandDelegate evalJs:[NSString stringWithFormat:@"window.plugins.jPushPlugin.receiveMessageIniOSCallback('%@')",jsonString]]; [self.commandDelegate evalJs:[NSString stringWithFormat:@"window.plugins.jPushPlugin.receiveMessageIniOSCallback('%@')",jsonString]];
}); });
} }
}
-(void)networkDidReceiveNotification:(id)notification{ -(void)networkDidReceiveNotification:(id)notification{
@@ -433,6 +356,7 @@ static NSDictionary *_luanchOptions=nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%ld",(long)[UIApplication sharedApplication].applicationState);
switch ([UIApplication sharedApplication].applicationState) { switch ([UIApplication sharedApplication].applicationState) {
case UIApplicationStateActive: case UIApplicationStateActive:
{ {
@@ -457,5 +381,4 @@ static NSDictionary *_luanchOptions=nil;
} }
@end @end
+92 -85
View File
@@ -11,18 +11,22 @@ JPushPlugin.prototype.receiveNotification={}
JPushPlugin.prototype.isPlatformIOS = function() { JPushPlugin.prototype.isPlatformIOS = function() {
return device.platform == "iPhone" || device.platform == "iPad" || device.platform == "iPod touch" || device.platform == "iOS" var isPlatformIOS = device.platform == "iPhone"
|| device.platform == "iPad"
|| device.platform == "iPod touch"
|| device.platform == "iOS";
return isPlatformIOS;
} }
JPushPlugin.prototype.error_callback = function(msg) { JPushPlugin.prototype.error_callback = function(msg) {
console.log("Javascript Callback Error: " + msg) console.log("Javascript Callback Error: " + msg);
} }
JPushPlugin.prototype.call_native = function(name, args, callback) { JPushPlugin.prototype.call_native = function(name, args, callback) {
ret = cordova.exec(callback, this.error_callback, 'JPushPlugin', name, args); ret = cordova.exec(callback, this.error_callback, 'JPushPlugin', name, args);
return ret; return ret;
} }
//public plugin function //public plugin function
JPushPlugin.prototype.startLogPageView = function(pageName) { JPushPlugin.prototype.startLogPageView = function(pageName) {
@@ -42,11 +46,13 @@ JPushPlugin.prototype.beginLogPageView = function(pageName,duration){
this.call_native("beginLogPageView", [pageName, duration], null); this.call_native("beginLogPageView", [pageName, duration], null);
} }
} }
JPushPlugin.prototype.setApplicationIconBadgeNumber = function(badge) { JPushPlugin.prototype.setApplicationIconBadgeNumber = function(badge) {
if(this.isPlatformIOS()) { if(this.isPlatformIOS()) {
this.call_native("setApplicationIconBadgeNumber", [badge], null); this.call_native("setApplicationIconBadgeNumber", [badge], null);
} }
} }
JPushPlugin.prototype.getApplicationIconBadgeNumber = function(callback) { JPushPlugin.prototype.getApplicationIconBadgeNumber = function(callback) {
if(this.isPlatformIOS()) { if(this.isPlatformIOS()) {
this.call_native("getApplicationIconBadgeNumber", [], callback); this.call_native("getApplicationIconBadgeNumber", [], callback);
@@ -66,18 +72,15 @@ JPushPlugin.prototype.setTagsWithAlias = function(tags,alias){
var arrayTagWithAlias = [tags]; var arrayTagWithAlias = [tags];
arrayTagWithAlias.unshift(alias); arrayTagWithAlias.unshift(alias);
this.call_native("setTagsWithAlias", arrayTagWithAlias, null); this.call_native("setTagsWithAlias", arrayTagWithAlias, null);
} } catch(exception) {
catch(exception){
console.log(exception); console.log(exception);
} }
} }
JPushPlugin.prototype.setTags = function(tags){
JPushPlugin.prototype.setTags = function(tags) {
try { try {
this.call_native("setTags", tags, null); this.call_native("setTags", tags, null);
} } catch(exception) {
catch(exception){
console.log(exception); console.log(exception);
} }
} }
@@ -85,146 +88,144 @@ JPushPlugin.prototype.setTags = function(tags){
JPushPlugin.prototype.setAlias = function(alias) { JPushPlugin.prototype.setAlias = function(alias) {
try { try {
this.call_native("setAlias", [alias], null); this.call_native("setAlias", [alias], null);
} } catch(exception) {
catch(exception){
console.log(exception); console.log(exception);
} }
} }
JPushPlugin.prototype.getRegistrationID = function(callback){
JPushPlugin.prototype.getRegistrationID = function(callback) {
try { try {
var data = []; var data = [];
this.call_native("getRegistrationID", [data], callback); this.call_native("getRegistrationID", [data], callback);
} } catch(exception) {
catch(exception){
console.log(exception); console.log(exception);
} }
} }
JPushPlugin.prototype.setBadge = function(value) { JPushPlugin.prototype.setBadge = function(value) {
if(this.isPlatformIOS()) { if(this.isPlatformIOS()) {
try { try {
this.call_native("setBadge", [value], null); this.call_native("setBadge", [value], null);
} } catch(exception) {
catch(exception){
console.log(exception); console.log(exception);
} }
}
}
}
}
JPushPlugin.prototype.resetBadge = function() { JPushPlugin.prototype.resetBadge = function() {
if(this.isPlatformIOS()) { if(this.isPlatformIOS()) {
try { try {
var data = []; var data = [];
this.call_native("resetBadge", [data], null); this.call_native("resetBadge", [data], null);
} } catch(exception) {
catch(exception){
console.log(exception); console.log(exception);
} }
} }
} }
JPushPlugin.prototype.setDebugModeFromIos = function() { JPushPlugin.prototype.setDebugModeFromIos = function() {
if(this.isPlatformIOS()) { if(this.isPlatformIOS()) {
var data = []; var data = [];
this.call_native("setDebugModeFromIos", [data], null); this.call_native("setDebugModeFromIos", [data], null);
} }
} }
JPushPlugin.prototype.setLogOFF = function() { JPushPlugin.prototype.setLogOFF = function() {
if(this.isPlatformIOS()) { if(this.isPlatformIOS()) {
var data = []; var data = [];
this.call_native("setLogOFF", [data], null); this.call_native("setLogOFF", [data], null);
} }
} }
JPushPlugin.prototype.setCrashLogON = function() {
if (this.isPlatformIOS()) {
var data = [];
this.call_native("crashLogON", [data], null);
}
}
JPushPlugin.prototype.addLocalNotificationForIOS = function(delayTime, content,
badge, notificationID, extras) {
if (this.isPlatformIOS()) {
var data = [delayTime, content, badge, notificationID, extras];
this.call_native("setLocalNotification", data, null);
}
}
JPushPlugin.prototype.deleteLocalNotificationWithIdentifierKeyInIOS = function(
identifierKey) {
if (this.isPlatformIOS()) {
var data = [identifierKey];
this.call_native("deleteLocalNotificationWithIdentifierKey", data, null);
}
}
JPushPlugin.prototype.clearAllLocalNotifications = function(){
if (this.isPlatformIOS()) {
var data = [];
this.call_native("clearAllLocalNotifications", data, null);
}
}
JPushPlugin.prototype.setLocation = function(latitude, longitude){
if (this.isPlatformIOS()) {
var data = [latitude, longitude];
this.call_native("setLocation", data, null);
}
}
JPushPlugin.prototype.receiveMessageIniOSCallback = function(data) { JPushPlugin.prototype.receiveMessageIniOSCallback = function(data) {
try { try {
console.log("JPushPlugin:receiveMessageIniOSCallback--data:" + data); console.log("JPushPlugin:receiveMessageIniOSCallback--data:" + data);
var bToObj = JSON.parse(data); var bToObj = JSON.parse(data);
var content = bToObj.content; var content = bToObj.content;
console.log(content); console.log(content);
} } catch(exception) {
catch(exception){
console.log("JPushPlugin:receiveMessageIniOSCallback" + exception); console.log("JPushPlugin:receiveMessageIniOSCallback" + exception);
} }
} }
JPushPlugin.prototype.receiveMessageInAndroidCallback = function(data) { JPushPlugin.prototype.receiveMessageInAndroidCallback = function(data) {
try { try {
console.log("JPushPlugin:receiveMessageInAndroidCallback"); console.log("JPushPlugin:receiveMessageInAndroidCallback");
data = JSON.stringify(data);
var bToObj = JSON.parse(data); var bToObj = JSON.parse(data);
this.receiveMessage = bToObj this.receiveMessage = bToObj
cordova.fireDocumentEvent('jpush.receiveMessage', null); cordova.fireDocumentEvent('jpush.receiveMessage', null);
//console.log(data); } catch(exception) {
//var message = bToObj.message;
//var extras = bToObj.extras;
//console.log(message);
//console.log(extras['cn.jpush.android.MSG_ID']);
//console.log(extras['cn.jpush.android.CONTENT_TYPE']);
//console.log(extras['cn.jpush.android.EXTRA']);
}
catch(exception){
console.log("JPushPlugin:pushCallback " + exception); console.log("JPushPlugin:pushCallback " + exception);
} }
} }
//
JPushPlugin.prototype.openNotificationInAndroidCallback = function(data) { JPushPlugin.prototype.openNotificationInAndroidCallback = function(data) {
try { try {
console.log("JPushPlugin:openNotificationInAndroidCallback"); console.log("JPushPlugin:openNotificationInAndroidCallback");
data = JSON.stringify(data);
var bToObj = JSON.parse(data); var bToObj = JSON.parse(data);
this.openNotification = bToObj; this.openNotification = bToObj;
cordova.fireDocumentEvent('jpush.openNotification', null); cordova.fireDocumentEvent('jpush.openNotification', null);
} catch(exception) {
//console.log(data);
//var bToObj = JSON.parse(data);
//var alert = bToObj.alert;
//var extras = bToObj.extras;
//console.log(alert);
//console.log(extras['cn.jpush.android.MSG_ID']);
//console.log(extras['app']);
//console.log(extras['cn.jpush.android.NOTIFICATION_CONTENT_TITLE']);
//console.log(extras['cn.jpush.android.EXTRA']);
//console.log(extras['cn.jpush.android.PUSH_ID']);
//console.log(extras['cn.jpush.android.NOTIFICATION_ID']);
//console.log("JPushPlugin:openNotificationCallback is ready");
}
catch(exception){
console.log(exception); console.log(exception);
} }
} }
JPushPlugin.prototype.receiveNotificationInAndroidCallback = function(data) { JPushPlugin.prototype.receiveNotificationInAndroidCallback = function(data) {
try{ try{
console.log("JPushPlugin:receiveNotificationInAndroidCallback"); console.log("JPushPlugin:receiveNotificationInAndroidCallback");
data = JSON.stringify(data);
var bToObj = JSON.parse(data); var bToObj = JSON.parse(data);
this.receiveNotification = bToObj; this.receiveNotification = bToObj;
cordova.fireDocumentEvent('jpush.receiveNotification', null); cordova.fireDocumentEvent('jpush.receiveNotification', null);
} catch(exception) {
//console.log(data);
//var bToObj = JSON.parse(data);
//var alert = bToObj.alert;
//var extras = bToObj.extras;
//console.log(alert);
//console.log(extras['cn.jpush.android.MSG_ID']);
//console.log(extras['app']);
//console.log(extras['cn.jpush.android.NOTIFICATION_CONTENT_TITLE']);
//console.log(extras['cn.jpush.android.EXTRA']);
//console.log(extras['cn.jpush.android.PUSH_ID']);
//console.log(extras['cn.jpush.android.NOTIFICATION_ID']);
//console.log("JPushPlugin:openNotificationCallback is ready");
}
catch(exception){
console.log(exception); console.log(exception);
} }
} }
//android single //android single
JPushPlugin.prototype.setBasicPushNotificationBuilder = function() { JPushPlugin.prototype.setBasicPushNotificationBuilder = function() {
if(device.platform == "Android") { if(device.platform == "Android") {
data=[] data = [];
this.call_native("setBasicPushNotificationBuilder", data, null); this.call_native("setBasicPushNotificationBuilder", data, null);
} }
} }
@@ -242,26 +243,27 @@ JPushPlugin.prototype.stopPush = function(){
} }
JPushPlugin.prototype.resumePush = function() { JPushPlugin.prototype.resumePush = function() {
data=[] data = [];
this.call_native("resumePush", data, null); this.call_native("resumePush", data, null);
} }
JPushPlugin.prototype.setDebugMode = function(mode) { JPushPlugin.prototype.setDebugMode = function(mode) {
if(device.platform == "Android") { if(device.platform == "Android") {
this.call_native("setDebugMode", [mode], null); this.call_native("setDebugMode", [mode], null);
} }
} }
//setDebugMode //setDebugMode
JPushPlugin.prototype.clearAllNotification = function() { JPushPlugin.prototype.clearAllNotification = function() {
if(device.platform == "Android") { if(device.platform == "Android") {
data=[] data = [];
this.call_native("clearAllNotification", data, null); this.call_native("clearAllNotification", data, null);
} }
} }
JPushPlugin.prototype.clearNotificationById = function(notificationId) { JPushPlugin.prototype.clearNotificationById = function(notificationId) {
if(device.platform == "Android") { if(device.platform == "Android") {
data=[] data = [];
this.call_native("clearNotificationById", [notificationId], null); this.call_native("clearNotificationById", [notificationId], null);
} }
} }
@@ -273,10 +275,8 @@ JPushPlugin.prototype.setLatestNotificationNum = function(num){
} }
JPushPlugin.prototype.isPushStopped = function(callback) { JPushPlugin.prototype.isPushStopped = function(callback) {
data = []; data = [];
this.call_native("isPushStopped",data,callback) this.call_native("isPushStopped", data, callback);
} }
JPushPlugin.prototype.init = function() { JPushPlugin.prototype.init = function() {
@@ -286,9 +286,7 @@ JPushPlugin.prototype.init = function(){
} else { } else {
data = []; data = [];
this.call_native("init", data, null); this.call_native("init", data, null);
} }
} }
JPushPlugin.prototype.setDebugMode = function(mode) { JPushPlugin.prototype.setDebugMode = function(mode) {
@@ -296,33 +294,45 @@ JPushPlugin.prototype.setDebugMode = function(mode){
this.call_native("setDebugMode", [mode], null); this.call_native("setDebugMode", [mode], null);
} }
} }
JPushPlugin.prototype.addLocalNotification = function(builderId,content,title,notificaitonID,broadcastTime,extras){
JPushPlugin.prototype.addLocalNotification = function(builderId, content, title,
notificaitonID, broadcastTime, extras) {
if(device.platform == "Android") { if(device.platform == "Android") {
data = [builderId, content, title, notificaitonID, broadcastTime, extras]; data = [builderId, content, title, notificaitonID, broadcastTime, extras];
this.call_native("addLocalNotification", data, null); this.call_native("addLocalNotification", data, null);
} }
} }
JPushPlugin.prototype.removeLocalNotification = function(notificationID) { JPushPlugin.prototype.removeLocalNotification = function(notificationID) {
if(device.platform == "Android") { if(device.platform == "Android") {
this.call_native("removeLocalNotification", [notificationID], null); this.call_native("removeLocalNotification", [notificationID], null);
} }
} }
JPushPlugin.prototype.clearLocalNotifications = function() { JPushPlugin.prototype.clearLocalNotifications = function() {
if(device.platform == "Android") { if(device.platform == "Android") {
data=[] data = [];
this.call_native("clearLocalNotifications", data, null); this.call_native("clearLocalNotifications", data, null);
} }
} }
JPushPlugin.prototype.reportNotificationOpened = function(msgID) { JPushPlugin.prototype.reportNotificationOpened = function(msgID) {
if(device.platform == "Android") { if(device.platform == "Android") {
this.call_native("reportNotificationOpened", [msgID], null); this.call_native("reportNotificationOpened", [msgID], null);
} }
} }
//iOS single /**
*是否开启统计分析功能,用于“用户使用时长”,“活跃用户”,“用户打开次数”的统计,并上报到服务器上,
*在 Portal 上展示给开发者。
**/
JPushPlugin.prototype.setStatisticsOpen = function(mode) {
if(device.platform == "Android") {
this.call_native("setStatisticsOpen", [mode], null);
}
}
//iOS single
if(!window.plugins) { if(!window.plugins) {
window.plugins = {}; window.plugins = {};
@@ -333,6 +343,3 @@ if(!window.plugins.jPushPlugin){
} }
module.exports = new JPushPlugin(); module.exports = new JPushPlugin();