uni app push 发送透传通知 支持安卓和苹果(最终版)

后台

package co.yixiang.common.utils;

import co.yixiang.modules.yinsheng.utils.StringUtil;
import co.yixiang.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.notify.Notify;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.dto.GtReq;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

import java.io.IOException;
import java.util.*;

public class UniPushUtil {
    // STEP1:获取应用基本信息
    private static String appId = "";
    private static String appKey = "";
    private static String masterSecret = "";
    private static String url = "http://sdk.open.api.igexin.com/apiex.htm";

    public static boolean uniPush(String title,String content,Integer type,Integer contentId){
        Map map=new HashMap();
        map.put("type",type);
        map.put("contentId",contentId);
        map.put("title",title);
        map.put("content",content);

        JSONObject jsonObj=new JSONObject(map);
        String s = jsonObj.toString();


        IGtPush push = new IGtPush(url, appKey, masterSecret);

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(2);// // 透传消息设置;1:立即启动APP;2:客户端收到消息后需要自行处理,如果设置为1,对用户使用不友好,不推荐使用
        template.setTransmissionContent(s);


        Notify notify = new Notify();
        notify.setTitle(title);
        notify.setContent(content);
        notify.setIntent("intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=uni.UNI91FE773/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload="+s+";end");
        notify.setType(GtReq.NotifyInfo.Type._intent);

        template.set3rdNotifyInfo(notify);//设置第三方通知



        APNPayload apnpayload = new APNPayload();
        apnpayload.setSound("");
        apnpayload.setAlertMsg(getDictionaryAlertMsg((String)map.get("title"),(String)map.get("content")));
        Set<Map.Entry<String, Object>> set = map.entrySet();
        for (Map.Entry<String, Object> entry:set) {
            apnpayload.addCustomMsg(entry.getKey(),entry.getValue());
        }

        template.setAPNInfo(apnpayload);

        List<String> appIds = new ArrayList<String>();
        appIds.add(appId);
        AppMessage message = new AppMessage();
        message.setData(template);
        message.setAppIdList(appIds);
        message.setOffline(true);
        message.setOfflineExpireTime(1000 * 600);  // 时间单位为毫秒

        IPushResult ret = push.pushMessageToApp(message);
        String result = (String)ret.getResponse().get("result");
        return StringUtils.equals(result,"ok")?true:false;
        //System.out.println(ret.getResponse().toString());
    }

    public static void main(String[] args) throws IOException {
        String title="我是标题9";
        String content="我是内容9";

        Integer type=0;
        Integer contentId=311;


        Map map=new HashMap();
        map.put("type",type);
        map.put("contentId",contentId);
        map.put("title",title);
        map.put("content",content);

        JSONObject jsonObj=new JSONObject(map);
        String s = jsonObj.toString();


        IGtPush push = new IGtPush(url, appKey, masterSecret);

        /*Style0 style = new Style0();
        style.setTitle(title);
        style.setText(content);
        style.setRing(true);  // 设置响铃
        style.setVibrate(true);  // 设置震动*/

        // STEP4:选择通知模板
        /*StartActivityTemplate template = new StartActivityTemplate ();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setStyle(style);
        String intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=uni.UNI91FE773/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload="+s+";end";
        template.setIntent(intent);*/

        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(2);// // 透传消息设置;1:立即启动APP;2:客户端收到消息后需要自行处理,如果设置为1,对用户使用不友好,不推荐使用
        template.setTransmissionContent(s);
        

        Notify notify = new Notify();
        notify.setTitle(title);
        notify.setContent(content);
        notify.setIntent("intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=uni.UNI91FE773/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload="+s+";end");
        notify.setType(GtReq.NotifyInfo.Type._intent);

        template.set3rdNotifyInfo(notify);//设置第三方通知



        APNPayload apnpayload = new APNPayload();
        apnpayload.setSound("");

        //apnpayload.setAlertMsg(new APNPayload.SimpleAlertMsg("hello"));
        apnpayload.setAlertMsg(getDictionaryAlertMsg((String)map.get("title"),(String)map.get("content")));

        //传送的附加信息,用于解析
        /*apnpayload.addCustomMsg("info","测试参数");
        apnpayload.addCustomMsg("info1","测试参数2");*/
        Set<Map.Entry<String, Object>> set = map.entrySet();
        for (Map.Entry<String, Object> entry:set) {
            apnpayload.addCustomMsg(entry.getKey(),entry.getValue());
        }

        template.setAPNInfo(apnpayload);

        // STEP5:定义"AppMessage"类型消息对象,设置推送消息有效期等推送参数
        List<String> appIds = new ArrayList<String>();
        appIds.add(appId);
        AppMessage message = new AppMessage();
        message.setData(template);
        message.setAppIdList(appIds);
        message.setOffline(true);
        message.setOfflineExpireTime(1000 * 600);  // 时间单位为毫秒
       /* try {
            message.setPushTime("202110211505");
        } catch (ParseException e) {
            e.printStackTrace();
        }*/

        // STEP6:执行推送
        IPushResult ret = push.pushMessageToApp(message);
        System.out.println(ret.getResponse().toString());
    }

    /**
     * 苹果消息文字设置
     * @return
     */
    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title,String body){
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();

        alertMsg.setTitle(title);
        alertMsg.setBody(body);

        alertMsg.setActionLocKey("ActionLockey");
        //显示关闭和查看两个按钮的消息;
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image");
        // iOS8.2以上版本支持
        alertMsg.setTitleLocKey("TitleLocKey");
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }
}

uni app 端

//#ifdef APP-PLUS
	plus.push.addEventListener("click", function(msg) {  
		//console.log("click:"+JSON.stringify(msg));  
		//console.log(msg.payload);
		if(msg.payload.type==0){
          setTimeout(function() {
				uni.navigateTo({
					url:"/pages/shop/GoodsCon/index?id="+msg.payload.contentId,
				})
			}, 1000)
		}else{
			setTimeout(function() {
				uni.navigateTo({
					url:"/pages/shop/news/NewsDetail/index?id="+msg.payload.contentId,
				})
			}, 1000) 
		}
		//获得个推用户信息
		//let pinf = plus.push.getClientInfo();
		//console.log("pinf:"+JSON.stringify(pinf));
	}, false);
	plus.push.addEventListener("receive", function(msg) {   
		//console.log("receive:"+JSON.stringify(msg));
		//console.log(msg.payload);
		
		//获得个推用户信息
		//let pinf = plus.push.getClientInfo();
		//console.log("pinf:"+JSON.stringify(pinf));
		var platform = uni.getSystemInfoSync().platform;
		if(platform == "ios"){
			//ios平台应用在前台时,不能收到通知消息,只能走透传,在创建一条本地消息
			if (msg.type == "receive"){// 这里判断触发的来源,否则一直推送。
				var content = JSON.parse(msg.content); 
				plus.push.createMessage(content.content, JSON.stringify(msg.payload), { title: content.title });
			}
		}else if (platform == 'android'){
			//console.log("content:"+msg.content);
			//console.log("title:"+msg.title);
			plus.push.createMessage(msg.content, JSON.stringify(msg.payload), { title: msg.title });
			/* var options = {cover:false};
			var str = ":欢迎使用Html5 Plus创建本地消息!";
			plus.push.createMessage(str, "LocalMSG", options); */
		}
	}, false); 
	plus.push.getClientInfoAsync((info) => {  
	     let cid = info["clientid"];
		 console.log("cid:"+cid);
	});
	// #endif

前端代码放在 App.vue -> onLaunch 方法内

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值