一、功能描述
根據業務需求,對IOS APP定時推送消息,點選通知欄的推送内容,跳轉到APP内指定界面。
二、準備工作
1. 參照友盟消息推送官方文檔,擷取 appkey 和 appMasterSecret:
官方文檔連結:https://developer.umeng.com/docs/66632/detail/68343
我是在閱讀此官方文檔的基礎上進行內建的,現針對文檔上一些必要的幹貨和我踩過的坑和大家分享一下:
1). 必須擷取 Appkey 和 App Master Secret,IOS和java背景可以用一套,我們是項目經理幫着申請的。
2). 關于“IP白名單”:不是必須設定,我在內建的時候沒有管,都是預設狀态。
3). Device Token:IOS小夥伴在使用者登入的時候根據裝置擷取的,并發送給友盟,使用單點傳播或者列播的時候才需要此字段,但這兩種模式有一個bug,比如同一個裝置,用兩個不同的賬号登入過app,兩個賬号對應的推送消息該裝置都能接收到,不符合常理。是以、我開始和小夥伴用的這種方式,發現這個bug後果斷放棄了。
4). Alias:根據别名的方式推送消息,每一個裝置上接到的推送就是最後一個登入的賬号應該收到的消息。我采用的是這一種。setAlias(alias, alias_type),也是IOS小夥伴在登入的時候注冊到友盟的,比如我這邊和IOS小夥伴約定好了,alias取的就是userId的值,alias_type為“push”,後面代碼中有提到。
5). unicast、listcast、customizedcast等模式的選擇:鑒于3)/4)兩條的分析,我選擇的是customizedcast。
2. 相關jar包及類的導入:
如下,是我是在官網Java SDK v1.5(2015-11-13)的基礎上進行修改後的,僅供參考。
連結:https://pan.baidu.com/s/1_BUcSwcru01bC49apJdfxQ 提取碼:tvvr
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHLzEkaNRTWU5UNrRUT4V0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLzAjN2MDN1UTMzATMwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
三、實作示例
1. PushHandler.java
package com.test.push;
import java.util.HashMap;
import java.util.Map;
public class PushHandler {
private static PushClient client = new PushClient();
// setBadge 推送角标數
public static Map<String, Integer> badgeMap;
static {
badgeMap = new HashMap<String, Integer>();
}
public static Map<String, Integer> getbadgeMap() {
return badgeMap;
}
public static void setbadgeMap(Map<String, Integer> badgeMap) {
PushHandler.badgeMap = badgeMap;
}
/**
*
* @param userId
* @return
*/
public static int getBadge(String userId)
{
//條數統計
String badgeKey = userId;
if(badgeMap.get(badgeKey) == null){
badgeMap.put(badgeKey, 0);
}
int badge = badgeMap.get(badgeKey);
return badge;
}
/**
*
* @param userId
* @param badge
* @return
*/
public static int setBadge(String userId,int badge)
{
//條數統計
String BadgeKey = userId;
badge++;
badgeMap.put(BadgeKey, badge);
return badge;
}
/**
* 自定義播(customizedcast):開發者通過自有的alias進行推送,可以針對單個或者一批alias進行推送,也可以将alias存放到檔案進行發送。
*
* @param alias
* @param description
* @throws Exception
*/
public static void sendIOSCustomizedcast(String alias, String description,String page) throws Exception {
IOSCustomizedcast customizedcast = new IOSCustomizedcast("你的appkey",
"你的appMasterSecret");
customizedcast.setAlias(alias, "push");
customizedcast.setAlert(description);
customizedcast.setPage(page);
// customizedcast.setBody(description);
//發送,角标+1
customizedcast.setBadge(getBadge(alias)+1);
customizedcast.setSound("default");
// TODO set 'production_mode' to 'true' if your app is under production
customizedcast.setTestMode();
System.out.println("==iosSend:" + customizedcast.getPostBody());
client.send(customizedcast);
//設定腳标+1;
setBadge(alias,getBadge(alias));
}
public static void main(String[] args) throws Exception {
sendIOSCustomizedcast("IOS小夥伴注冊的alias别名","你收到我的推送了嗎?記得多喝熱水。","");
}
}
1.PushClient.java
package com.test.push;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class PushClient {
// The user agent
protected final String USER_AGENT = "Mozilla/5.0";
// This object is used for sending the post request to Umeng
protected HttpClient client = new DefaultHttpClient();
// The host
protected static final String host = "http://msg.umeng.com";
// The upload path
protected static final String uploadPath = "/upload";
// The post path
protected static final String postPath = "/api/send";
public boolean send(UmengNotification msg) throws Exception {
// String timestamp1 = Integer.toString((int)(System.currentTimeMillis()/1000));
URL timeUrl = new URL("https://www.baidu.com/");// 取得百度資源對象
URLConnection uc = timeUrl.openConnection();// 生成連接配接對象
uc.connect();// 發出連接配接
String timestamp = Integer.toString((int) (uc.getDate() / 1000));
msg.setPredefinedKeyValue("timestamp", timestamp);
String url = host + postPath;
String postBody = msg.getPostBody();
String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
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);
int status = response.getStatusLine().getStatusCode();
System.out.println("Response Code : " + status);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
if (status == 200) {
System.out.println("Notification sent successfully.");
} else {
System.out.println("Failed to send the notification!");
}
return true;
}
// Upload file with device_tokens to Umeng
public String uploadContents(String appkey, String appMasterSecret, String contents) throws Exception {
// Construct the json string
JSONObject uploadJson = new JSONObject();
uploadJson.put("appkey", appkey);
String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
uploadJson.put("timestamp", timestamp);
uploadJson.put("content", contents);
// Construct the request
String url = host + uploadPath;
String postBody = uploadJson.toString();
String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
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);
}
System.out.println(result.toString());
// Decode response string and get file_id from it
JSONObject respJson = new JSONObject(result.toString());
String ret = respJson.getString("ret");
if (!ret.equals("SUCCESS")) {
throw new Exception("Failed to upload file");
}
JSONObject data = respJson.getJSONObject("data");
String fileId = data.getString("file_id");
// Set file_id into rootJson using setPredefinedKeyValue
return fileId;
}
}
四、測試
下載下傳第二項中提到的連結檔案pushDemo.zip,導入eclipse,打開PushHandler.java,執行main()方法,發送成功後,控制台如下: