1.极光推送接口

 

主要类:根类:IPush

import java.util.List;

public interface IPush {

    public void pushToUser(String userId, PushEntity pushEntity);

    public void pushToUserList(List<String> userIdList, PushEntity pushEntity);

    public void pushToDevice(List<String> deviceTokenList, PushEntity pushEntity);

    public void pushToApp(PushEntity pushEntity);
}

 

实现类两种,平台不同,实现类也不同

JPushAndroid  

 

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.jpush.api.common.DeviceType;

@Component
public class JPushAndroid implements IPush {

    @Autowired
    private JPushService jPushService;

    public void pushToApp(PushEntity pushEntity) {
        jPushService.sendNotification2App(pushEntity, DeviceType.Android);
    }

    public void pushToUser(String userId, PushEntity pushEntity) {

        if (StringUtils.isNotBlank(userId)) {
            jPushService.sendNotification2Alias(userId, pushEntity, DeviceType.Android);
        }
    }

    public void pushToUserList(List<String> userIdList, PushEntity pushEntity) {
        if (userIdList != null && userIdList.size() > 0) {
            for (String userId : userIdList) {
                if (StringUtils.isNotBlank(userId)) {
                    pushToUser(userId, pushEntity);
                }
            }
        }
    }

    public void pushToDevice(List<String> deviceTokenList, PushEntity pushEntity) {

        if (deviceTokenList != null && deviceTokenList.size() > 0) {

            for (String deviceToken : deviceTokenList) {
                if (StringUtils.isNotBlank(deviceToken)) {
                    jPushService.sendNotification2Reg(deviceToken, pushEntity, DeviceType.Android);
                }
            }
        }
    }

}

JPushIos

 

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.jpush.api.common.DeviceType;

@Component
public class JPushIOS implements IPush {

    @Autowired
    private JPushService jPushService;

    public void pushToApp(PushEntity pushEntity) {
        jPushService.sendNotification2App(pushEntity, DeviceType.IOS);
    }

    public void pushToUser(String userId, PushEntity pushEntity) {

        if (StringUtils.isNotBlank(userId)) {
            jPushService.sendNotification2Alias(userId, pushEntity, DeviceType.IOS);
        }
    }

    public void pushToUserList(List<String> userIdList, PushEntity pushEntity) {
        if (userIdList != null && userIdList.size() > 0) {
            for (String userId : userIdList) {
                if (StringUtils.isNotBlank(userId)) {
                    pushToUser(userId, pushEntity);
                }
            }
        }
    }

    /**
     * 根据设备列表推送
     */
    public void pushToDevice(List<String> deviceTokenList, PushEntity pushEntity) {

        if (deviceTokenList != null && deviceTokenList.size() > 0) {

            for (String deviceToken : deviceTokenList) {
                if (StringUtils.isNotBlank(deviceToken)) {
                    jPushService.sendNotification2Reg(deviceToken, pushEntity, DeviceType.IOS);
                }
            }
        }
    }

}

 

 

IPush直接实现类

JPushService

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.DeviceType;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.xcecs.wifi.provider.utils.PropertyUtils;
import com.xcecs.wifi.provider.utils.SpringUtils;
import com.xcecs.wifi.provider.utils.StringUtilsEx;

@Component
public class JPushService {

    private Log logger = LogFactory.getLog(JPushService.class);

    @Autowired
    private MobilePushService mobilePushService;

    public void sendNotification2App(PushEntity pushEntity, DeviceType platform) {

        PushPayload.Builder payloadBuilder = PushPayload.newBuilder();
        payloadBuilder.setAudience(Audience.all());

        send(pushEntity, payloadBuilder, platform);
    }

    public void sendNotification2Tag(String tag, PushEntity pushEntity, DeviceType platform) {

        PushPayload.Builder payloadBuilder = PushPayload.newBuilder();
        payloadBuilder.setAudience(Audience.tag(tag));

        send(pushEntity, payloadBuilder, platform);
    }

    public void sendNotification2Alias(String alias, PushEntity pushEntity, DeviceType platform) {

        PushPayload.Builder payloadBuilder = PushPayload.newBuilder();
        payloadBuilder.setAudience(Audience.alias(alias.replace("-", "")));

        send(pushEntity, payloadBuilder, platform);
    }

    public void sendNotification2Reg(String regId, PushEntity pushEntity, DeviceType platform) {

        PushPayload.Builder payloadBuilder = PushPayload.newBuilder();
        payloadBuilder.setAudience(Audience.registrationId(regId));

        send(pushEntity, payloadBuilder, platform);
    }

