uniapp uses unipush to push and java background push code (including local packaged apk to use unipush to push)

You know, it is used in the project again. As a programmer, he has no hesitation and needs to "evolve" regularly, and write it hard. Although he has written a lot of pushes as an android developer, the pushes of uniapp are also different. Record it. For future use.

First of all, uniapp's push uniPush is an integrated unified push service launched by DCloud and Getui Company, that is, you don't have to choose, just push.

Secondly, unipush is divided into version 1.0 and version 2.0. This is very important. It is a completely different concept. Don't think it is just a simple upgraded version.

Version 1.0: It is a traditional push method. Both the client and the server need to integrate the push service, and the server sends a request to the push server to operate the relevant push function.

Version 2.0: There is no such thing as your server. It is equivalent to the concept of cloud operation , that is, the integration of uniCloud and cloud. It is also an inevitable trend of uniapp cloud technology. It has powerful functions and comes with a web console. Since it is missing For the server, the natural process is simple.

So be sure to choose a reasonable version according to your business needs. I am also writing for the first time. I want to feel the new version. The result is almost finished and I realize that something is wrong. 2.0 is not suitable for my project needs this time, so I switched back to version 1.0. . So this article still introduces the use of version 1.0, and how to adjust it if your uniapp is packaged into an app based on local.

Let me talk about the use of unipush 1.0 under normal circumstances (non-packaged apk)

1. Open unipush push service

After you create a new uniapp project, select the App module configuration in manifest.json, and then check Push (message push) and the corresponding version, here is unipush 1.0

 Then click Configure to enter the Dcloud Developer Center

Here I will not introduce ios-related, so you can uncheck the IOS in the selection platform. Here you can see that you need to fill in the package name and signature.

Regarding packaging, if you are using cloud packaging

You can also see that your package name is actually uni. Your AppID is the thing circled above, fill it in the column of the package name, remember to check the use of the old Dcloud certificate when packaging. In this way, you can look at the introduction in the signature column of the developer center. Does it mean that if you use cloud packaging and an old version of the certificate, what to fill in the signature, it has already told you, copy the signature and fill in Enter the signature column.

Finally, click to activate the application, and a pop-up window will appear when the activation is successful.

 2. Push related knowledge

To write push, you must first understand push. Like traditional push or this kind of real-time delivery of a small amount of information (instant messaging), it is nothing more than:

1. The polling method, that is, regularly making http requests to check whether there is any news to be sent, this method is the most stupid method.

2. SMS, Hao, please feel free

3. Long connection, although long connection is mature now, but for mobile phones, this kind of performance consumption is still huge. After all, it is not a chat or a live broadcast.

Fortunately, mature third-party notifications have already appeared on the market, such as Jiguang Push, Alibaba Cloud Push, Getui, etc. I will not expand here, but just mention it. Because many people have been engaged in background or non-mobile web technology development, they don't know about mobile push, or even what push is.

As shown in the picture, there are various pop-up windows on the status bar of your mobile phone that you sometimes like and sometimes get tired of. They can be advertisements, update notifications, certain messages, or text messages, etc. And push does not just refer to pop-up windows, this pop-up window is a function that comes with android, that is, notification (notification), you can let your mobile phone pop up such pop-up windows without any push technology, and even bring various Icons, sound effects, vibration, etc. And the push is to transmit data to the mobile phone in real time, let the mobile phone know that I am going to start pop-up windows, what is the content displayed on the pop-up window, or what to do when clicking this pop-up window, understand the applause!

Secondly, let’s briefly talk about the push principle and technical architecture. I directly take the original image of unipush, and I can’t draw.

To put it bluntly, your mobile phone first establishes a connection with the unipush server (push server), which is basically established through a unique identification, which is the so-called clientId (cid) here. Then after your java server integrates the push service, you can call the API of the push server by sending a request to tell it that I want to push a xxx message to the mobile phone whose cid is xx, and the push server can push data to the mobile phone through the cid .

