java集成推送SDK(oppo vivo xioami meizu huawei)

481 阅读6分钟

OPPO

OPPO 开放平台-OPPO开发者服务中心 (oppomobile.com)

<!-- 添加手动下载的 OPPO 推送 JAR -->
<dependency>
    <groupId>com.oppo.push</groupId>
    <artifactId>push-sdk</artifactId>
    <version>1.1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/opush-server-sdk-1.1.0.jar</systemPath>
</dependency>

image.png

import com.oppo.push.server.Sender;
import com.oppo.push.server.Environment;
import com.oppo.push.server.Notification;
import com.oppo.push.server.Target;
import com.oppo.push.server.Result;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class OPPOPush {

    // OPPO 推送服务的应用标识符
    private static final String APP_KEY = "APP_KEY";
    // OPPO 推送服务的密钥,用于身份验证
    private static final String MASTER_SECRET = "your_master_secret";

    /**
     * 创建一个 Sender 实例,用于发送通知
     * @return Sender 实例
     * @throws Exception 如果创建失败则抛出异常
     */
    private Sender createSender() throws Exception {
        return Sender.newBuilder()
                .appKey(APP_KEY)  // 设置应用标识符
                .masterSecret(MASTER_SECRET)  // 设置密钥
                .env(Environment.CHINA_PRODUCTION)  // 选择环境:中国生产环境
                .httpMaxConnection(64)  // 设置最大连接数
                .httpMaxRoute(64)  // 设置最大路由数
                .httpConnectionTimeout(5000)  // 设置连接超时时间(毫秒)
                .httpConnectRequestTimeout(5000)  // 设置连接请求超时时间(毫秒)
                .httpSocketTimeout(5000)  // 设置套接字超时时间(毫秒)
                .build();  // 构建 Sender 实例
    }

    /**
     * 创建一个通知对象,设置通知内容和参数
     * @return Notification 实例
     */
    private Notification createNotification() {
        Notification notification = new Notification();
        notification.setTitle("通知栏消息标题");  // 设置通知标题
        notification.setContent("通知栏内容");  // 设置通知内容

        // 设置可选参数
        notification.setStyle(1);  // 设置样式:1-标准样式
        notification.setAppMessageId(UUID.randomUUID().toString());  // 设置自定义消息ID
        notification.setCallBackUrl("http://www.example.com");  // 设置回调URL
        notification.setClickActionType(4);  // 设置点击动作类型
        notification.setClickActionActivity("com.example.app.SomeActivity");  // 设置应用内页
        notification.setClickActionUrl("http://www.example.com");  // 设置网页URL
        notification.setActionParameters("{"key1":"value1","key2":"value2"}");  // 设置动作参数
        notification.setShowTimeType(1);  // 设置展示类型:1-定时
        notification.setShowStartTime(System.currentTimeMillis() + 1000 * 60 * 3);  // 设置展示开始时间(3分钟后)
        notification.setShowEndTime(System.currentTimeMillis() + 1000 * 60 * 5);  // 设置展示结束时间(5分钟后)
        notification.setOffLine(true);  // 设置是否离线消息
        notification.setOffLineTtl(24 * 3600);  // 设置离线消息存活时间(24小时)
        notification.setTimeZone("GMT+08:00");  // 设置时区
        notification.setNetworkType(0);  // 设置网络类型:0-不限
        return notification;
    }

    /**
     * 发送单个通知
     * @throws Exception 如果发送失败则抛出异常
     */
    public void sendSingleNotification() throws Exception {
        Sender sender = createSender();  // 创建 Sender 实例
        Notification notification = createNotification();  // 创建通知对象
        Target target = Target.build("CN_8fa0618f178145d8c2a44091a1326411");  // 创建目标对象(替换为实际的注册ID)

        // 发送单个通知
        Result result = sender.unicastNotification(notification, target);

        // 打印结果
        System.out.println("HTTP Status Code: " + result.getStatusCode());
        System.out.println("Return Code: " + result.getReturnCode());
        System.out.println("Message ID: " + result.getMessageId());
    }

    /**
     * 发送批量通知
     * @throws Exception 如果发送失败则抛出异常
     */
    public void sendBatchNotification() throws Exception {
        Sender sender = createSender();  // 创建 Sender 实例
        Notification notification = createNotification();  // 创建通知对象

        // 创建批量通知映射
        Map<Target, Notification> batch = new HashMap<>();
        batch.put(Target.build("CN_ddfaa7db1e4ecf75014143bdbc3e53ea"), notification);  // 添加目标和通知
        batch.put(Target.build("CN_8fa0618f178145d8c2a44091a1326411"), notification);  // 添加目标和通知

        // 发送批量通知
        Result result = sender.unicastBatchNotification(batch);

        // 打印结果
        System.out.println("HTTP Status Code: " + result.getStatusCode());
        System.out.println("Return Code: " + result.getReturnCode());

        // 打印批量结果
        result.getUnicastBatchResults().forEach(record -> {
            System.out.println("Message ID: " + record.getMessageId());
            System.out.println("Error Code: " + record.getErrorCode());
            System.out.println("Error Message: " + record.getErrorMessage());
            System.out.println("Target: " + record.getTargetValue());
        });
    }

    /**
     * 发送广播通知
     * @throws Exception 如果发送失败则抛出异常
     */
    public void sendBroadcastNotification() throws Exception {
        Sender sender = createSender();  // 创建 Sender 实例
        Notification notification = createNotification();  // 创建通知对象

        // 保存通知
        Result saveResult = sender.saveNotification(notification);
        String messageId = saveResult.getMessageId();

        // 打印保存结果
        System.out.println("Saved Message ID: " + messageId);
        System.out.println("HTTP Status Code: " + saveResult.getStatusCode());
        System.out.println("Return Code: " + saveResult.getReturnCode());

        // 创建广播目标
        Target target = new Target();
        target.setTargetValue("CN_ddfaa7db1e4ecf75014143bdbc3e53ea;CN_8fa0618f178145d8c2a44091a1326411");  // 设置广播目标(用分号分隔)

        // 发送广播通知
        Result broadResult = sender.broadcastNotification(messageId, target);

        // 打印广播任务ID和错误信息
        System.out.println("Broadcast Task ID: " + broadResult.getTaskId());
        broadResult.getBroadcastErrorResults().forEach(error -> {
            System.out.println("Error Code: " + error.getErrorCode());
            System.out.println("Target: " + error.getTargetValue());
        });
    }

    /**
     * 上传大图
     * @throws Exception 如果上传失败则抛出异常
     */
    public void uploadBigPicture() throws Exception {
        Sender sender = createSender();  // 创建 Sender 实例
        File bigPicture = new File("path/to/large_picture.jpg");  // 设置大图文件路径
        int bigPictureTtl = 86400;  // 图片过期时间(秒)

        // 上传大图
        Result uploadResult = sender.uploadBigPicture(bigPictureTtl, bigPicture);
        String bigPictureId = uploadResult.getBigPictureId();

        // 打印大图ID
        System.out.println("Big Picture ID: " + bigPictureId);
    }

    /**
     * 上传小图
     * @throws Exception 如果上传失败则抛出异常
     */
    public void uploadSmallPicture() throws Exception {
        Sender sender = createSender();  // 创建 Sender 实例
        File smallPicture = new File("path/to/small_picture.jpg");  // 设置小图文件路径
        int smallPictureTtl = 86400;  // 图片过期时间(秒)

        // 上传小图
        Result uploadResult = sender.uploadSmallPicture(smallPictureTtl, smallPicture);
        String smallPictureId = uploadResult.getSmallPictureId();

        // 打印小图ID
        System.out.println("Small Picture ID: " + smallPictureId);
    }

    /**
     * 主方法,演示如何使用 OPPO 推送 SDK
     * @param args 命令行参数
     * @throws Exception 如果执行过程中出现异常
     */
    public static void main(String[] args) throws Exception {
        OPPOPush oppoPush = new OPPOPush();

        // 示例:发送单推通知
        oppoPush.sendSingleNotification();

        // 示例:发送批量推送通知
        oppoPush.sendBatchNotification();

        // 示例:发送广播通知
        oppoPush.sendBroadcastNotification();

        // 示例:上传大图
        oppoPush.uploadBigPicture();

        // 示例:上传小图
        oppoPush.uploadSmallPicture();
    }
}