    private void send(PushEntity pushEntity, PushPayload.Builder payloadBuilder, DeviceType deviceType) {

        try {
            List<String[]> JpushInfoList = mobilePushService.getJpushKeyInfo(pushEntity.getJpushApiMasterSecret(),
                    pushEntity.getJpushAppKey());

            // 如果配置mobile.notify.ios.production=false,则是开发模式
            boolean iosMode = true;
            if (StringUtils.isNotBlank(PropertyUtils.getProperty("mobile.notify.ios.production"))
                    && "false".equals(PropertyUtils.getProperty("mobile.notify.ios.production").trim())) {
                iosMode = false;
            }

            // 设置平台
            payloadBuilder.setPlatform(deviceType.equals(DeviceType.IOS) ? Platform.ios() : Platform.android());

            Map<String, Object> extrasMap = new HashMap<String, Object>();

            // 新的模式,只需要传入type与value
            if (StringUtils.isNotBlank(pushEntity.getType())) {
                extrasMap.put("type", pushEntity.getType());
            }

            if (StringUtils.isNotBlank(pushEntity.getValue())) {
                extrasMap.put("value", pushEntity.getValue());
            }


            // 如果是IOS,设置平台特性
            if (deviceType.equals(DeviceType.IOS)) {

                // IOS内容的长度限制
                String notificationContent = pushEntity.getMsgContent();
                if (StringUtils.isNotBlank(notificationContent) && notificationContent.getBytes().length > 70) {
                    notificationContent = StringUtilsEx.substringb(notificationContent, 70) + "...";
                }

                IosNotification.Builder iosNotificationBuilder = IosNotification.newBuilder().setAlert(notificationContent).setBadge(1)
                        .setSound("default");

                for (String key : extrasMap.keySet()) {
                    iosNotificationBuilder.addExtra(key, String.valueOf(extrasMap.get(key)));
                }

                payloadBuilder.setNotification(Notification.newBuilder().addPlatformNotification(iosNotificationBuilder.build()).build());
            } else {

                AndroidNotification.Builder androidNotificationBuilder = AndroidNotification.newBuilder()
                        .setAlert(pushEntity.getMsgContent()).setTitle(pushEntity.getMsgTitle());

                for (String key : extrasMap.keySet()) {
                    androidNotificationBuilder.addExtra(key, String.valueOf(extrasMap.get(key)));
                }

                payloadBuilder.setNotification(Notification.newBuilder().addPlatformNotification(androidNotificationBuilder.build())
                        .build());
            }

            PushPayload pushPayload = payloadBuilder.build();

            for (String[] jpushInfo : JpushInfoList) {
                try {
                    JPushClient jPushClient = new JPushClient(jpushInfo[0], jpushInfo[1], iosMode,
                            (pushEntity.getJpushTimeToLive() == null ? 86400 : pushEntity.getJpushTimeToLive()));
                    jPushClient.sendPush(pushPayload);
                } catch (Exception e) {

                    // 个推时如果手机端没有注册用户,不打错误日志
                    if (e.getMessage().indexOf("\"code\": 1011") == -1) {
                        logger.error("JPUSH推送消息时发生异常:[" + e.getMessage() + "]", e);
                    }
                }
            }
        } catch (Exception e) {
            if (e.getMessage().indexOf("\"code\": 1011") == -1) {
                logger.error("JPUSH推送消息时发生异常:[" + e.getMessage() + "]", e);
            }
        }
    }

}

 

读取配置的类MobilePushService

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.xcecs.wifi.provider.utils.ServiceException;

@Component
public class MobilePushService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    
    /*********************************** 内部使用接口 ******************************/


    // 0:IOS,1:android
    protected static Integer getPlatformWithDeviceToken(String deviceToken) {
        return (deviceToken.length() == 64) ? 0 : 1;
    }

    /**
     * 返回API MasterSecret,AppKey
     * @param appid
     * @return
     */
    protected List<String[]> getJpushKeyInfo(String apiMasterSecret, String appKey) {

        List<Map<String, Object>> resultList = null;

        List<String[]> resultA = new ArrayList<String[]>();

        try {

            // 如果设定了自定义key,则使用自定义,否则进行数据库查询
            if (StringUtils.isNotBlank(apiMasterSecret) && StringUtils.isNotBlank(appKey)) {
                resultA.add(new String[] { apiMasterSecret, appKey });
            } else {
                resultList = jdbcTemplate.queryForList("select * from cpt_notify_jpush where status = 1",
                        new Object[] {});
                

                if (resultList != null && resultList.size() > 0) {
                    for (Map<String, Object> result : resultList) {
                        resultA.add(new String[] { (String) result.get("api_master_secret"), (String) result.get("app_key") });
                    }
                }
            }

        } catch (Exception e) {
        }

        if (resultA.size() == 0) {
            throw new ServiceException("请配置好推送的APPKEY");
        }

        return resultA;
    }

}

推送实体 PushEntity

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class PushEntity implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    // jpush apiMasterSecret
    private String jpushApiMasterSecret;

    // jpush appkey
    private String jpushAppKey;

    // jpush timeToLive
    private Long jpushTimeToLive;

    // 消息标题
    private String msgTitle;

    // 消息内容
    private String msgContent;

    // 新消息的类型
    private String type;

    // 新消息的值
    private String value;
    
    private String platform;

    public String getPlatform() {
        return platform;
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }
    

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getMsgTitle() {
        return msgTitle;
    }

    public void setMsgTitle(String msgTitle) {
        this.msgTitle = msgTitle;
    }

    public String getMsgContent() {
        return msgContent;
    }

    public void setMsgContent(String msgContent) {
        this.msgContent = msgContent;
    }

    public String getJpushApiMasterSecret() {
        return jpushApiMasterSecret;
    }

    public void setJpushApiMasterSecret(String jpushApiMasterSecret) {
        this.jpushApiMasterSecret = jpushApiMasterSecret;
    }

    public String getJpushAppKey() {
        return jpushAppKey;
    }

    public void setJpushAppKey(String jpushAppKey) {
        this.jpushAppKey = jpushAppKey;
    }

    public Long getJpushTimeToLive() {
        return jpushTimeToLive;
    }

    public void setJpushTimeToLive(Long jpushTimeToLive) {
        this.jpushTimeToLive = jpushTimeToLive;
    }

}

 

 

直接d调用JPushService 的方法就行了,appkey,master secret配置好就行了