APICloud (13): Using jpush for message push

Foreword:

Recently, the push function will be added to the APP, and there is a push module in the template library of APICloud. After comparison, it is decided to use Jiguang push. The module name is ajpush , and it can be used by adding it to your own project. There are also official documents. Although the method is relatively detailed, it feels that there is a lack of coherence. After the first step and the next step, I am confused about what method to use. The API of the same Aurora Push official website is also written in great detail, but there is no coherent example to refer to. These two confused things made me stumble for several days without progress. Basically, the code on the Internet does not have this. This is an entry-level example, and later I saw an example about getting started (the link is as follows: http://blog.csdn.net/xuexiiphone/article/details/51252796 .), I finally know what is going on, and I express it here. grateful. Here's a record in the hope that it can help the little white rabbits who were as confused as me at the time.

 

Let's talk about its basic process first : it mainly involves three aspects ,

The first client : This can be done by configuring in APICloud and adding detection code

Second Aurora Push Third Party : It is mainly used to push the stuff that the server requires to push for the client , and acts as a bridge

Third server : The APP is installed on the mobile phone as a client and needs to request data from the server. Similarly, what kind of message to push is also configured through this server .

 

Next , let 's talk about Jiguang Push as a third party , because it connects the client and the server, that is, both use it, so let's talk about it first.

1. Log in to the official website of Jiguang Push https://www.jiguang.cn/, register an account and log in

2. Create an application : After logging in, you may see three options: "Aurora Developer Service", "Aurora Data Service", "Aurora Precise Advertising", select the first "Enter Background". Find "Create App" on the page, enter "App Name" and then "Create My App".

3. Obtain AppKey and Master Secret : After the application is successfully created, you can see the AppKey and Master Secret on the current page. If you can't see it, you can click "App Information" on the left to find the app you just created, click the settings in the lower right corner of the app, and get the AppKey and Master Secret. The Master Secret is usually hidden, and you need to click "View" to display it.

4. Push configuration : At the bottom of the "Get AppKey and Master Secret" page, find "Push Configuration", click "Complete Push Configuration" on the right, select "Android" in the opened page, and enter APICloud for "Application Package Name" The package name of the APP in the APP is obtained as shown in the figure:

This information is a bit secret, usually only a small amount of APP information is displayed in the overview. Click the ^ in the lower right corner to see more complete information.

After entering the package name, click Submit.

At this point, the third-party Jiguang push configuration is basically completed.

 

The third step is to embed Jiguang push in the mobile APP :

1. Add "ajpush" to your APP in the module library ;

2. Register in config.xml and add the following code:

<feature name="ajpush">
    <param name="app_key" value="AppKey obtained in the previous step"/>
    <param name="channel" value="Just fill in, preferably not in Chinese"/>
</ feature>

3. Introduce Jiguang push in the APP and add monitoring - it is best to add it on the home page - here is the message push, the specific code is as follows:

apiready=function(){
	noticePush();
}

var jpush = null;
//This method is used to push the announcement
function noticePush(){
	jpush = api.require('ajpush');             
    //initialization
    jpush.init (function (ret) {
    	//alert(ret.status);//If it returns 1, the initialization is successful
        if (ret && ret.status) {                    
           /*
            jpush.setListener (function (ret) {  
                var id = ret.id;//Message ID  
                var title = ret.title; // message title
                var content = ret.content; //Message content
                var extra = ret.extra; //Extra key-value pair
                console.log("id=" + id + ",title=" + title + ",content=" + content + ",extra=" + extra);  
            });
            */  
        }  
    });
    //Listen to the event that the message on the status bar is clicked
    api.addEventListener({name:'appintent'}, function(ret,err) {
		//alert('The notification is clicked, the data is received:\n' + JSON.stringify(ret));//Listen to the data received after the notification is clicked	    		
		var extra = ret.appParam.ajpush.extra;
		extra = eval('('+extra+')');
		//console.log("extra.user_id=" + extra.user_id + ",extra.notice_id=" + extra.notice_id);	    		 		
			
		api.openWin({
            name: 'noticedetails_win',
            url: 'noticedetails.html',
            allowEdit : true,
            pageParam:{
            	'notice_id':extra.notice_id
            },
            progress:{
            	type:"default",
            	title:"Loading..."
            }
    	});            	
	})
	api.addEventListener({name:'pause'}, function(ret,err) {
		onPause();//Listen for the application to enter the background and notify the jpush pause event
	});
		
	api.addEventListener({name:'resume'}, function(ret,err) {
		onResume();//Monitor the application to resume to the foreground and notify the jpush resume event
	});            
}

//Statistics-app recovery
function onResume(){
	jpush.onResume();
	console.log('JPush onResume');
}

//Statistics - app pause
function onPause(){
	jpush.onPause();
	console.log('JPush onPause');
}

4. Test : Re-login to the "Aurora Push" official website, enter the background, select the app you just created from the "upper left corner", click the "Push" tab parallel to the name of the app, click "Send Notification" on the left , and enter For the content of the SMS, select "Android" for the platform, "Broadcast (Everyone)" for the target group, "Immediately" for the sending time, and finally click "Send Now". Check whether the push message is received on the mobile phone with the APP installed.

 

The fourth step is to build your own server to send messages. I am using the Java version here .

1. Download the "Server SDK" from the Jiguang official website , the link is as follows: https://docs.jiguang.cn/jpush/resources/#sdk_1 , select the Java version, and unzip it after downloading. I have downloaded several versions of this SDK. When I downloaded it a while ago, there were Java code and jar packages, but there were no two most critical jar packages. Today, I downloaded only 2 key jar packages. There are no examples and no other needs. jar package, everyone pay attention.

 

There are 6 jar packages in total : gson-2.2.2.jar, jiguang-common-1.0.6.jar, jpush-client-3.2.19.jar, slf4j-api-1.6.1.jar, slf4j-api -1.7.5.jar, slf4j-log4j12-1.5.2.jar, of which jiguang-common-1.0.6.jar, jpush-client-3.2.19.jar are the keys, which have been uploaded to the attachment if needed download .

 

When it comes to this JAR package, there is a digression I want to say: because I didn’t know how many packages were there when I started to get it, and there was only Java code on the Internet, and it didn’t say which packages needed to be used, let alone where to get them. Download the Example of Jiguang Push official website and import the required jar package from it. I don't know where to download this Example (there are too many APIs in Jiguang and not enough system) I thought it was "demo given during push configuration", so I downloaded the demo Refer to the information on the official website for configuration, the demo is about Android, and I have never used Android, so I built the Android environment according to the gourd painting, and I wasted 2 days for this environment. When I came to various problems, I read the article mentioned above and finished the push function before I understood: this "demo given during push configuration" does not need to be studied at all for me who uses APICloud, it is just a The plug-in is used to install the mobile phone where the APP is located to receive messages, and the ajpush module in APICloud is used for this purpose. It is already integrated and does not need to be installed again.

So here is a reminder to the children's shoes who use the ajpush module to implement the push function, this damn demo has nothing to do with our APP, and don't think about finding the jar package we need from here because it doesn't exist at all.

 

Okay, enough nonsense, let's get down to business.

 

2. Create a new web project, import the above 6 jar packages, and build-path

 

3. Drag the entire cn folder under the \jpush-api-java-client-xxx\src\main\java path in the official website example into src, and refer to the example on the official website. Maybe there is no official download example (I downloaded jpush-api-java-client-3.2.20.zip and there is no example), jpush-api-java-client-3.2.19 has it, it has been uploaded to the attachment, you can download it if you need it .

 

4. According to the own push written by Example :

public class JpushInstance {
	 protected static final Logger LOG = LoggerFactory.getLogger(JpushInstance.class);

	 // demo App defined in resources/jpush-api.conf
	private static String appKey="xxxxxx";
	private static String masterSecret="xxxxxx";
	//long optional 	
	// How long to save offline messages. seconds. Up to 10 days (864000 seconds) are supported.
	//0 means the message is not saved offline. That is: if the user is online, the message will be sent immediately, and the user who is not online will not receive this message.
	//If this parameter is not set, it means the default, and the default is to save offline messages for 1 day (86400 seconds).
	private static int timeToLive=3;
	private static String TITLE = "wjl";
	private static String ALERT = "Announcement posted";
	private static String MSG_CONTENT = TITLE+":"+ALERT;
	private static JPushClient jpushClient=null;
	private static Map<String,String> extrasMap = null;//Used to save the parameters that need to be used
	
	/**
	 * This method is used to push the message
	 * @param title: notification title, if specified, the place where the app name was originally displayed in the notification will be displayed as this field.
	 * @param alert: notification content, if it is specified here, it will overwrite the alert information uniformly specified by the superior; the content can be an empty string, which means that it will not be displayed in the notification bar.
	 * @param extras: Key/Value information in custom JSON format in the extension field for business use.
	 * **/
	public static void sendPush(String title,String alert,Map<String,String> extras) {
		 jpushClient = new JPushClient(masterSecret, appKey, timeToLive);
		 TITLE = title;
		 ALERT = alert;
		 if(extras!=null)extrasMap = extras;
		 
		 //Generate push content, push all
        PushPayload payload=buildPushObject_android_tag_alertWithTitle();
        
        try {
        	//System.out.println(payload.toString());
            PushResult result = jpushClient.sendPush(payload);
           // System.out.println(result+"................................");
            LOG.info("/********************************Aurora push starts*********** ********************/");
        	LOG.info("时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\r\n");
            LOG.info("Aurora push: sending status: " + result);
            LOG.info("/********************************The end of the aurora push*********** ********************/");
            
        } catch (APIConnectionException e) {
            LOG.error("Aurora push: Connection error. Should retry later. ", e);
            
        } catch (APIRequestException e) {
        	LOG.info("/********************************Aurora push starts*********** ********************/");
        	LOG.info("时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\r\n");
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.info("/********************************The end of the aurora push*********** ********************/");
        }
	}
	
	public static PushPayload buildPushObject_all_all_alert() {
	    return PushPayload.alertAll(ALERT);
	}
	
    public static PushPayload buildPushObject_all_alias_alert() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())//Set the accepted platform
                .setAudience(Audience.all())//Audience is set to all, indicating that it is pushed by broadcast, and all users can receive it
                .setNotification(Notification.alert(ALERT))
                .build();
    }
    
    public static PushPayload buildPushObject_android_tag_alertWithTitle() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())//Android platform
                .setAudience(Audience.all())//Audience is set to all, indicating that it is pushed by broadcast, and all users can receive it
                .setNotification(Notification.android(ALERT, TITLE, extrasMap))
                .build();
    }
    
    public static PushPayload buildPushObject_android_and_ios() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.newBuilder()
                		.setAlert("alert content")
                		.addPlatformNotification(AndroidNotification.newBuilder()
                				.setTitle("Android Title").build())
                		.addPlatformNotification(IosNotification.newBuilder()
                				.incrBadge(1)
                				.addExtra("extra_key", "extra_value").build())
                		.build())
                .build();
    }
    
    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(ALERT)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                 .setMessage(Message.content(MSG_CONTENT))
                 .setOptions(Options.newBuilder()
                         .setApnsProduction(true)
                         .build())
                 .build();
    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }
}

5. Make a call at the place where the message needs to be pushed . Here I am publishing a message on the mobile APP. It is sent to the background through ajax. After the server saves the data to the database, the push program is called to push:

Map<String,String> extrasMap = new HashMap<String,String>();
extrasMap.put("user_id", user_id);
extrasMap.put("notice_id",(result2)+"");
com.tzj.tsp.admin.jpush.JpushInstance.sendPush("wjl","posted an announcement",extrasMap);

6. Test : The mobile APP sends a message to test whether the mobile phone can receive the push message.

 

At this point, the whole push function is completed, I hope it will be helpful to everyone.

 

Finally, good luck to everyone!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326637771&siteId=291194637