MQTT+ACTIVEMQ implement message push (move end) _ACTIVEMQ

Source: Internet
Author: User
Tags getmessage

This small program is my tutor assigned me a task, the online tutorial is not a lot, encountered some difficulties are their own solution, so write to share, what questions you can leave a message, try to help us solve.

First, we need to download ACTIVEMQ first
(Official website: http://activemq.apache.org/download.html)

Come to the extract directory, into the bin directory under the Win64 folder (how the 32-bit machine is into the Win32), run Activemq.bat. If an access denied occurs, the right mouse button runs as an administrator, and the following illustration shows that Activemq started successfully.

Mobile end of the download address Https://github.com/nymar123/MqttPusher

Once the server has started successfully, you can open the mobile side and click the corresponding button to connect.

How the mqttexception exception occurs when the connection server fails, check to see if the server is open and the URL and port are correct

After the connection is successful, the mobile end can receive the message from the ACTIVEMQ message server, the effect chart is as follows

I use the ORG.ECLIPSE.PAHO.CLIENT.MQTTV3, which encapsulates the mqttclient, Mqttconnection, Mqtttopic, Mqttmessage and other classes, with the following service code, With a more detailed annotation, you can see the role of various classes, there is a need to check the source code

public class Mqttservice extends Service {//message server URL public static final String Broker_url = "tcp://192.168.191.
    6:1883 ";
    The client ID, which identifies a customer and can generate the public static final String clientId = "Android-client" based on different policies;
    The subject name of the subscription is public static final String TOPIC = "Test";
    MQTT Client class private mqttclient mqttclient;  

    MQTT connection Configuration class private mqttconnectoptions options;
    Private String userName = "admin";


    Private String PassWord = "PassWord";
    Public IBinder Onbind (Intent Intent) {return null; @Override public void OnStart (Intent Intent, int startid) {try {//New at start of service mqttclient Real example, the client ID is clientId, the third argument is a persistent client, and if it is null, it is non-persistent mqttclient = new Mqttclient (Broker_url, clientId, new memorypers

            Istence ());  
            MQTT Connection Setting options = new Mqttconnectoptions (); Sets whether to empty the session, where setting to False indicates that the server retains the client's connection record, which is set to true to indicate that each connection to the server is in a new identity connection//or, when set to False, the client canTo accept offline message options.setcleansession (FALSE);  
            Set the user name of the connection options.setusername (UserName);  
            Set the password for the connection Options.setpassword (Password.tochararray ());  
            Set the timeout time in seconds options.setconnectiontimeout (10);  
            Set the session heartbeat time unit to seconds the server sends a message to the client every 1.5*20 seconds to determine whether the client is online, but this method does not have a mechanism to options.setkeepaliveinterval (20);  
            Set the description of the callback callback class to look behind Mqttclient.setcallback (this) (new Pushcallback);  
            Mqtttopic topic = mqttclient.gettopic (topic); Setwill method that can be invoked if the project needs to know whether the client is out of line. 
            Sets the notification message for the final port Options.setwill (topic, "Close". GetBytes (), 2, true);

            MQTT Client Connection Server mqttclient.connect (options);
            MQTT Client Subscription topic//In Mqtt QoS to identify the quality of service//qos=0, messages are sent at most once, it is possible to lose//qos=1, message sent at least once, it is possible to repeat
            When qos=2, messages are sent only once, and the message is guaranteed to arrive only once.  
            Int[] Qos = {1}; string[] Topic1 ={TOPIC}; 


        Mqttclient.subscribe (Topic1, Qos); catch (Mqttexception e) {toast.maketext (Getapplicationcontext), "something went wrong!" + e.getmessage (),
            Toast.length_long). Show ();
        E.printstacktrace ();
    } Super.onstart (Intent, Startid);
        @Override public void OnDestroy () {try {mqttclient.disconnect (0); catch (Mqttexception e) {toast.maketext (Getapplicationcontext), "something went wrong!" + e.getmessage (),
            Toast.length_long). Show ();
        E.printstacktrace (); The public class Pushcallback implements Mqttcallback {//callback method class needs to implement the Mqttpushback interface, which is used to handle an event triggered by the message push process privat

    e Contextwrapper context;
    Public Pushcallback (Contextwrapper context) {This.context = context; @Override public void Connectionlost (Throwable cause) {//The callback method when the connection is disconnected, you can reconnect here} @SuppressLint ("Newapi") @Override public VoiD messagearrived (mqtttopic topic, Mqttmessage message) throws Exception {//callback method when new messages arrive final Notificatio Nmanager Notificationmanager = (notificationmanager) context.getsystemservice (context.notification_service

        ); 


        Final Notification Notification;
        Final Intent Intent = new Intent (context, blackiceactivity.class);

        Final pendingintent activity = pendingintent.getactivity (context, 0, intent, 0);  
                Notification.builder Builder = new Notification.builder (context). Setautocancel (True) . Setcontenttitle ("message"). Setcontenttext (New String (Message.getpayload ()) + ""). S Etcontentintent (activity). Setsmallicon (R.drawable.snow). Setwhen (System.currenttimemi  
        Llis ()). Setongoing (True);
        Notification=builder.getnotification ();
        Notification.flags |= Notification.flag_auto_cancel; NotifIcation.number + 1;
    Notificationmanager.notify (0, notification);
 @Override public void Deliverycomplete (Mqttdeliverytoken token) {//callback method after successful publication of a message}}

Here's an introduction to the next ACTIVEMQ Web console, through which we can quickly and easily release the push content.

Open 127.0.0.1:8161/admin with browser (specific URL depends on deployment IP), login username password by default admin

We can see the topic in the current server, and we can see the Subscriber list under the Subscribers page.

So how do you post the message. Click on a topic under the topic page

Here are a lot of properties can be set according to their needs, click Send to the topic subscribers to push the

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.