VIVO

vivo开放平台

image.png

<dependency>
    <groupId>com.vivo.push</groupId>
    <artifactId>sdk</artifactId>
    <version>3.3</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/vpush-server-sdk-3.3.jar</systemPath>
</dependency>
import com.vivo.push.sdk.notofication.Message;
import com.vivo.push.sdk.notofication.Result;
import com.vivo.push.sdk.notofication.TargetMessage;
import com.vivo.push.sdk.server.Sender;
import com.vivo.push.sdk.server.TagManage;
import com.vivo.push.sdk.tag.TagMessage;

import java.util.Set;
import java.util.Arrays;

public class VIVOPush {

    private Sender sender; // Sender 实例,用于发送推送请求
    private String authToken; // 鉴权令牌
    private final String appSecret; // 应用密钥

    /**
     * 构造函数
     * @param appSecret 应用密钥
     */
    public VIVOPush(String appSecret) throws Exception {
        this.appSecret = appSecret;
        this.sender = new Sender(appSecret); // 初始化 Sender 实例
    }

    /**
     * 初始化连接池
     * @param connection 最大连接数
     * @param route 连接池路由数
     */
    public void initPool(int connection, int route) throws Exception {
        sender.initPool(connection, route);
    }

    /**
     * 鉴权并获取 authToken
     * @param appId 应用 ID
     * @param appKey 应用密钥
     * @throws Exception 鉴权失败时抛出异常
     */
    public void authenticate(int appId, String appKey) throws Exception {
        // 获取鉴权令牌
        Result result = sender.getToken(appId, appKey);
        if (result.getResult() == 0) { // 鉴权成功
            this.authToken = result.getAuthToken(); // 设置 authToken
            sender.setAuthToken(authToken); // 将 authToken 设置到 Sender 实例
        } else {
            throw new Exception("Authentication failed: " + result.getDesc()); // 鉴权失败,抛出异常
        }
    }

