Java中使用友盟消息推送
U-Push可以实现主动推送消息给App的终端用户,让用户实时实地的获取相关信息并拉活相应的app,那么如何在java中使用友盟U-Push 消息推送呢?
首先进入友盟官网去创建添加一个应用,以获取应用对应的Appkey和Umeng Message Secret。
然后进入开发者中心下载集成示例:
解压后,可以看到demo文件,以android广播推送为例,我们需要:
应用的appkey和appMasterSecret,DeviceToken 设备标识,Ticker 通知栏提示文字,Title 标题以及点击后显示的文字Text。
public void sendAndroidBroadcast() throws Exception {
AndroidBroadcast broadcast = new AndroidBroadcast(appkey,appMasterSecret);
broadcast.setTicker( "Android broadcast ticker");
broadcast.setTitle( "中文的title");
broadcast.setText( "Android broadcast text");
broadcast.goAppAfterOpen();
broadcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
// TODO Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
broadcast.setProductionMode();
client.send(broadcast);
}
那怎么在用户点击后显示图片等等附带数据呢?消息推送的有效期怎么设置?推送任务自动生成的id又怎么获取?
自定义接收类UmengResult
@Getter
@Setter
public class UmengResult {
private String ret;
private JSONObject data;
}
demo中,sendAndroidBroadcast()
public void sendAndroidBroadcast() throws Exception {
AndroidBroadcast broadcast = new AndroidBroadcast(appkey,appMasterSecret);
broadcast.setTicker( "Android broadcast ticker");
broadcast.setTitle( "中文的title");
broadcast.setText( "Android broadcast text");
broadcast.goAppAfterOpen();//默认点击消息拉活app
broadcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
broadcast.setProductionMode();//生产模式,一开始改成测试避免手滑哦
//可以使用setCustomField()给客户端推送附加数据
JSONObject extraData = new JSONObject();
extraData.put("img","imgUrl");
extraData.put("source",new source());
broadcast.setCustomField(extraData);
//设置推送的有效期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.add(Calendar.MINUTE, 1);
broadcast.setStartTime(sdf.format(c1.getTime()));
// 友盟推送的有效期延迟一天
c2.add(Calendar.DAY_OF_MONTH, 1);
broadcast.setExpireTime(sdf.format(c2.getTime()));
String result = client.send(broadcast);
//获取推送消息的任务id
UmengResult umengResult = JSON.parseObject(status.toString(), UmengResult.class);
String taskid = umengResult.getData().get("task_id").toString();
}
消息推送出去了,那怎么获取消息的状态,多少客户端收到推送消息,又有多少的点击量呢?
查阅api文档,可以看到获取任务状态的api为 '/api/status',需要以下参数
{
"appkey":"xx", // 必填, 应用唯一标识
"timestamp":"xx", // 必填, 时间戳,10位或者13位均可,时间戳有效期为10分钟
"task_id":"xx" // 必填, 消息发送时, 从返回消息中获取的task_id
}
打开pushClient.java,自定义我们获取状态的方法,代码如下:
protected static final String statusPath = "/api/status";
public String getPushStatus(String appkey,String task_id,String appMasterSecret) throws Exception {
JSONObject getStatus = new JSONObject();
getStatus.put("appkey", appkey);
String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
getStatus.put("timestamp", timestamp);
getStatus.put("task_id",task_id);
String url = host + statusPath;
String postBody = getStatus.toString();
String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes(StandardCharsets.UTF_8));
url = url + "?sign=" + sign;
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
StringEntity se = new StringEntity(postBody, "UTF-8");
post.setEntity(se);
// Send the post request and get the response
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
示例接口
@RequestMapping(value = "/getStatus")
public CommonResult GetStatus(@RequestBody MessageInfo model) throws Exception {
PushClient pushClient = new PushClient();
String s = pushClient.getPushStatus(model.getAppId(), model.getUmengTaskId(), model.getSecret());
UmengResult umengResult = JSON.parseObject(s, UmengResult.class);
//推送接收统计数目
model.setSendCount((Integer) umengResult.getData().get("sent_count"));
//推送打开统计数目
model.setOpenCount((Integer) umengResult.getData().get("open_count"));
//推送被忽略统计数目
model.setDismissCount((Integer) umengResult.getData().get("dismiss_count"));
messageInfoService.update(model);
return processSuccess("更新成功");
}
至此,U-Push的推送和获取后续状态的实例就完成了,单播,组播都可以用类似写法。