Microsoft Azure IoTHub Serials 2-How to add IoTHub support to android apps

Microsoft Azure IoTHub Serials 2-How to add IoTHub support to android apps

1. Add dependencies on the following items in the dependencies of the build.gradle (app) file:

'com.microsoft.azure.sdk.iot:iot-device-client:1.5.37'

The 1.5.37 behind is the version number, the latest version can be checked here:

http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.microsoft.azure.sdk.iot%22

2. Add the following content in the packagingOptions of the build.gradle (app) file

packagingOptions {

    exclude "META-INF/MSFTSIG.SF"

    exclude "META-INF/MSFTSIG.RSA"

    exclude'META-INF/DEPENDENCIES'

    exclude'META-INF/NOTICE'

    exclude'META-INF/LICENSE'

    exclude'META-INF/LICENSE.txt'

    exclude'META-INF/NOTICE.txt'

    exclude'thirdpartynotice.txt'

}

As shown below.

3. In the java file that needs to interact with IoTHub, introduce the following package

//Azure IoTHub packages

import com.microsoft.azure.sdk.iot.device.DeviceClient;

import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol;

import com.microsoft.azure.sdk.iot.device.IotHubEventCallback;

import com.microsoft.azure.sdk.iot.device.IotHubMessageResult;

import com.microsoft.azure.sdk.iot.device.IotHubStatusCode;

import com.microsoft.azure.sdk.iot.device.Message;

4. Add the following global connection string

//Azure IoTHub

private final String connString = "HostName=************.azure-devices.net;DeviceId=***********;SharedAccessKey=******* **************";

private final String deviceId = "*****************";

5. Add the following 3 classes (MessageCallbackMqtt, EventCallback, MessageCallback and Counter) declarations in the java file

//Our MQTT doesn't support abandon/reject, so we will only display the messaged received

//from IoTHub and return COMPLETE

static class MessageCallbackMqtt implements com.microsoft.azure.sdk.iot.device.MessageCallback

{

    public IotHubMessageResult execute(Message msg, Object context)

    {

        Counter counter = (Counter) context;

        System.out.println(

                "Received message "+ counter.toString()

                        + "with content:" + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));



        counter.increment();



        return IotHubMessageResult.COMPLETE;

    }

}



static class EventCallback implements IotHubEventCallback

{

    public void execute(IotHubStatusCode status, Object context)

    {

        Integer i = (Integer) context;

        System.out.println("IoT Hub responded to message "+ i.toString()

                + "with status" + status.name());

    }

}



static class MessageCallback implements com.microsoft.azure.sdk.iot.device.MessageCallback

{

    public IotHubMessageResult execute(Message msg, Object context)

    {

        Counter counter = (Counter) context;

        System.out.println(

                "Received message "+ counter.toString()

                        + "with content:" + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));



        int switchVal = counter.get()% 3;

        IotHubMessageResult res;

        switch (switchVal)

        {

            case 0:

                res = IotHubMessageResult.COMPLETE;

                break;

            case 1:

                res = IotHubMessageResult.ABANDON;

                break;

            case 2:

                res = IotHubMessageResult.REJECT;

                break;

            default:

               //should never happen.

                throw new IllegalStateException("Invalid message result specified.");

        }



        System.out.println("Responding to message "+ counter.toString() +" with "+ res.name());



        counter.increment();



        return res;

    }

}



/**

 * Used as a counter in the message callback.

 */

static class Counter

{

    int num;



    Counter(int num) {

        this.num = num;

    }



    int get() {

        return this.num;

    }



    void increment() {

        this.num++;

    }



    @Override

    public String toString() {

        return Integer.toString(this.num);

    }

}

6. When you need to send data, call the following code segment

private void SendMessage() throws URISyntaxException, IOException
    {
       //Comment/uncomment from lines below to use HTTPS or MQTT protocol
       //IotHubClientProtocol protocol = IotHubClientProtocol.HTTPS;
        IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;

        DeviceClient client = new DeviceClient(connString, protocol);

        try
        {
            client.open();
        } catch (Exception e2)
        {
            System.err.println("Exception while opening IoTHub connection: "+ e2.toString());
        }

//Send message fill
            String msgStr = "{\"deviceId\":\"" + deviceId + ",\"PM25\":" + PM25 + ",\"PM10\":" + PM10 + "}";
            try
            {
                Message msg = new Message(msgStr);
                msg.setProperty("PMAlert", PM25> 100? "true": "false");
                msg.setMessageId(java.util.UUID.randomUUID().toString());
                System.out.println(msgStr);
                EventCallback eventCallback = new EventCallback();
                client.sendEventAsync(msg, eventCallback, null);
            } catch (Exception e)
            {
                System.err.println("Exception while sending event: "+ e.getMessage());
            }
            try
            {
                Thread.sleep(2000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }


        client.closeNow();
    }
Reference: https://cloud.tencent.com/developer/article/1172426 Microsoft Azure IoTHub Serials 2-How to add IoTHub support for android applications-Cloud + Community-Tencent Cloud