    /**
     * 发送单条推送消息
     * @param regId 注册 ID
     * @param title 消息标题
     * @param content 消息内容
     * @param skipContent 跳转内容
     * @throws Exception 发送失败时抛出异常
     */
    public void sendSinglePush(String regId, String title, String content, String skipContent) throws Exception {
        // 构造消息对象
        Message message = new Message.Builder()
                .regId(regId) // 设置注册 ID
                .notifyType(3) // 通知类型
                .title(title) // 消息标题
                .content(content) // 消息内容
                .skipType(2) // 跳转类型
                .skipContent(skipContent) // 跳转内容
                .build();

        // 发送消息
        Result result = sender.sendSingle(message);
        handleResult(result); // 处理发送结果
    }

    /**
     * 批量推送消息
     * @param regIds 注册 ID 集合
     * @param taskId 任务 ID
     * @param requestId 请求 ID
     * @throws Exception 发送失败时抛出异常
     */
    public void sendBatchPush(Set<String> regIds, String taskId, String requestId) throws Exception {
        // 构造目标消息对象
        TargetMessage targetMessage = new TargetMessage.Builder()
                .regIds(regIds) // 设置注册 ID 集合
                .taskId(taskId) // 设置任务 ID
                .requestId(requestId) // 设置请求 ID
                .build();

        // 发送消息
        Result result = sender.sendToList(targetMessage);
        handleResult(result); // 处理发送结果
    }

    /**
     * 根据标签发送推送消息
     * @param tagName 标签名称
     * @param title 消息标题
     * @param content 消息内容
     * @throws Exception 发送失败时抛出异常
     */
    public void sendTagPush(String tagName, String title, String content) throws Exception {
        // 构造消息对象
        Message message = new Message.Builder()
                .orTags(Arrays.asList(tagName)) // 使用 Arrays.asList() 创建列表
                .notifyType(3) // 通知类型
                .title(title) // 消息标题
                .content(content) // 消息内容
                .build();

        // 发送消息
        Result result = sender.sendToTag(message);
        handleResult(result); // 处理发送结果
    }

    /**
     * 处理推送结果
     * @param result 结果对象
     */
    private void handleResult(Result result) {
        if (result.getResult() == 0) {
            System.out.println("Success: " + result.getTaskId()); // 处理成功结果
        } else {
            System.out.println("Error: " + result.getDesc()); // 处理错误结果
        }
    }

