java de Iphone批量推送代码

本文介绍了一种批量推送消息至苹果设备的方法,包括获取token、设置消息内容、配置应用图标上的数值、选择正式或测试服务器,并通过多线程并发发送通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
     * apple批量的推送方法
     * @param tokens  iphone手机获取的token
     * @param content 推送消息的内容
     * @param count 应用图标上小红圈上的数值
     * @param goal 目标服务器  true:正式 false:测试
     * @parm List<String> 返回发送失败的tokens
     */
	public List<String>  ApnsSend(List<String> tokenList,String content,int count ,boolean goal){
		List<String> tokens = new ArrayList<String>();
		try {
		String certificatePath="";
		String certificatePassword="";
		if(!goal){
		//测试证书地址+密码
		certificatePath=PropertiesUtil.getProperty("testCertificatePath");     
		certificatePassword=PropertiesUtil.getProperty("testCertificatePwd"); 
	}else{
		//正式证书地址+密码
		certificatePath=PropertiesUtil.getProperty("certificatePath");     
		certificatePassword=PropertiesUtil.getProperty("certificatePwd"); 
		}
		PushNotificationManager pushManager = new PushNotificationManager();//true:表示的是产品发布推送服务 false:表示的是产品测试推送服务
		pushManager.initializeConnection(new AppleNotificationServerBasicImpl(certificatePath, certificatePassword, goal));
		//这个地方估计数据多会有错,不知道怎样该怎样做 是先拿到链接在用线程发怕长时间链接APNS服务器会给断开, 还是一个一个的开连接发
		/*AppleNotificationServer server = null;
		try {
			server = new AppleNotificationServerBasicImpl(certificatePath,certificatePassword,goal);	//true 正式  false 测试服务器
		} catch (KeystoreException e) {
			receipt="服务器链接失败";
			System.out.println(receipt);
		}*/
		List<Task> tasks = TaskProducer.produce(tokenList,content,count,pushManager); 
		Queue<Task> taskQueue = new ConcurrentLinkedQueue<Task>();  
	        taskQueue.addAll(tasks);  
	        List<Thread> threadHolder = new LinkedList<Thread>();  
	        TaskHandler taskHandler = new TaskHandler(taskQueue);
	        for(int i = 0; i < 10; i ++) {  
			Thread thread = new Thread(taskHandler);  
			    threadHolder.add(thread);  
			    thread.start();  
	        }  
	        while(true) {  
	            boolean allFinished = true;  
	            for(Thread thread : threadHolder) {  
	                allFinished = allFinished && !thread.isAlive();  
	            }  
	              
	            if(allFinished) {  
	                break;  
	            }  
		tokens = taskHandler.getTokens();
	        return tokens;
		}catch(Exception e){
			return tokens;
		}
		
	}

	private static class TaskHandler implements Runnable {  
		private final Queue<Task> tasks;
		public List<String> tokens = new ArrayList<String>();
		public TaskHandler(Queue<Task> tasks) {  
		    this.tasks = tasks;  
		}  
		public void run() {  
		    while(!tasks.isEmpty()) {  
			Task task = tasks.poll();  
			if(task != null) {  
			    try {
				tokens.add(task.start());
				} catch (Exception e) {
					}  
                }  
            } 
        }
        public List<String> getTokens(){
        	return tokens;
        }
          
    }  
    
    /**
	 * @param args
	 * 测试方法
	 */
	public static void main(String[] args) {
		PhonePush pp = new PhonePush();
		List<String> tokens=new ArrayList<String>();
		tokens.add("76edc85fd2e6704b27974d774cc046d7e33a3440fd6f39ba18c729387e6c788a");
		tokens.add("dc2cf037bd4465c851b1d96a86b0a028307bc7e443435b6fafe93c2957bb415c");
		tokens.add("d44f95e7f08bf62377a5b041584ce5dfcb9ce89e3d01a3846b96fe80e2a0991");
		String content="批量测试"; //测试内容
		int count=10; //手机上显示的数值 最好给1 
		boolean goal=false;  //正式服务起ture  测试服务器false
		tokens=pp.ApnsSend(tokens, content, count, goal);
		System.out.println(tokens.size());
	}

}
//还需要2个类 目的将所有任务加入到线程池
import java.util.List;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;


public class Task {
	private int id;
	private String token;
	private PushNotificationPayload payload;
	private List<PushedNotification> notifications ;
	private PushNotificationManager pushManager;
	public Task(int id,String token,PushNotificationPayload payload,PushNotificationManager pushManager) {
		this.id = id;
		this.token=token;
		this.payload=payload;
		this.pushManager=pushManager;
	}
	public String start() throws CommunicationException, KeystoreException {
		String ftoken="";
		Device device = new BasicDevice();
		device.setToken(token);
		notifications = pushManager.sendNotifications(payload, device);
		List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);
		int failed = failedNotifications.size();
		if(failed>0){
			System.out.println(Thread.currentThread().getName() + ": error send faild " + id+token);
			ftoken=token;
			System.out.println(ftoken);
		}
		System.out.println(Thread.currentThread().getName() + ": start to handle task " + id+token);
		return ftoken;
	}
	
}
//第二个类 其实可以不用将每个的token的payload都加载一遍,因为内容都一样,可以将一个封装好的payload穿进去,这里就不做了。批量还没有做大量的测试,会有BUG的 //- - 

import java.util.LinkedList;
import java.util.List;
import org.json.JSONException;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;

public class TaskProducer {

	public static List<Task> produce(List<String> tokenList,String content,int count,PushNotificationManager pushManager) throws JSONException {
		List<Task> tasks = new LinkedList<Task>();
		PushNotificationPayload payload = null;
		for(int i = 0; i < tokenList.size(); i ++) {
		payload = new PushNotificationPayload();
				payload.addAlert(content);
				payload.addSound("default");
				payload.addBadge(count);
				tasks.add(new Task((i + 1),tokenList.get(i),payload,pushManager));
		}
		return tasks;
	}
		
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值