Android and iot Hub Azure , create service mqtt client -
i read , follow in link : https://github.com/azure/azure-iot-sdk-java/tree/master/device/iot-device-samples/android-sample
now , because want app run in background , listen messages received iothub azure , create service. service have timer task send after n-time report server. service open connection azureiot sdk , wait message.
i know bad solution , , see don't catch message or catch annoying delay.
what right implementation of kind of client mqtt listener on service ( or not if wrong ) on android app run in background ?
this code :
public class homeservice extends service { public static final long interval = 15 * 1000; private handler mhandler = new handler(); private timer mtimer = null; private requestqueue queue; private commandsender commandsender; deviceclient client = null; private boolean statelight = false; @nullable @override public ibinder onbind(intent intent) { throw new unsupportedoperationexception("unsupported operation"); } ///private final static string conn_string = "hostname=lifesensorhub.azure-devices.net;sharedaccesskeyname=device;sharedaccesskey=mhpmt3hl4jmebini/xpd+yo7afweguumxquzbnf/+pa=;deviceid=android-tv-dev"; private runnable runnable = new runnable() { @override public void run() { while(true) { waitformessage(); } } }; @override public void oncreate() { new thread(runnable).start(); if (mtimer != null) mtimer.cancel(); else mtimer = new timer(); commandsender = new commandsender(this); mtimer.scheduleatfixedrate(new timedisplaytimertask(), 0, interval); } public void waitformessage() { iothubclientprotocol protocol = iothubclientprotocol.mqtt; try { if(client == null) { client = new deviceclient(azurehelper.conn_string, protocol); } try { client.open(); } catch (ioexception e1) { system.out.println("exception while opening iothub connection: " + e1.tostring()); } catch (exception e2) { system.out.println("exception while opening iothub connection: " + e2.tostring()); } if (protocol == iothubclientprotocol.mqtt) { azurehelper.messagecallbackmqtt callback = new azurehelper.messagecallbackmqtt(commandsender); azurehelper.counter counter = new azurehelper.counter(0); client.setmessagecallback(callback, counter); } else { azurehelper.messagecallback callback = new azurehelper.messagecallback(); azurehelper.counter counter = new azurehelper.counter(0); client.setmessagecallback(callback, counter); } thread.sleep(2000); client.close(); } catch (urisyntaxexception e) { e.printstacktrace(); } catch (interruptedexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } @override public void ondestroy() { mtimer.cancel(); } private class timedisplaytimertask extends timertask { @override public void run() { mhandler.post(new runnable() { @override public void run() { makerequest(); } }); } } private void makerequest() { commandsender.getstatus(); } }
Comments
Post a Comment