    /**
     * 添加新标签
     * @param tagName 标签名称
     * @param description 标签描述
     * @throws Exception 添加标签失败时抛出异常
     */
    public void addTag(String tagName, String description) throws Exception {
        TagManage tagManage = new TagManage(appSecret);
        tagManage.setAuthToken(authToken); // 设置 authToken
        TagMessage tagMessage = new TagMessage.Builder()
                .name(tagName)
                .desc(description)
                .build();

        // 添加标签
        Result result = tagManage.addTag(tagMessage);
        handleResult(result); // 处理结果
    }

    /**
     * 更新标签信息
     * @param oldName 旧标签名称
     * @param newName 新标签名称
     * @param description 标签描述
     * @throws Exception 更新标签失败时抛出异常
     */
    public void updateTag(String oldName, String newName, String description) throws Exception {
        TagManage tagManage = new TagManage(appSecret);
        tagManage.setAuthToken(authToken); // 设置 authToken
        TagMessage tagMessage = new TagMessage.Builder()
                .oldName(oldName)
                .newName(newName)
                .desc(description)
                .build();

        // 更新标签
        Result result = tagManage.updateTag(tagMessage);
        handleResult(result); // 处理结果
    }

    /**
     * 将用户添加到标签中
     * @param tagName 标签名称
     * @param regIds 注册 ID 集合
     * @throws Exception 添加用户到标签失败时抛出异常
     */
    public void addUsersToTag(String tagName, Set<String> regIds) throws Exception {
        TagManage tagManage = new TagManage(appSecret);
        tagManage.setAuthToken(authToken); // 设置 authToken
        TagMessage tagMessage = new TagMessage.Builder()
                .name(tagName)
                .type(1) // 1 表示添加用户
                .ids(regIds)
                .build();

        // 添加用户到标签
        Result result = tagManage.addMembers(tagMessage);
        handleResult(result); // 处理结果
    }

    /**
     * 从标签中移除用户
     * @param tagName 标签名称
     * @param regIds 注册 ID 集合
     * @throws Exception 移除用户失败时抛出异常
     */
    public void removeUsersFromTag(String tagName, Set<String> regIds) throws Exception {
        TagManage tagManage = new TagManage(appSecret);
        tagManage.setAuthToken(authToken); // 设置 authToken
        TagMessage tagMessage = new TagMessage.Builder()
                .name(tagName)
                .type(2) // 2 表示移除用户
                .ids(regIds)
                .build();

        // 从标签中移除用户
        Result result = tagManage.removeMembers(tagMessage);
        handleResult(result); // 处理结果
    }

