苹果推送(JAVA)

本方案采用了JAVAPNS,下载地址为:http://code.google.com/p/javapns/

代码如下:

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import javapns.notification.AppleNotificationServer;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PayloadPerDevice;
import javapns.notification.PushNotificationPayload;
import javapns.notification.transmission.NotificationProgressListener;
import javapns.notification.transmission.NotificationThread;
import javapns.notification.transmission.NotificationThreads;

/**
 * 苹果通知
 * 
 * @author Administrator
 * 
 */
public class AppleNotification {

	/**
	 * 日志输出类
	 */
	private static Logger logger = Logger.getLogger(AppleNotification.class
			.getName());

	/**
	 * 苹果消息推送
	 * 
	 * @param certificatePath
	 *            证书路径
	 * @param certificatePassword
	 *            证书密码
	 * @param deviceToken
	 *            设备标识
	 * @param msg
	 *            消息内容
	 * @param msgCount
	 *            消息数
	 * @param host
	 *            苹果推送服务器域名(开发:gateway.sandbox.push.apple.com ;
	 *            正式:gateway.push.apple.com)
	 * @return
	 */
	public boolean push(String certificatePath, String certificatePassword,
			String deviceToken, String msg, int msgCount, String host,
			boolean isProduction) {

		String keystore = certificatePath;// 证书路径和证书名
		String password = certificatePassword; // 证书密码
		String token = deviceToken;// 手机唯一标识
		boolean production = isProduction; // 设置true为正式服务地址,false为开发者地址
		int threadThreads = 10; // 线程数
		try {
			// 建立与Apple服务器连接
			AppleNotificationServer server = new AppleNotificationServerBasicImpl(
					keystore, password, production);
			List<PayloadPerDevice> list = new ArrayList<PayloadPerDevice>();
			PushNotificationPayload payload = new PushNotificationPayload();
			payload.addAlert(msg);
			payload.addSound("default");// 声音
			payload.addBadge(msgCount);// 图标小红圈的数值
			PayloadPerDevice pay = new PayloadPerDevice(payload, token);// 将要推送的消息和手机唯一标识绑定
			list.add(pay);

			NotificationThreads work = new NotificationThreads(server, list,
					threadThreads);//
			work.setListener(DEBUGGING_PROGRESS_LISTENER);// 对线程的监听,一定要加上这个监听
			work.start(); // 启动线程
			work.waitForAllThreads();// 等待所有线程启动完成

		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		return true;
	}

	public static final NotificationProgressListener DEBUGGING_PROGRESS_LISTENER = new NotificationProgressListener() {

		public void eventThreadStarted(NotificationThread notificationThread) {
			logger.info("   [EVENT]: thread #"
					+ notificationThread.getThreadNumber() + " started with "
					+ " devices beginning at message id #"
					+ notificationThread.getFirstMessageIdentifier());
		}

		public void eventThreadFinished(NotificationThread thread) {
			logger.info("   [EVENT]: thread #"
					+ thread.getThreadNumber() + " finished: pushed messages #"
					+ thread.getFirstMessageIdentifier() + " to "
					+ thread.getLastMessageIdentifier() + " toward "
					+ " devices");
		}

		public void eventConnectionRestarted(NotificationThread thread) {
			logger.info("   [EVENT]: connection restarted in thread #"
					+ thread.getThreadNumber() + " because it reached "
					+ thread.getMaxNotificationsPerConnection()
					+ " notifications per connection");
		}

		public void eventAllThreadsStarted(
				NotificationThreads notificationThreads) {
			logger.info("   [EVENT]: all threads started: "
					+ notificationThreads.getThreads().size());
		}

		public void eventAllThreadsFinished(
				NotificationThreads notificationThreads) {
			logger.info("   [EVENT]: all threads finished: "
					+ notificationThreads.getThreads().size());
		}

		public void eventCriticalException(
				NotificationThread notificationThread, Exception exception) {
			logger.info("   [EVENT]: critical exception occurred: "
					+ exception);
		}
	};
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Apple APNs java client, based on netty4. 基于netty4实现的苹果通知服务Java客户端。 特点: 支持第三版通知,即command = 2。目前的绝大部分Java客户端都只支持command = 1,即第二版。 支持SSL握手成功才返回,可以调用 pushManager.start().sync(); 等待握手成功才开始发; 最大限度重试发,内部自动处理重连,错误重发机制; 支持配置RejectListener,即通知被Apple服务器拒绝之后的回调接口; 支持配置ShutdownListener,即当shutdown时,没有发完的消息处理的回调接口; 支持发统计信息; 实现组件分离,可以利用PushClient,FeedbackClient来写一些灵活的代码。 Notification发者可以自己定义设置发的Queue,自己灵活处理阻塞,超时等问题。     Example: 更多的例子在src/test/java 目录下。 public class MainExample {     public static void main(String[] args) throws InterruptedException {         Environment environment = Environment.Product;         String password = "123456";         String keystore = "/home/hengyunabc/test/apptype/app_type_1/productAPNS.p12";         PushManager pushManager = new PushManagerImpl(keystore, password, environment);         //set a push queue         BlockingQueuequeue = new LinkedBlockingQueue(8192);         pushManager.setQueue(queue );         //waiting for SSL handshake success         pushManager.start().sync();         //build a notification         String token = "5f6aa01d8e3358949b7c25d461bb78ad740f4707462c7eafbebcf74fa5ddb387";         Notification notification = new NotificationBuilder()                 .setToken(token)                 .setBadge(1)                 .setPriority(5)                 .setAlertBody("xxxxx").build();         //put notification into the queue         queue.put(notification);         TimeUnit.SECONDS.sleep(10);         //get statistic info         Statistic statistic = pushManager.getStatistic();         System.out.println(statistic);     } } 标签:zpush
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linyu19872008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值