public class PushUtils {
privatestatic String host = "gateway.sandbox.push.apple.com"; privatestatic int port = 2195;
publicstatic void main(String[] args) throws Exception {
String deviceToken = "";//iphone手机获取的token String deviceToken2 = "";//iphone手机获取的token List deviceTokens = new ArrayList(); deviceTokens.add(deviceToken); deviceTokens.add(deviceToken2);
String contentOne = "只有你看到这条了";//push的内容 String contentMore = "你们都能看到的";//push的内容 String p12File ="E:\\push.p12";//这里是一个.p12格式的文件路径,需要去apple官网申请一个 String p12FilePassword ="123456";//此处注意导出的证书密码不能为空因为空密码会报错 pushOne(p12File, p12FilePassword, deviceToken2,contentOne);//单个推送 pushMore(p12File, p12FilePassword, deviceTokens,contentMore);//群组推送 }
publicstatic void pushOne(String p12File, String p12Pass, StringdeviceToken, String content) { try { PayLoad payLoad = new PayLoad(); payLoad.addAlert(content);//push的内容 payLoad.addBadge(1);//应用图标上小红圈上的数值 payLoad.addSound("default");//铃音
//添加字典 payLoad.addCustomDictionary("url", "www.baidu.com"); PushNotificationManager pushManager =PushNotificationManager.getInstance(); pushManager.addDevice("iphone", deviceToken);
//链接到APNs pushManager.initializeConnection(host, port, p12File, p12Pass,SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
//开始推送 Device client = pushManager.getDevice("iphone"); pushManager.sendNotification(client, payLoad); //断开链接 pushManager.stopConnection(); pushManager.removeDevice("iphone"); HLog.writeLog(HLog.INFO, "iphone 推送消息成功"); } catch (Exception e) { // System.out.println("iphone推送消息异常:" + e.getMessage()); HLog.writeLog(HLog.ERROR, "iphone 推送消息异常:" + e.getMessage()); } }
publicstatic void pushMore(String p12File, String p12Pass, ListdeviceTokens, String content) { try { PayLoad payLoad = new PayLoad(); payLoad.addAlert(content);//push的内容 payLoad.addBadge(1);//应用图标上小红圈上的数值 payLoad.addSound("default");//铃音
//添加字典 payLoad.addCustomDictionary("url", "www.baidu.com"); PushNotificationManager pushManager =PushNotificationManager.getInstance();
//链接到APNs pushManager.initializeConnection(host, port, p12File, p12Pass,SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
//开始循环推送 for (int i = 0; i < deviceTokens.size(); i++){ pushManager.addDevice("iphone" + i, deviceTokens.get(i)); Device client = pushManager.getDevice("iphone" + i); pushManager.sendNotification(client, payLoad); } //断开链接 pushManager.stopConnection(); for (int i = 0; i < deviceTokens.size(); i++){ pushManager.removeDevice("iphone" + i); } HLog.writeLog(HLog.INFO, "iphone 推送消息成功"); } catch (Exception e) { HLog.writeLog(HLog.ERROR, "iphone 推送消息异常:" + e.getMessage()); } } }
---------------------
需要的第三方包
bcprov-jdk16-145-1.jar (1.6 MB) commons-io-2.0.1.jar (155.8 KB) commons-lang-2.5.jar (272.6 KB) javapns-jdk16-163.jar (51.9 KB) log4j-1.2.16.jar (470.2 KB)