欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java后端集成激光推送

程序员文章站 2022-03-27 12:57:10
激光推送引入maven包 cn.jpush.api jpush-client 3.4.3配置安卓 ios通知方式private AndroidNotification buildAndroidNotifi...

激光推送

引入maven包

<dependency>
    <groupId>cn.jpush.api</groupId>
    <artifactId>jpush-client</artifactId>
    <version>3.4.3</version>
</dependency>

配置安卓 ios通知方式

private AndroidNotification buildAndroidNotification(ExtraPushInfoDto dto) {
    return AndroidNotification.newBuilder()
        .setTitle(pushConfig.getTitle()) // 默认app名称
        .setAlert(dto.getContent())
        .addExtras(dto.getJiGuangExtensions())
        .build();
}

private IosNotification buildIosNotification(ExtraPushInfoDto dto) {
    return IosNotification.newBuilder()
        .setAlert(dto.getContent())
        .setBadge(1)
        .setSound("")
        .addExtras(dto.getJiGuangExtensions())
        .build();
}

执行推送

@Override
public void jPushByAlias(String alias, ExtraPushInfoDto dto) {
    this.startPush(Audience.alias(alias), dto);
}

private void startPush(Audience aliasAudience, ExtraPushInfoDto dto) {
    GlobalPushConfig.JpushConfig jPushConfig = pushConfig.getJpushConfig();
    String jpushSecret = jPushConfig.getAppSecret();
    String jpushAppKey = jPushConfig.getAppKey();
    if (StringUtils.isBlank(jpushSecret) || StringUtils.isBlank(jpushAppKey)) {
        logger.error("推送消息失败,无有效的配置!");
        return;
    }
    JPushClient client = new JPushClient(
            jpushSecret, jpushAppKey, null, ClientConfig.getInstance());
    try {
        String[] activeProfiles = environment.getActiveProfiles();
        boolean isProductionEnvironment = ArrayUtils.contains(activeProfiles, "prod");
        // 构造推送对象
        PushPayload.Builder builder = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(aliasAudience);

        builder.setNotification(Notification.newBuilder()
                .addPlatformNotification(buildAndroidNotification(dto))
                .addPlatformNotification(buildIosNotification(dto))
                .build()); // 推送 [通知]
        builder.setOptions(Options.newBuilder().setApnsProduction(isProductionEnvironment).build());
        client.sendPush(builder.build());
    } catch (APIConnectionException e) {
        logger.error("推送连接出现异常", e);
    } catch (APIRequestException e) {
//            logger.error("推送请求出现异常!", e);
        logger.info("HTTP Status: " + e.getStatus());
        logger.info("Error Code: " + e.getErrorCode());
        logger.info("Error Message: " + e.getErrorMessage());
    } finally {
        client.close();
    }
}

配置文件

push:
  title: 推送主题
  package-name: com.xxx.xxx // 推送包名
  jpush-config:
    app-key: ****
    app-secret: ****

本文地址:https://blog.csdn.net/lwjxxhx/article/details/107506151

相关标签: 后端实例