关闭

百度云推送

709人阅读 评论(0) 收藏 举报
分类:
<pre name="code" class="html"><pre name="code" class="html">    private Map<String, Integer> sendMessage(MessageEntity messageEntity) {
        Map<String, Integer> result = new HashMap<String, Integer>();
        PushMessageForAdmin pushMessage = new PushMessageForAdmin();
        int errorFlag = 2;
        int sum = 0;
        int success = 0;
        int channel = messageEntity.getChannel();

        String title = messageEntity.getTitle();
        String messageString = messageEntity.getMessageString();
        int device = messageEntity.getDevice();
        String channelId = messageEntity.getChannelId();

        //指定设备推送
        if (device == 1) {
            try {


                if (channel == 1) {
                    if (StringUtils.isEmpty(channelId)) {
                        errorFlag = 3;

                    } else {
                        errorFlag = pushMessage.pushMessageToSingleDevice(messageEntity);
                    }
                }
                if (channel == 2) {

                    String[] chaId = messageEntity.getLotChannelId().split("-");
                    if (chaId == null || chaId.length <= 0) {
                        errorFlag = 3;
                    } else {

                        for (String id : chaId) {

                            sum = sum + 1;
                            messageEntity.setChannelId(id);
                            int sendFlag = pushMessage.pushMessageToSingleDevice(messageEntity);
                            if (sendFlag == 1) {
                                errorFlag = 1;
                                success = success + 1;
                            }
                        }
                    }

                }


            } catch (Exception e) {
                logger.error("pushSingle抓住异常");
                errorFlag = 4;

            }
        }


        //所有设备推送
        else if (device == 2) {
            try {
                int sendTime = messageEntity.getSendTime();
                int deviceType = messageEntity.getDeviceType();
                String sdTime = messageEntity.getSdTime();
                Long ts = null;
                if (sendTime == 1) {
                    ts = System.currentTimeMillis() / 1000 + 70;
                } else if (sendTime == 2) {

                    SimpleDateFormat SDF_1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date pubTime = SDF_1.parse(sdTime);
                    SimpleDateFormat sb2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String t2 = sb2.format(pubTime);
                    ts = Timestamp.valueOf(t2).getTime() / 1000;


                    long subTime = ts - System.currentTimeMillis() / 1000;
                    if (subTime < 70) {
                        ts = System.currentTimeMillis() / 1000 + 70;
                    }

                }
                messageEntity.setTs(ts);

                errorFlag = pushMessage.pushMessageToAll(messageEntity);

            } catch (Exception e) {
                logger.error("pushAll抓住异常");
            }


        }
        result.put("errorFlag", errorFlag);
        result.put("channel", channel);
        result.put("sum", sum);
        result.put("success", success);
        return result;

    }



<pre name="code" class="html">package com.baidu.yunpush;


import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushMsgToAllRequest;
import com.baidu.yun.push.model.PushMsgToAllResponse;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PushMessageForAdmin {

    private static Logger logger = LoggerFactory.getLogger(PushMessageForAdmin.class);

    private static BaiduPushClient pushClient;

    /**
     * 根据ChannelId精准推送  支持android/ios设备
     */
    public static int pushMessageToSingleDevice(MessageEntity message) throws PushClientException, PushServerException {
        pushClient = initPushClientMaple(message);
        try {
            logger.info("推送信息:" + message.toString());

            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
                    .addChannelId(message.getChannelId())
                    .addMsgExpires(new Integer(message.getMsgExpires())). // message有效时间
                    addMessageType(message.getType()).// 1:通知,0:透传消息. 默认为0 注:IOS只有通知.
                    addMessage(message.getMessageString()).
                            addDeviceType(message.getDeviceType()).addDeployStatus(2);// deviceType => 3:android, 4:ios  deployStatus :1开发 2生产
            PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);

            logger.info("推送信息:msgId: " + response.getMsgId() + ",sendTime: " + response.getSendTime());
            return 1;
        } catch (PushClientException e) {
            /*
			 * ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,'true' 表示抛出, 'false' 表示捕获。
			 */
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                return 2;
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {

                logger.info("推送信息:" + String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
                return 2;
            }
        }
    }

    public static int pushMessageToAll(MessageEntity message) throws PushClientException, PushServerException {
        pushClient = initPushClientMaple(message);

        try {
            PushMsgToAllRequest request = new PushMsgToAllRequest()
                    .addMsgExpires(new Integer(message.getMsgExpires())).addMessageType(message.getType())
                    .addMessage(message.getMessageString())
//					.addSendTime(System.currentTimeMillis() / 1000 + 120) // 设置定时推送时间,必需超过当前时间一分钟,单位秒.实例2分钟后推送
                    .addSendTime(message.getTs())
                    .addDepolyStatus(1).addDeviceType(message.getDeviceType());


            // 5. http request
            PushMsgToAllResponse response = pushClient.pushMsgToAll(request);
            // Http请求结果解析打印
            logger.info("推送信息:msgId: " + response.getMsgId() + ",sendTime: " + response.getSendTime() + ",timerId: " + response.getTimerId());
            return 1;
        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                logger.error("pushMessageToAll()异常");
                return 2;
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                logger.info("推送信息:" + String.format(
                        "requestId: %d, errorCode: %d, errorMessage: %s",
                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
                return 2;
            }
        }
    }


    private static BaiduPushClient initPushClientMaple(MessageEntity message) {

        JSONObject notification = new JSONObject();
        notification.put("type", message.getTypeKey());


        if (message.getDeviceType() == 4) {
            notification.put("message", message.getMessageString());
            pushClient = PushInitForIos.getInstance();
            JSONObject jsonAPS = new JSONObject();
            jsonAPS.put("alert", message.getTitle());
            jsonAPS.put("sound", "ttt");
            notification.put("aps", jsonAPS);

            if (message.getUrlFlag() == 3) {
                notification.put("url", message.getUrl());
            }

        } else {
            notification.put("description", message.getMessageString());
            notification.put("title", message.getTitle());
            if (message.getUrlFlag() == 3) {
                JSONObject jsonCustom = new JSONObject();
                jsonCustom.put("url", message.getUrl());
                notification.put("custom_content", jsonCustom);

            }
            pushClient = PushInitForAndroid.getInstance();
        }
        message.setMessageString(notification.toString());
        return pushClient;
    }


//	public static void main(String[] args) throws PushClientException, PushServerException {
//
//		MessageEntity iosmEntity = new MessageEntity();
//		iosmEntity.setChannelId("4680797241349342110");
//		iosmEntity.setTitle("订单信息");
//		iosmEntity.setTypeKey("orderInfo");
//		iosmEntity.setPlatform("ios");
//		iosmEntity.setMessageString("你好");
//		pushMessageToSingleDevice(iosmEntity);
//
//		MessageEntity androidEntity = new MessageEntity();
//		androidEntity.setChannelId("4193505691417552139");
//		androidEntity.setTitle("订单信息");
//		androidEntity.setTypeKey("orderInfo");
//		androidEntity.setPlatform("android");
//		androidEntity.setMessageString("你好");
//		pushMessageToSingleDevice(androidEntity);
//	}
}




   
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:61579次
    • 积分:2130
    • 等级:
    • 排名:第18592名
    • 原创:80篇
    • 转载:19篇
    • 译文:0篇
    • 评论:17条