1. 引入依赖
<!-- 极光 -->
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.3.10</version>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.1.4</version>
</dependency>
<!-- 苹果 -->
<dependency>
<groupId>com.notnoop.apns</groupId>
<artifactId>apns</artifactId>
<version>1.0.0.Beta6</version>
</dependency>
<!-- 华为 -->
<dependency>
<groupId>com.huawei.android</groupId>
<artifactId>huawei-push</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 小米,vivo 请去官网下载, 然后配置到maven私服仓库nexus -->
<dependency>
<groupId>com.xiaomi</groupId>
<artifactId>mipush</artifactId>
<version>2.2.20</version>
</dependency>
<dependency>
<groupId>com.vivo</groupId>
<artifactId>vpush</artifactId>
<version>1.1.0</version>
</dependency>
2. 定义推送接口
public interface PushMessage {
/**
* 通知栏消息推送
*/
public int pushNcMsg(PushMessageDTO pushMessageDTO, String content, String title) throws Exception ;
/**
* 透传推送
*/
public int pushTransMsg(PushMessageDTO pushMessageDTO, String content) throws Exception ;
}
//辅助类 appName, appId, appKey ,masterSecret请去官网注册账号,添加app应用获取
@Getter
@Setter
@ToString
public class PushMessageDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String appName; //应用名称
private String appId; //应用id
private String appKey; //应用key
private String masterSecret; //秘钥
private String target; //推送目标
private String platform; //推送平台
}
3. 实现类
//苹果都是透传推送
@Component
public class ApplePushMessage implements PushMessage {
@Override
public int pushNcMsg(PushMessageDTO pushMessageDTO, String content, String title) throws Exception {
// TODO Auto-generated method stub
return 0;
}
//苹果的appKey是voippush.p12文件路径, masterSecret是密码
@Override
public int pushTransMsg(PushMessageDTO pushMessageDTO, String content) throws Exception {
ApnsService service = APNS.newService()
.withCert(pushMessageDTO.getAppKey(), pushMessageDTO.getMasterSecret())
.withSandboxDestination()
.withAppleDestination(true)
.build();
String payloadApple = APNS.newPayload()
.alertBody(content)
.build();
String token = pushMessageDTO.getTarget();
service.push(token, payloadApple);
return 1;
}
}
//华为
@Component
public class HuaWeiPushMessage implements PushMessage {
private static String tokenUrl = "https://login.cloud.huawei.com/oauth2/v2/token"; // 获取认证Token的URL
private static String apiUrl = "https://api.push.hicloud.com/pushsend.do"; // 应用级消息下发API
private static String accessToken;// 下发通知消息的认证Token
private static long tokenExpiredTime; // accessToken的过期时间
@Override
public int pushNcMsg(PushMessageDTO pushMessageDTO, String conte