You have also seen that I am talking about mobile phones and equipment, not about a certain person or a certain account. Because the account is often a set of account system of our own server. So if you want a richer push method, or associate it with your own account system (you can also directly pass the cid device ID to your own server to bind), then you need a set of other push methods related to cid, which is derived Out of the alias (alias), label (tag). Some third-party push methods have richer methods, but they are similar, and generally have methods such as aliases and tags.

Alias ​​(alias), generally used to associate with your own account. It can be the user's account number, nickname, email address, or mobile phone number, depending on your own needs.

Tags are generally used for grouping your own account system, such as collective push for a certain type of users, or collective push for users under a certain group.

Finally, you need to understand that push is generally divided into two types, one is called notification, and the other is called message (unipush is called transparent transmission message here). The difference between the two is that one is just for reminding, and the other is for passing data or customizing business logic, styles, etc.

Notifications are relatively simple and crude. Generally, just pass a title and content, and then automatically display it on the mobile phone. For example, it is used to remind users that the software needs to be updated, you have new messages, new replies, etc. 

For transparent transmission messages, generally you can customize the data format, but json is mostly used. Secondly, after your mobile phone receives the transparent transmission message, it will not automatically pop up a window like a notification, but there is no response at all, just received the data , you need to pop up a pop-up window according to the business, or perform follow-up operations.

The push process is slightly different from other third-party pushes. You need to get the cid as soon as the app is running, and then write an interface in the Java background. The app passes the cid to the background server, and the background server performs the cid, alias, and label. to bind. After the user logs out, remember to unbind, otherwise, if there are multiple devices to log in with an account, there will be disordered pushes.

Well, it is enough to basically understand these. Keep on coding!

3. uniapp obtains clientId and establishes a connection with unipush

We should first get the clientId when the App runs for the first time, the code is as follows

getClient: (callback) => {
		// #ifdef APP-PLUS
		let clientInfo = plus.push.getClientInfo();  //获取 clientID
		uni.setStorageSync('clientid', clientInfo.clientid) //缓存到本地
		console.log(clientInfo);
		// #endif

}

4. Monitor the processing when receiving the push

In addition to obtaining the cid, we also need to configure how to process the received push messages. Some of the codes here are borrowed from others (I don’t know who exactly...), and add our own fine-tuning. Then put it in a js file unipush.js for convenience

export default {
	init: () => {
		// #ifdef APP-PLUS
		plus.push.setAutoNotification(true);  //设置通知栏显示通知 //必须设置
		plus.push.addEventListener("click", function(msg) {
			plus.push.clear(); //清空通知栏
			pushHandle(msg) //处理方法
		}, false);
		// 监听在线消息事件    
		plus.push.addEventListener("receive", function(msg) {			
			console.log("receive:"+JSON.stringify(msg));
			if (plus.os.name=='iOS') {  //由于IOS 必须要创建本地消息 所以做这个判断
				if (msg.payload&& msg.payload!=null&&msg.type=='receive') {
					console.log(msg);
					// {"title": "xxx","content": "xxx","payload": "xxx"} 符合这种 才会自动创建消息  文档地址https://ask.dcloud.net.cn/article/35622
					plus.push.createMessage(msg.title,msg.content,JSON.stringify(msg.payload))  //创建本地消息
				}
			}
			if (plus.os.name=='Android') {
				let options={
					cover:false,
					sound:"system",
					title:msg.title
				}
				plus.push.createMessage(msg.content,msg.payload.content,options);
				// if(!msg.title||!msg.content||!msg.payload){ //  不符合自动创建消息的情况
				// 	 //这里根据你消息字段来创建消息 
				// 	 console.log("这里根据你消息字段来创建消息:"+msg.title+","+msg.content+","+msg.payload);
				// 	plus.push.createMessage(msg.payload.content,JSON.stringify(msg.payload))  //创建本地消息
				// }else{
				// 	//符合自动创建消息 
				// 	console.log("符合自动创建消息"+msg.title+","+msg.content+","+msg.payload);
				// 	pushHandle(msg)
				// }	
			}
			 	
		}, false);
		// #endif
	},

	getClient: (callback) => {
		// #ifdef APP-PLUS
		let clientInfo = plus.push.getClientInfo();  //获取 clientID
		uni.setStorageSync('clientid', clientInfo.clientid)
		console.log(clientInfo);
		// #endif

	},

}
const pushHandle = (msg) => {
	if (typeof (msg.payload )=='string') {  //如果是字符串,表示是ios创建的  要转换一下
		msg.payload=JSON.parse(msg.payload )
	}
	if(!msg) return false;
	plus.runtime.setBadgeNumber(0); //清除app角标
	
	//下面的代码根据自己业务来写 这里可以写跳转业务代码
	//跳转到tab
	if (msg.payload.pathType == '1') {
		uni.switchTab({
			url: msg.payload.url
		})
	}
	//跳转到详情
	if (msg.payload.pathType == 0) {
		let url = msg.payload.url
		if (msg.payload.args) {
			url = url + '?id=' + msg.payload.args
		}
		console.log(url);
		uni.navigateTo({
			url: url
		})
	}
}

