以下为修改后的官网示例代码,注意红色部分。
//发送Push消息
private void sendPushMessage(int IsPassThrough,String packageName,String appSecret,String appId,
List regIdList,String title, String content) throws IOException{
if (tokenExpiredTime <= System.currentTimeMillis()){
refreshToken(appSecret,appId);
}
JSONArray deviceTokens = new JSONArray();//目标设备Token
if(regIdList != null){
for (int i=0;i
deviceTokens.add(regIdList.get(i));
}
}
JSONObject body = new JSONObject();//仅通知栏消息需要设置标题和内容,透传消息key和value为用户自定义
body.put("title",title);//消息标题
body.put("content",content);//消息内容体
JSONObject param = new JSONObject();
param.put("appPkgName",packageName);//定义需要打开的appPkgName
JSONObject action = new JSONObject();
action.put("type", 3);//类型3为打开APP,其他行为请参考接口文档设置
action.put("param", param);//消息点击动作参数
JSONObject msg = new JSONObject();
msg.put("type", IsPassThrough);//1:透传异步消息,3:通知栏消息
msg.put("action", action);//消息点击动作
msg.put("body", body);//通知栏消息body内容
JSONObject ext = new JSONObject();//扩展信息,含BI消息统计,特定展示风格,消息折叠。
ext.put("biTag", "Trump");//设置消息标签,如果带了这个标签,会在回执中推送给CP用于检测某种类型消息的到达率和状态
ext.put("icon", "");//自定义推送消息在通知栏的图标,value为一个公网可以访问的URL
JSONArray mCustomizes = new JSONArray();
JSONObject customize = new JSONObject();
customize.put("pushNotifyId","6000");
mCustomizes.add(customize);
ext.put("customize",mCustomizes);
JSONObject hps = new JSONObject();//华为PUSH消息总结构体
hps.put("msg", msg);
hps.put("ext", ext);
System.out.print("hps.toString() = " + hps.toString());
JSONObject payload = new JSONObject();
payload.put("hps", hps);
String postBody = MessageFormat.format(
"access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
URLEncoder.encode(accessToken,"UTF-8"),
URLEncoder.encode("openpush.message.api.send","UTF-8"),
URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000),"UTF-8"),
URLEncoder.encode(deviceTokens.toString(),"UTF-8"),
URLEncoder.encode(payload.toString(),"UTF-8"));
String postUrl = apiUrl + "?nsp_ctx=" + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + appId + "\"}", "UTF-8");
httpPost(postUrl, postBody, 5000, 5000);
}