    public static void main(String[] args) {
        try {
            // 初始化 VIVOPush 实例
            VIVOPush push = new VIVOPush("你的AppSecret"); // 替换为实际的 AppSecret
            push.authenticate(105763583, "445367a52c6ec4ec385ba2a6641bd9ea"); // 替换为实际的 AppId 和 AppKey

            // 发送单条推送消息
            push.sendSinglePush("测试设备的regId", "试标题", "试内容", "http://www.vivo.com"); // 替换为实际的 regId

            // 发送标签推送消息
            push.sendTagPush("testTag", "试标题", "试内容");

            // 你可以根据需要调用其他方法,例如添加或更新标签
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

小米

小米开放平台 (mi.com)

image.png

<dependency>
    <groupId>com.xiaomi</groupId>
    <artifactId>sdk</artifactId>
    <version>2_1.0.14</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/MiPush_SDK_Server_Http2_1.0.14.jar</systemPath>
</dependency>

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version> <!-- 使用最新版本 -->
</dependency>
import com.xiaomi.xmpush.server.*;

import java.util.ArrayList;
import java.util.List;

public class XiaomiPush {
    private String appSecretKey;
    private Sender sender;

    public XiaomiPush(String appSecretKey) {
        this.appSecretKey = appSecretKey;
        Constants.useOfficial(); // 使用正式环境
        this.sender = new Sender(appSecretKey);
    }

    /**
     * 发送单条消息到指定设备
     * @param regId 目标设备的regId
     * @param title 消息标题
     * @param description 消息描述
     * @param payload 消息内容
     * @param notifyType 通知类型
     * @throws Exception 发送失败时抛出异常
     */
    public void sendMessage(String regId, String title, String description, String payload, int notifyType) throws Exception {
        Message message = new Message.Builder()
                .title(title)
                .description(description)
                .payload(payload)
                .restrictedPackageName("com.example.app") // 替换为你的包名
                .notifyType(notifyType)
                .build();

        Result result = sender.send(message, regId, 3);
        System.out.println("Server response: " +
                "MessageId: " + result.getMessageId() +
                " ErrorCode: " + result.getErrorCode().toString() +
                " Reason: " + result.getReason());
    }

    /**
     * 发送消息到多个设备
     * @param regIds 目标设备的regIds列表
     * @param title 消息标题
     * @param description 消息描述
     * @param payload 消息内容
     * @param notifyType 通知类型
     * @throws Exception 发送失败时抛出异常
     */
    public void sendMessages(List<String> regIds, String title, String description, String payload, int notifyType) throws Exception {
        Message message = new Message.Builder()
                .title(title)
                .description(description)
                .payload(payload)
                .restrictedPackageName("com.example.app") // 替换为你的包名
                .notifyType(notifyType)
                .build();

        Result result = sender.send(message, regIds, 3);
        System.out.println("Server response: " +
                "MessageId: " + result.getMessageId() +
                " ErrorCode: " + result.getErrorCode().toString() +
                " Reason: " + result.getReason());
    }

    /**
     * 发送消息到指定的别名
     * @param alias 目标设备的别名
     * @param title 消息标题
     * @param description 消息描述
     * @param payload 消息内容
     * @param notifyType 通知类型
     * @throws Exception 发送失败时抛出异常
     */
    public void sendMessageToAlias(String alias, String title, String description, String payload, int notifyType) throws Exception {
        Message message = new Message.Builder()
                .title(title)
                .description(description)
                .payload(payload)
                .restrictedPackageName("com.example.app") // 替换为你的包名
                .notifyType(notifyType)
                .build();

        Result result = sender.sendToAlias(message, alias, 3);
        System.out.println("Server response: " +
                "MessageId: " + result.getMessageId() +
                " ErrorCode: " + result.getErrorCode().toString() +
                " Reason: " + result.getReason());
    }

    /**
     * 发送消息到多个别名
     * @param aliases 目标设备的别名列表
     * @param title 消息标题
     * @param description 消息描述
     * @param payload 消息内容
     * @param notifyType 通知类型
     * @throws Exception 发送失败时抛出异常
     */
    public void sendMessagesToAliases(List<String> aliases, String title, String description, String payload, int notifyType) throws Exception {
        Message message = new Message.Builder()
                .title(title)
                .description(description)
                .payload(payload)
                .restrictedPackageName("com.example.app") // 替换为你的包名
                .notifyType(notifyType)
                .build();

        Result result = sender.sendToAlias(message, aliases, 3);
        System.out.println("Server response: " +
                "MessageId: " + result.getMessageId() +
                " ErrorCode: " + result.getErrorCode().toString() +
                " Reason: " + result.getReason());
    }

    /**
     * 发送定时消息到指定设备
     * @param regId 目标设备的regId
     * @param title 消息标题
     * @param description 消息描述
     * @param payload 消息内容
     * @param notifyType 通知类型
     * @param delayMilliseconds 延迟时间(毫秒)
     * @throws Exception 发送失败时抛出异常
     */
    public void sendScheduledMessage(String regId, String title, String description, String payload, int notifyType, long delayMilliseconds) throws Exception {
        Message message = new Message.Builder()
                .title(title)
                .description(description)
                .payload(payload)
                .restrictedPackageName("com.example.app") // 替换为你的包名
                .notifyType(notifyType)
                .timeToSend(System.currentTimeMillis() + delayMilliseconds)
                .build();

        Result result = sender.send(message, regId, 3);
        System.out.println("Server response: " +
                "MessageId: " + result.getMessageId() +
                " ErrorCode: " + result.getErrorCode().toString() +
                " Reason: " + result.getReason());
    }

    public static void main(String[] args) {    
        try {
            XiaomiPush push = new XiaomiPush("你的AppSecret"); // 替换为实际的 AppSecret

            // 发送单条消息
            push.sendMessage("测试设备的regId", "测试标题", "测试内容", "这是一条消息", 1);

            // 发送多条消息
            List<String> regIds = new ArrayList<>();
            regIds.add("设备regId1");
            regIds.add("设备regId2");
            push.sendMessages(regIds, "测试标题", "测试内容", "这是一条消息", 1);

            // 发送到别名
            push.sendMessageToAlias("testAlias", "测试标题", "测试内容", "这是一条消息", 1);

            // 发送到多个别名
            List<String> aliases = new ArrayList<>();
            aliases.add("别名1");
            aliases.add("别名2");
            push.sendMessagesToAliases(aliases, "测试标题", "测试内容", "这是一条消息", 1);

            // 发送定时消息
            push.sendScheduledMessage("测试设备的regId", "测试标题", "测试内容", "这是一条消息", 1, 3600000); // 1小时后发送

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

荣耀HONOR

集成荣耀推送 - IM 即时通讯 (163.com)

魅族

魅族开放平台 (flyme.cn)

image.png

<!-- meizu -->
<dependency>
    <groupId>com.meizu.push</groupId>
    <artifactId>sdk</artifactId>
    <version>1.2.10.20230811_release</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/push-server-sdk-1.2.10.20230811_release.jar</systemPath>
</dependency>
import com.meizu.push.sdk.server.*;
import com.meizu.push.sdk.server.constant.ResultPack;
import com.meizu.push.sdk.server.model.push.PushResult;
import com.meizu.push.sdk.server.model.push.VarnishedMessage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FlymePush {
    public static final int APP_ID = APP_ID;

    public static final String APP_KEY = "APP_KEY";

    public static final String APP_SECRET = "APP_SECRET";

    // 需要推送用户的注册di
    public static final String REGIS_ID = "REGIS_ID";

    public static void main(String[] args) {
        doMeizuPush();
    }

    /**
     * 组装消息
     *
     * @param appId
     * @param title
     *            标题
     * @param content
     *            内容
     * @return
     */
    public static VarnishedMessage buildMessage(Long appId, String title, String content) {
        return new VarnishedMessage.Builder().appId(appId).title(title).content(content).build();
    }

    public static void doMeizuPush() {
        // 推送对象
        final IFlymePush push = new IFlymePush(APP_SECRET);
        // 目标用户
        List<String> pushIds = new ArrayList<String>();
        pushIds.add(REGIS_ID);
        // 1 调用推送服务
        ResultPack<PushResult> result;
        try {
            result = push.pushMessage(buildMessage(Long.valueOf(APP_ID), "title", "content"), pushIds, 3);
            if (result.isSucceed()) {
                // 2 调用推送服务成功 (其中map为设备的具体推送结果,一般业务针对超速的code类型做处理)
                PushResult pushResult = result.value();
                // 推送消息ID,用于推送流程明细排查
                String msgId = pushResult.getMsgId();
                // 推送结果,全部推送成功,则map为empty
                Map<String, List<String>> targetResultMap = pushResult.getRespTarget();
                if (targetResultMap != null && !targetResultMap.isEmpty()) {
                    System.out.println("Meizu Push fail, token: " + targetResultMap);
                }
                System.out.println(String.format(
                        "Meizu Push Over -> regisId: {}, data: {}, code: {}, messageId:{}, message: {}.", REGIS_ID,
                        result.toString(), result.code(), msgId, result.comment()));
            } else {
                // 调用推送接口服务异常 eg: appId、appKey非法、推送消息非法.....
                // result.code(); //服务异常码
                // result.comment();//服务异常描述
                System.out.println(String.format("meizu pushMessage error code:%scomment:%s", result.code(), result.comment()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

华为

java版服务端接入华为消息推送3.0接口_华为push接口对接-CSDN博客

hms-push-serverdemo-java: 华为推送服务服务端Java示例代码,对华为推送的服务端接口进行封装,包含丰富的示例程序,方便您参考或直接使用。 (gitee.com)

服务端示例代码-推送服务 - 华为HarmonyOS开发者 (huawei.com)

<!-- huawei -->
<dependency>
    <groupId>com.huawei.push</groupId>
    <artifactId>sdk</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/libs/push.java.sample-1.0.jar</systemPath>
</dependency>

image.png

import com.alibaba.fastjson.JSONObject;
import com.huawei.push.android.AndroidNotification;
import com.huawei.push.android.BadgeNotification;
import com.huawei.push.android.ClickAction;
import com.huawei.push.android.Color;
import com.huawei.push.android.LightSettings;
import com.huawei.push.exception.HuaweiMesssagingException;
import com.huawei.push.message.AndroidConfig;
import com.huawei.push.message.Message;
import com.huawei.push.message.Notification;
import com.huawei.push.messaging.HuaweiApp;
import com.huawei.push.messaging.HuaweiCredential;
import com.huawei.push.messaging.HuaweiMessaging;
import com.huawei.push.messaging.HuaweiOption;
import com.huawei.push.model.Urgency;
import com.huawei.push.model.Importance;
import com.huawei.push.model.Visibility;
import com.huawei.push.reponse.SendResponse;
import com.huawei.push.util.InitAppUtils;

import java.util.ResourceBundle;

public class HuaweiPush {

    public void sendTestMessage() throws HuaweiMesssagingException {
        HuaweiApp app = initializeApp();
        HuaweiMessaging huaweiMessaging = HuaweiMessaging.getInstance(app);

        Notification notification = Notification.builder().setTitle("sample title")
                .setBody("sample message body")
                .build();

        JSONObject multiLangKey = new JSONObject();
        JSONObject titleKey = new JSONObject();
        titleKey.put("en","好友请求");
        JSONObject bodyKey = new JSONObject();
        bodyKey.put("en","My name is %s, I am from %s.");
        multiLangKey.put("key1", titleKey);
        multiLangKey.put("key2", bodyKey);

        LightSettings lightSettings = LightSettings.builder().setColor(Color.builder().setAlpha(0f).setRed(0f).setBlue(1f).setGreen(1f).build())
                .setLightOnDuration("3.5")
                .setLightOffDuration("5S")
                .build();

        AndroidNotification androidNotification = AndroidNotification.builder().setIcon("/raw/ic_launcher2")
                .setColor("#AACCDD")
                .setSound("/raw/shake")
                .setDefaultSound(true)
                .setTag("tagBoom")
                .setClickAction(ClickAction.builder().setType(2).setUrl("https://www.huawei.com").build())
                .setBodyLocKey("key2")
                .addBodyLocArgs("boy").addBodyLocArgs("dog")
                .setTitleLocKey("key1")
                .addTitleLocArgs("Girl").addTitleLocArgs("Cat")
                .setChannelId("Your Channel ID")
                .setNotifySummary("some summary")
                .setMultiLangkey(multiLangKey)
                .setStyle(1)
                .setBigTitle("Big Boom Title")
                .setBigBody("Big Boom Body")
                .setAutoClear(86400000)
                .setNotifyId(486)
                .setGroup("Group1")
                .setImportance(Importance.LOW.getValue())
                .setLightSettings(lightSettings)
                .setBadge(BadgeNotification.builder().setAddNum(1).setBadgeClass("Classic").build())
                .setVisibility(Visibility.PUBLIC.getValue())
                .setForegroundShow(true)
                .build();

        AndroidConfig androidConfig = AndroidConfig.builder().setCollapseKey(-1)
                .setUrgency(Urgency.HIGH.getValue())
                .setTtl("10000s")
                .setBiTag("the_sample_bi_tag_for_receipt_service")
                .setNotification(androidNotification)
                .build();

        Message message = Message.builder().setNotification(notification)
                .setAndroidConfig(androidConfig)
                .addToken("AND8rUp4etqJvbakK7qQoCVgFHnROXzH8o7B8fTl9rMP5VRFN83zU3Nvmabm3xw7e3gZjyBbp_wfO1jP-UyDQcZN_CtjBpoa7nx1WaVFe_3mqXMJ6nXJNUZcDyO_-k3sSw")
                .build();

        SendResponse response = huaweiMessaging.sendMessage(message, true);
    }

    public static HuaweiApp initializeApp() {
        String appId = ResourceBundle.getBundle("url").getString("appid");//appid
        String appSecret = ResourceBundle.getBundle("url").getString("appsecret");//appsecret
        return initializeApp(appId, appSecret);
    }

    private static HuaweiApp initializeApp(String appId, String appSecret) {
        HuaweiCredential credential = HuaweiCredential.builder().setAppId(appId).setAppSecret(appSecret).build();
        HuaweiOption option = HuaweiOption.builder().setCredential(credential).build();
        return HuaweiApp.getInstance(option);
    }
}