<1>: Guide package
<!--极光推送通知-->
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.4.6</version>
</dependency>
<2>:
Example 1:
public static void main(String[] args) {
List<String> alias = new ArrayList<String>();
alias.add("123");
sendToAll("测试", "测试信息", "测试信息", "https://www.baidu.com");
}
//发送给所有用户
public static int sendToAll( String notification_title, String msg_title, String msg_content, String extrasparam) {
int result = 0;
try {
PushPayload pushPayload= JpushClientUtil.buildPushObject_android_and_ios(notification_title,msg_title,msg_content,extrasparam);
PushResult pushResult=jPushClient.sendPush(pushPayload);
if(pushResult.getResponseCode()==200){
result=1;
}
logger.info("[极光推送]PushResult result is " + pushResult);
} catch (APIConnectionException e) {
logger.error("[极光推送]Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
logger.info("[极光推送]HTTP Status: " + e.getStatus());
logger.info("[极光推送]Error Code: " + e.getErrorCode());
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
}
return result;
}
public static PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content, String extrasparam) {
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.all())
.setNotification(Notification.newBuilder()
.setAlert(msg_content)
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(msg_content)
.setTitle(notification_title)
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("url",extrasparam)
.build()
)
.addPlatformNotification(IosNotification.newBuilder()
//传一个IosAlert对象,指定apns title、title、subtitle等
.setAlert(msg_content)
//直接传alert
//此项是指定此推送的badge自动加1
.incrBadge(1)
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
.setSound("sound.caf")
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("url",extrasparam)
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
// .setContentAvailable(true)
.build()
)
.build()
)
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
.setMessage(Message.newBuilder()
.setMsgContent(msg_content)
.setTitle(msg_title)
.addExtra("url",extrasparam)
.build())
.setOptions(Options.newBuilder()
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
.setApnsProduction(true)
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
.setSendno(1)
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
.setTimeToLive(86400)
.build()
)
.build();
}
<3>
Example 2 (Learn from others) :
public static boolean sendPush(
PushParam pushParam,
String masterSecret,
String appKey) throws JPushException {
ClientConfig config = ClientConfig.getInstance();
config.setGlobalPushSetting(false, 24 * 60 * 60 * 2);
JPushClient jpushClient =
new JPushClient(masterSecret, appKey, null, config);
PushPayload payload = buildPushPayload(pushParam);
try {
PushResult result = jpushClient.sendPush(payload);
if (result.isResultOK()) {
return true;
} else {
if (result.error.getCode() == 2002) {
log.warn("极光API调用频率超出限制");
return false;
} else if (result.error.getCode() == 1011) {
log.info("没有设备满足推送目标,可能是因为没有登录");
return true;
} else {
String errorMessage = "极光API出错, statusCode=" + result.getResponseCode()
+ ", code=" + result.error.getCode()
+ ", msg=" + result.error.getMessage();
log.error(errorMessage);
throw new JPushException(errorMessage);
}
}
} catch (APIConnectionException e) {
String errorMessage = "调用极光http API连接错误,需要过一段时间重试";
log.error(errorMessage, e);
return false;
} catch (APIRequestException e) {
if (e.getErrorCode() == 2002) {
log.warn("极光API调用频率超出限制, messageId: " + e.getMsgId());
return false;
} else if (e.getErrorCode() == 1011) {
log.info("没有设备满足推送目标,可能是因为没有登录, messageId: " + e.getMsgId());
return true;
} else {
String errorMessage = "系统内部错误:调用极光推送http API时参数错误,需要修复请求参数";
log.error(errorMessage, e);
log.error("HTTP Status: " + e.getStatus());
log.error("Error Code: " + e.getErrorCode());
log.error("Error Message: " + e.getErrorMessage());
throw new JPushException(errorMessage);
}
}
}
private static PushPayload buildPushPayload(PushParam pushParam) {
List<PushParam.Platform> platforms = pushParam.getPlatforms();
List<String> aliases = pushParam.getAliases();
JsonObject intent = null;
if (pushParam.getIntent() != null) {
intent = new JsonObject();
intent.add("url", new JsonPrimitive(pushParam.getIntent().getUrl()));
}
PushPayload.Builder builder = PushPayload.newBuilder();
if(platforms.contains(PushParam.Platform.ANDROID)
&& platforms.contains(PushParam.Platform.IOS)) {
builder.setPlatform(Platform.android_ios());
} else if (platforms.contains(PushParam.Platform.ANDROID)) {
builder.setPlatform(Platform.android());
} else if (platforms.contains(PushParam.Platform.IOS)) {
builder.setPlatform(Platform.ios());
}
builder.setAudience(Audience.alias(aliases));
Notification.Builder notificationBuilder = Notification.newBuilder();
if (platforms.contains(PushParam.Platform.ANDROID)) {
AndroidNotification.Builder androidNotifiBuilder =
AndroidNotification.newBuilder()
.setTitle(pushParam.getTitle())
.setAlert(pushParam.getMessage())
.addExtras(pushParam.getExtras());
if (pushParam.getIntent() != null) {
androidNotifiBuilder.setIntent(intent);
}
notificationBuilder.addPlatformNotification(androidNotifiBuilder.build());
}
if (platforms.contains(PushParam.Platform.IOS)) {
IosAlert alert = IosAlert.newBuilder()
.setTitleAndBody(pushParam.getTitle(), null, pushParam.getMessage())
.build();
notificationBuilder.addPlatformNotification(IosNotification.newBuilder()
.setAlert(alert)
.setContentAvailable(true)
.setMutableContent(true)
.addExtras(pushParam.getExtras())
.autoBadge()
.build());
}
return builder.setNotification(notificationBuilder.build())
.setOptions(Options.newBuilder()
.setApnsProduction(false)
.setTimeToLive(24 * 60 * 60 * 2)
.build())
.build();
}
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class PushParam {
/**
* 推送平台
*/
private List<Platform> platforms;
/**
* 推送目标别名,一个别名对应一个登录身份
*/
private List<String> aliases;
private String title;
private String message;
/**
* 仅安卓有效,指定跳转页面
* 使用 intent 里的 url 指定点击通知栏后跳转的目标页面;
* 此字段值,仅对走极光自有通道下发生效,不影响请求走厂商通道。
* 例子:"intent": {
* "url": "intent:#Intent;component=com.jiguang.push/com.example.jpushdemo.SettingActivity;end",
* }
*/
@Nullable
private Intent intent;
/**
* 扩展字段
* 这里自定义 JSON 格式的 Key / Value 信息,以供业务使用。
* 可以把跳转页面链接信息从这里传入,客户端收到后自行处理
*/
@Nullable
private Map<String, String> extras;
// /**
// * 用户回执
// */
// private Callback callback;
public enum Platform {
ANDROID, IOS
}
@Data
public static class Intent {
private String url;
}
}
public class JPushException extends IOException {
public JPushException(String msg) {
super(msg);
}
}