Apollo implements C # with Android message push (iv)

Source: Internet
Author: User

4 Android code just to implement the function, relatively simple, just paste out the source code

 Packagecom.myapps.mqtttest;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledExecutorService;ImportJava.util.concurrent.TimeUnit;ImportOrg.eclipse.paho.client.mqttv3.IMqttDeliveryToken;ImportOrg.eclipse.paho.client.mqttv3.MqttCallback;Importorg.eclipse.paho.client.mqttv3.MqttClient;Importorg.eclipse.paho.client.mqttv3.MqttConnectOptions;Importorg.eclipse.paho.client.mqttv3.MqttException;ImportOrg.eclipse.paho.client.mqttv3.MqttMessage;Importorg.eclipse.paho.client.mqttv3.persist.MemoryPersistence;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.provider.Settings;Importandroid.view.KeyEvent;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateTextView Resulttv; PrivateString Mdeviceid; PrivateString host = "tcp://192.168.101.195:61613"; PrivateString userName = "admin"; PrivateString PassWord = "PassWord"; PrivateHandler Handler; Privatemqttclient Client; PrivateString myTopic = "Test"; Privatemqttconnectoptions options; PrivateScheduledexecutorservice Scheduler; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Mdeviceid= Settings.Secure.getString ( This. Getcontentresolver (), Settings.Secure.ANDROID_ID); Resulttv=(TextView) Findviewbyid (R.id.result);        Init (); Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); if(Msg.what = = 1) {Toast.maketext (mainactivity. This, (String) msg.obj, Toast.length_short). Show (); System.out.println ("-----------------------------"); } Else if(Msg.what = = 2) {Toast.maketext (mainactivity. This, "Connection succeeded", Toast.length_short). Show (); Try{client.subscribe (myTopic,1); } Catch(Exception e) {e.printstacktrace (); }                } Else if(Msg.what = = 3) {Toast.maketext (mainactivity. This, "Connection failed, re-connecting", Toast.length_short). Show ();        }            }        };    Startreconnect (); }    Private voidStartreconnect () {Scheduler=Executors.newsinglethreadscheduledexecutor (); Scheduler.scheduleatfixedrate (NewRunnable () {@Override Public voidrun () {if(!client.isconnected ())                {Connect (); }            }        }, 0 * 1000, 10 * 1000, Timeunit.milliseconds); }    Private voidinit () {Try {            //host is the hostname, test for ClientID is the client ID that connects to MQTT, typically represented by a client unique identifier, Memorypersistence set ClientID save form, default to save in memoryClient =NewMqttclient (Host, "Testandroid",                    Newmemorypersistence ()); //connection settings for MqttOptions =Newmqttconnectoptions (); //set whether to empty the session, if set 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 connected as a new identityOptions.setcleansession (true); //set the user name for the connectionOptions.setusername (userName); //set the password for the connectionOptions.setpassword (Password.tochararray ()); //set the time-out unit to secondsOptions.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 re-connectOptions.setkeepaliveinterval (20); //Set CallbackClient.setcallback (NewMqttcallback () {@Override Public voidconnectionlost (Throwable cause) {//after the connection is lost, it is usually re-connected in this area.System.out.println ("Connectionlost----------"); } @Override Public voidDeliverycomplete (Imqttdeliverytoken token) {//Publish will execute here after theSystem.out.println ("Deliverycomplete---------" +Token.iscomplete ()); } @Override Public voidmessagearrived (String topicname, mqttmessage message)throwsException {//subscribe, the message will be executed in this area.System.out.println ("Messagearrived----------"); Message msg=NewMessage (); Msg.what= 1; Msg.obj= topicname+ "---" +message.tostring ();                Handler.sendmessage (msg);        }            }); } Catch(Exception e) {e.printstacktrace (); }    }    Private voidConnect () {NewThread (NewRunnable () {@Override Public voidrun () {Try{client.connect (options); Message msg=NewMessage (); Msg.what= 2;                Handler.sendmessage (msg); } Catch(Exception e) {e.printstacktrace (); Message msg=NewMessage (); Msg.what= 3;                Handler.sendmessage (msg);    }}). Start (); } @Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {        if(Client! =NULL&& KeyCode = =keyevent.keycode_back) {            Try{client.disconnect (); } Catch(Exception e) {e.printstacktrace (); }        }        return Super. OnKeyDown (KeyCode, event); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Try{scheduler.shutdown ();        Client.disconnect (); } Catch(mqttexception e) {e.printstacktrace (); }    }}
View Code

Apollo implements C # with Android message push (iv)

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.