Finally, add the following code in App.vue

<script>
	import push from 'push/unipush.js';
	export default {
		onLaunch: function() {
			console.log('App Launch');
			push.getClient(); 
			push.init();
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

<style>
	/*每个页面公共css */
</style>

So far, the mobile phone code has been completed. Fairly simple. Next is the java server side

5. Java server-side integrated push

To obtain relevant information such as the secret key, go to the developer center, and there is secret key related information in the message push -> configuration management -> application configuration 

My background is Springboot, so fill in the following configuration under application.yml

Then integrate a pushed sdk in pom.xml

<dependency>
    <groupId>com.getui.push</groupId>
    <artifactId>restful-sdk</artifactId>
    <version>1.0.0.8</version>
</dependency>

6. Create a push configuration class GTPushConfig

import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GTPushConfig {

//    @Value("https://restapi.getui.com/v2")
//    private String baseUrl;

    @Value("${uniPush.appId}")
    private String appId;

    @Value("${uniPush.appKey}")
    private String appKey;

    @Value("${uniPush.masterSecret}")
    private String masterSecret;

    @Bean(name = "myApiHelper")
    public ApiHelper apiHelper() {
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        //填写应用配置
        apiConfiguration.setAppId(appId);
        apiConfiguration.setAppKey(appKey);
        apiConfiguration.setMasterSecret(masterSecret);
        // 接口调用前缀,请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
        //默认为https://restapi.getui.com/v2
        //apiConfiguration.setDomain("https://restapi.getui.com/v2/");
        // 实例化ApiHelper对象,用于创建接口对象
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        return apiHelper;
    }
}

7. Encapsulate push tool class PushUtil and push message entity class

Push message entity class

@Data
public class PushReqBean implements Serializable {

    //消息类型  0代表透传消息(使用这个,需要手机自己弹出通知,定义通知样式,content为json串)  1代表是通知(使用这个,标题和内容即手机上显示的通知标题和内容)
    private Integer noticeType;
    //推送用户类型 0 全部用户  1根据cid推送  2根据别名  3根据标签
    private Integer userType;
    //用户标识,可为cid,别名,tag,多个之间逗号隔开
    private String user;
    //推送标题
    private String title;
    //推送内容
    private String content;

}

The result of the api call encapsulates the entity class (optional)

@Data
public class ResultBean implements Serializable {

    public int code;
    public String msg;
    public Object data;

}

Push tool class, in this, I have integrated almost all functions, such as binding aliases, batch binding, binding tags, unbinding, push notifications according to various methods, push transparent transmission messages according to various methods, etc. .


import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.api.UserApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.*;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.res.QueryCidResDTO;
import com.getui.push.v2.sdk.dto.res.TaskIdDTO;
import com.google.gson.JsonObject;
import com.njlift.wechat.common.Result;
import com.njlift.wechat.entity.PushReqBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class PushUtil {

    @Resource(name = "myApiHelper")
    private ApiHelper myApiHelper;


    /**
     * 绑定别名
     * @param cid  用户在推送服务器的唯一识别标志
     * @param alias 在自己服务器上的唯一识别标志
     * @return 绑定结果
     */
    public Result bindAlias(String cid,String alias){
        Result rb=new Result();
        CidAliasListDTO cidAliasListDTO=new CidAliasListDTO();
        CidAliasListDTO.CidAlias cidAlias=new CidAliasListDTO.CidAlias();
        cidAlias.setCid(cid);
        cidAlias.setAlias(alias);
        cidAliasListDTO.add(cidAlias);
        UserApi userApi = myApiHelper.creatApi(UserApi.class);
        ApiResult<Void> voidApiResult = userApi.bindAlias(cidAliasListDTO);
        rb.setCode(voidApiResult.getCode());
        rb.setMsg(voidApiResult.getMsg());
        rb.setData(voidApiResult.getData());
        return rb;
    }

    /**
     * 批量解绑别名
     * @param aliasList 别名列表
     * @return 解绑结果
     *
     */
    public Result unbindAlias(List<String> aliasList){
        Result rb=new Result();
        List<CidAliasListDTO.CidAlias> list=new ArrayList<>();
        UserApi userApi = myApiHelper.creatApi(UserApi.class);
        for (String alias:aliasList){
            ApiResult<QueryCidResDTO> queryCidResDTOApiResult = userApi.queryCidByAlias(alias);
            if (queryCidResDTOApiResult.isSuccess()){
                List<String> cidList = queryCidResDTOApiResult.getData().getCid();
                for (String cid:cidList){
                    CidAliasListDTO.CidAlias cidAlias=new CidAliasListDTO.CidAlias();
                    cidAlias.setAlias(alias);
                    cidAlias.setCid(cid);
                    list.add(cidAlias);
                }
            }
        }
        CidAliasListDTO cidAliasListDTO=new CidAliasListDTO();
        cidAliasListDTO.setDataList(list);
        ApiResult<Void> voidApiResult = userApi.batchUnbindAlias(cidAliasListDTO);
        rb.setCode(voidApiResult.getCode());
        rb.setMsg(voidApiResult.getMsg());
        rb.setData(voidApiResult.getData());
        return rb;
    }

    /**
     * 一个用户根据cid进行绑定tag标签(次数限制)
     * @param cid 用户在推送服务器的唯一识别标志
     * @param tag 标签名
     * @return 绑定结果
     */
    public Result userBindTagsByCid(String cid,String tag){
        Result rb=new Result();
        UserApi userApi = myApiHelper.creatApi(UserApi.class);
        TagDTO dto=new TagDTO();
        dto.addTag(tag);
        ApiResult<Void> voidApiResult = userApi.userBindTags(cid, dto);
        rb.setCode(voidApiResult.getCode());
        rb.setMsg(voidApiResult.getMsg());
        rb.setData(voidApiResult.getData());
        return rb;
    }

    /**
     * 一个用户根据别名进行绑定tag标签(次数限制)
     * @param alias 在自己服务器上的唯一识别标志
     * @param tag 标签名
     * @return 绑定结果
     */
    public Result userBindTagsByAlias(String alias,String tag){
        Result rb=new Result();
        rb.setCode(1);
        UserApi userApi = myApiHelper.creatApi(UserApi.class);
        ApiResult<QueryCidResDTO> queryCidResDTOApiResult = userApi.queryCidByAlias(alias);
        if (queryCidResDTOApiResult.isSuccess()){
            List<String> cidList = queryCidResDTOApiResult.getData().getCid();
            if (cidList.size()==1){
                String cid = cidList.get(0);
                TagDTO dto=new TagDTO();
                dto.addTag(tag);
                ApiResult<Void> voidApiResult = userApi.userBindTags(cid, dto);
                rb.setCode(voidApiResult.getCode());
                rb.setMsg(voidApiResult.getMsg());
                rb.setData(voidApiResult.getData());
            }else {
                rb.setMsg("该别名对应多个cid,无法绑定标签");
            }
        }else {
            rb.setMsg(queryCidResDTOApiResult.getMsg());
        }
        return rb;
    }

    /**
     * 一批用户绑定tag标签(每分钟100次,每日10000次)
     * @param cidList 用户在推送服务器的唯一识别标志
     * @param tag 标签名
     * @return 绑定结果
     */
    public Result userBindTagsByAlias(List<String> cidList,String tag){
        Result rb=new Result();
        rb.setCode(1);
        UserApi userApi = myApiHelper.creatApi(UserApi.class);
        UserDTO userDTO=new UserDTO();
        Set<String> cidSet=new HashSet<>(cidList);
        userDTO.setCid(cidSet);
        ApiResult<Map<String, String>> mapApiResult = userApi.usersBindTag(tag, userDTO);
        rb.setCode(mapApiResult.getCode());
        rb.setMsg(mapApiResult.getMsg());
        rb.setData(mapApiResult.getData());
        return rb;
    }

    /**
     * 批量用户解绑一个标签
     * @param list 用户集合(可cid集合或alias集合)
     * @param type 0表示alias集合,1表示cid集合
     * @param tag 标签
     * @return 解绑结果
     */
    public Result usersUnbindTag(List<String> list,int type,String tag){
        Result rb=new Result();
        rb.setCode(1);
        UserApi userApi = myApiHelper.creatApi(UserApi.class);
        UserDTO userDTO=new UserDTO();
        List<String> cidList=new ArrayList<>();
        if (type==0){
            for (String alias:list){
                ApiResult<QueryCidResDTO> queryCidResDTOApiResult = userApi.queryCidByAlias(alias);
                if (queryCidResDTOApiResult.isSuccess()){
                    cidList.addAll(queryCidResDTOApiResult.getData().getCid());
                }
            }
        }else {
            cidList.addAll(list);
        }
        Set<String> cidSet=new HashSet<>(cidList);
        userDTO.setCid(cidSet);
        ApiResult<Map<String, String>> mapApiResult = userApi.deleteUsersTag(tag, userDTO);
        rb.setCode(mapApiResult.getCode());
        rb.setMsg(mapApiResult.getMsg());
        rb.setData(mapApiResult.getData());
        return rb;
    }



    /**
     * 群推透传消息
     * @param bean 推送信息
     * @return 结果
     */
    public Result pushMessageToAll(PushReqBean bean){
        Result rb=new Result();
        PushDTO<String> pushDTO = new PushDTO<String>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        pushDTO.setAudience("all");
        PushMessage pushMessage = new PushMessage();
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("m_title",bean.getTitle());
        jsonObject.addProperty("m_content",bean.getContent());
        pushMessage.setTransmission(jsonObject.toString());
        pushDTO.setPushMessage(pushMessage);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> apiResult = pushApi.pushAll(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }

    /**
     * 根据cid推送消息(含批量)
     * @param bean 推送信息
     * @return 结果
     */
    public Result pushMessageToCid(PushReqBean bean){
        boolean isMany=bean.getUser().contains(",");
        if (isMany){
            return pushMessageToManyCid(bean);
        }else {
            return pushMessageToSingleCid(bean);
        }
    }

    /**
     * 根据别名推送消息(含批量)
     * @param bean 推送信息
     * @return 结果
     */
    public Result pushMessageToAlias(PushReqBean bean){
        boolean isMany=bean.getUser().contains(",");
        if (isMany){
            return pushMessageToManyAlias(bean);
        }else {
            return pushMessageToSingleAlias(bean);
        }
    }

    //根据cid单推消息
    private Result pushMessageToSingleCid(PushReqBean bean){
        Result rb=new Result();
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("m_title",bean.getTitle());
        jsonObject.addProperty("m_content",bean.getContent());
        pushMessage.setTransmission(jsonObject.toString());
        pushDTO.setPushMessage(pushMessage);
        Audience audience = new Audience();
        audience.addCid(bean.getUser());
        pushDTO.setAudience(audience);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }

    //批量根据cid推送消息
    private Result pushMessageToManyCid(PushReqBean bean){
        Result rb = new Result();
        PushDTO pushDTO=new PushDTO();
        PushMessage pushMessage = new PushMessage();
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("m_title",bean.getTitle());
        jsonObject.addProperty("m_content",bean.getContent());
        pushMessage.setTransmission(jsonObject.toString());
        pushDTO.setPushMessage(pushMessage);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> msg = pushApi.createMsg(pushDTO);
        if (msg.isSuccess()){
            AudienceDTO audienceDTO=new AudienceDTO();
            audienceDTO.setTaskid(msg.getData().getTaskId());
            audienceDTO.setAsync(true);
            List<String> users = Arrays.asList(bean.getUser().split(","));
            Audience audience=new Audience();
            for (String user:users){
                audience.addCid(user);
            }
            audienceDTO.setAudience(audience);
            PushApi pushApi1 = myApiHelper.creatApi(PushApi.class);
            ApiResult<Map<String, Map<String, String>>> mapApiResult = pushApi1.pushListByCid(audienceDTO);
            rb.setCode(mapApiResult.getCode());
            rb.setMsg(mapApiResult.getMsg());
            rb.setData(mapApiResult.getData());
        }else {
            rb.setCode(msg.getCode());
            rb.setMsg(msg.getMsg());
            rb.setData(msg.getData());
        }
        return rb;
    }

    //根据别名单推消息
    private Result pushMessageToSingleAlias(PushReqBean bean){
        Result rb=new Result();
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("m_title",bean.getTitle());
        jsonObject.addProperty("m_content",bean.getContent());
        pushMessage.setTransmission(jsonObject.toString());
        pushDTO.setPushMessage(pushMessage);
        Audience audience = new Audience();
        audience.addAlias(bean.getUser());
        pushDTO.setAudience(audience);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByAlias(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }

    //批量根据别名推送消息
    private Result pushMessageToManyAlias(PushReqBean bean){
        Result rb = new Result();
        PushDTO pushDTO=new PushDTO();
        PushMessage pushMessage = new PushMessage();
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("m_title",bean.getTitle());
        jsonObject.addProperty("m_content",bean.getContent());
        pushMessage.setTransmission(jsonObject.toString());
        pushDTO.setPushMessage(pushMessage);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> msg = pushApi.createMsg(pushDTO);
        if (msg.isSuccess()){
            AudienceDTO audienceDTO=new AudienceDTO();
            audienceDTO.setTaskid(msg.getData().getTaskId());
            audienceDTO.setAsync(true);
            List<String> users = Arrays.asList(bean.getUser().split(","));
            Audience audience=new Audience();
            for (String user:users){
                audience.addAlias(user);
            }
            audienceDTO.setAudience(audience);
            PushApi pushApi1 = myApiHelper.creatApi(PushApi.class);
            ApiResult<Map<String, Map<String, String>>> mapApiResult = pushApi1.pushListByAlias(audienceDTO);
            rb.setCode(mapApiResult.getCode());
            rb.setMsg(mapApiResult.getMsg());
            rb.setData(mapApiResult.getData());
        }else {
            rb.setCode(msg.getCode());
            rb.setMsg(msg.getMsg());
            rb.setData(msg.getData());
        }
        return rb;
    }

    //根据标签推送消息
    public Result pushMessageToTag(PushReqBean bean){
        Result rb=new Result();
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("m_title",bean.getTitle());
        jsonObject.addProperty("m_content",bean.getContent());
        pushMessage.setTransmission(jsonObject.toString());
        pushDTO.setPushMessage(pushMessage);
        Audience audience = new Audience();
        Condition condition=new Condition();
        condition.setKey("custom_tag");
        List<String> tags=new ArrayList<>();
        if (bean.getUser().contains(",")){
            tags.addAll(Arrays.asList(bean.getUser().split(",")));
        }else {
            tags.add(bean.getUser());
        }
        Set<String> sets=new HashSet<>();
        for (String tag:tags){
            sets.add(tag);
        }
        condition.setValues(sets);
        condition.setOptType("and");
        audience.addCondition(condition);
        pushDTO.setAudience(audience);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> apiResult = pushApi.pushByTag(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }


    /**
     * 群推通知
     * @param bean 推送信息
     * @return 结果
     */
    public Result pushNoticeToAll(PushReqBean bean){
        Result rb=new Result();
        PushDTO<String> pushDTO = new PushDTO<String>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        pushDTO.setAudience("all");
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setTitle(bean.getTitle());
        notification.setBody(bean.getContent());
        notification.setClickType("none");
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> apiResult = pushApi.pushAll(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }

    /**
     * 根据cid推送通知(含批量)
     * @param bean 推送信息
     * @return 结果
     */
    public Result pushNoticeToCid(PushReqBean bean){
        boolean isMany=bean.getUser().contains(",");
        if (isMany){
            return pushNoticeToManyCid(bean);
        }else {
            return pushNoticeToSingleCid(bean);
        }
    }

    /**
     * 根据别名推送通知(含批量)
     * @param bean 推送信息
     * @return 结果
     */
    public Result pushNoticeToAlias(PushReqBean bean){
        boolean isMany=bean.getUser().contains(",");
        if (isMany){
            return pushNoticeToManyAlias(bean);
        }else {
            return pushNoticeToSingleAlias(bean);
        }
    }

    //根据cid单推通知
    private Result pushNoticeToSingleCid(PushReqBean bean){
        Result rb=new Result();
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setTitle(bean.getTitle());
        notification.setBody(bean.getContent());
        notification.setClickType("none");
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        Audience audience = new Audience();
        audience.addCid(bean.getUser());
        pushDTO.setAudience(audience);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }

    //批量根据cid推送通知
    private Result pushNoticeToManyCid(PushReqBean bean) {
        Result rb = new Result();
        PushDTO pushDTO=new PushDTO();
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setTitle(bean.getTitle());
        notification.setBody(bean.getContent());
        notification.setClickType("none");
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> msg = pushApi.createMsg(pushDTO);
        if (msg.isSuccess()){
            AudienceDTO audienceDTO=new AudienceDTO();
            audienceDTO.setTaskid(msg.getData().getTaskId());
            audienceDTO.setAsync(true);
            List<String> users = Arrays.asList(bean.getUser().split(","));
            Audience audience=new Audience();
            for (String user:users){
                audience.addCid(user);
            }
            audienceDTO.setAudience(audience);
            PushApi pushApi1 = myApiHelper.creatApi(PushApi.class);
            ApiResult<Map<String, Map<String, String>>> mapApiResult = pushApi1.pushListByCid(audienceDTO);
            rb.setCode(mapApiResult.getCode());
            rb.setMsg(mapApiResult.getMsg());
            rb.setData(mapApiResult.getData());
        }else {
            rb.setCode(msg.getCode());
            rb.setMsg(msg.getMsg());
            rb.setData(msg.getData());
        }
        return rb;
    }

    //根据别名单推通知
    private Result pushNoticeToSingleAlias(PushReqBean bean){
        Result rb=new Result();
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setTitle(bean.getTitle());
        notification.setBody(bean.getContent());
        notification.setClickType("none");
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        Audience audience = new Audience();
        audience.addAlias(bean.getUser());
        pushDTO.setAudience(audience);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByAlias(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }

    //批量根据别名推送通知
    private Result pushNoticeToManyAlias(PushReqBean bean) {
        Result rb = new Result();
        PushDTO pushDTO=new PushDTO();
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setTitle(bean.getTitle());
        notification.setBody(bean.getContent());
        notification.setClickType("none");
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> msg = pushApi.createMsg(pushDTO);
        if (msg.isSuccess()){
            AudienceDTO audienceDTO=new AudienceDTO();
            audienceDTO.setTaskid(msg.getData().getTaskId());
            audienceDTO.setAsync(true);
            List<String> users = Arrays.asList(bean.getUser().split(","));
            Audience audience=new Audience();
            for (String user:users){
                audience.addAlias(user);
            }
            audienceDTO.setAudience(audience);
            PushApi pushApi1 = myApiHelper.creatApi(PushApi.class);
            ApiResult<Map<String, Map<String, String>>> mapApiResult = pushApi1.pushListByAlias(audienceDTO);
            rb.setCode(mapApiResult.getCode());
            rb.setMsg(mapApiResult.getMsg());
            rb.setData(mapApiResult.getData());
        }else {
            rb.setCode(msg.getCode());
            rb.setMsg(msg.getMsg());
            rb.setData(msg.getData());
        }
        return rb;
    }

    //根据标签推送通知
    public Result pushNoticeToTag(PushReqBean bean){
        Result rb=new Result();
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        GTNotification notification = new GTNotification();
        notification.setTitle(bean.getTitle());
        notification.setBody(bean.getContent());
        notification.setClickType("none");
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        Audience audience = new Audience();
        Condition condition=new Condition();
        condition.setKey("custom_tag");
        List<String> tags=new ArrayList<>();
        if (bean.getUser().contains(",")){
            tags.addAll(Arrays.asList(bean.getUser().split(",")));
        }else {
            tags.add(bean.getUser());
        }
        Set<String> sets=new HashSet<>();
        for (String tag:tags){
            sets.add(tag);
        }
        condition.setValues(sets);
        condition.setOptType("and");
        audience.addCondition(condition);
        pushDTO.setAudience(audience);
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);
        ApiResult<TaskIdDTO> apiResult = pushApi.pushByTag(pushDTO);
        rb.setCode(apiResult.getCode());
        rb.setMsg(apiResult.getMsg());
        rb.setData(apiResult.getData());
        return rb;
    }


}

In fact, the content in the tool class can roughly guess the meaning. For details, you can refer to Push Server Documentation     Push API-Tui Document Center

In fact, it is to build parameters, request, and then request a push server to operate.

Eight, packaging test

If you want to run directly on the emulator or mobile phone, it will have no effect, because uniapp running is divided into standard dock and custom dock.

The brief description is that the standard base is used for simple debugging. When the native layer remains unchanged, new code can be dynamically loaded and run with hot reload. But if you modify the native layer, you need to package it into an android apk or an ios ipa package. In this way, you can't even monitor the logs, and it will be very troublesome for the debugging and development stage, so you have a custom base.

Click Run -> Run to mobile phone or emulator -> Make a custom debugging base

 

The official statement is also very clear, with the custom base, these third-party sdk configurations will also take effect, and only need to be packaged once, unless you modify the configuration again.

The production is relatively simple. I recommend using your own certificate here, so there is no limit. The generated certificate is in the article at the bottom of the blog, which is the jks file. Some people use other formats. It doesn’t matter, it’s just an Android certificate. Then choose to open a custom debugging base, traditional packaging, and then confirm to wait for packaging.

 Then click Run, choose to run the custom base, and you can run it directly on the emulator or the real machine connected to the computer, and perform push joint debugging to see the effect.

9. Locally package uniapp as apk (if used, please read below)

If you use the local android studio to package the apk, you need to import the jar/aar package in addition to the above operations. How to use local packaging uniapp has been explained in the previous blog, so I won't say much here.

There are corresponding jar/aar packages in the SDK folder in the previously downloaded project project

Pick it up as needed, not put them all in, I put these

 

 Then under the build.gradle of the project (not the outermost build.gradle), add the manifestPlaceholders code under android as follows, a total of four values, the appid of your uniapp, then the configuration of unipush, and finally your android project Package name, the applicationId is the package name, you need to fill in the same as the applicationId

 Finally, remember to go to the developer center to modify your package name and signature

Fill in the package name in your android studio, and the sha1 value of your packaged apk certificate. This is also explained in the blog that was packaged before. I won’t go into details here. So far, it’s all over.

Packaging blog address:   Hbuilderx uniapp local packaging android project

extra words

Finally, there is another point to be noted that the Mi mobile phone will hide the push in unimportant notifications (not that the notification message has not been received) . To solve this problem, you need to apply for a Channel on the Mi development platform to adjust the message level, set it to the important level. I'll update here when I have time. Read this document yourself first: Documentation Center

My personal creation, if there is any similarity, it is purely coincidental, or contact me to make changes. Please reprint or CV combination to indicate the source, thank you! (If you have any questions or errors, please point them out, my QQ:752231513)

Guess you like

Origin blog.csdn.net/qq_30548105/article/details/128219723