当前位置: 首页>后端>正文

java主动给前端推页面 java后端推送消息给app

一、功能描述

根据业务需求,对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)的基础上进行修改后的,仅供参考。

java主动给前端推页面 java后端推送消息给app,java主动给前端推页面 java后端推送消息给app_System,第1张

三、实现示例

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()方法,发送成功后,控制台如下:

java主动给前端推页面 java后端推送消息给app,java主动给前端推页面 java后端推送消息给app_System_02,第2张



https://www.xamrdz.com/backend/38r1932831.html

相关文章: