前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Microsoft Azure IoTHub Serials 2 - 如何为android应用添加IoTHub支持

Microsoft Azure IoTHub Serials 2 - 如何为android应用添加IoTHub支持

作者头像
ShiJiong
发布2018-08-01 10:13:55
5770
发布2018-08-01 10:13:55
举报

1. 在build.gradle(app)文件的dependencies中添加对以下项的依赖:

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

其中后面的1.5.37是版本号,最新的版本可以到这里查:

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

2. 在build.gradle(app)文件的packagingOptions中添加如下内容

代码语言:javascript
复制
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'

}

如下图所示。

3. 在需要与IoTHub交互的java文件中,引入如下package

代码语言:javascript
复制
//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. 添加如下全局的连接字符串

代码语言:javascript
复制
//Azure IoTHub

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

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

5. 在java文件中添加如下3个类(MessageCallbackMqtt、EventCallback、MessageCallback和Counter)的声明

代码语言:javascript
复制
// 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.需要发送数据时,调用以下代码段

代码语言:javascript
复制
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());
        }

//发送message填充
            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();
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-05-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
物联网通信
腾讯云物联网通信(Internet of Things Hub, IoT Hub)旨在提供一个安全、稳定、高效的连接平台,帮助开发者低成本、快速地实现“设备-设备”、“设备-用户应用”、“设备-云服务”之间可靠、高并发的数据通信。物联网通信平台不仅可以实现设备之间的互动、设备的数据上报和配置下发,还可以基于规则引擎和腾讯云产品打通,方便快捷地实现海量设备数据的存储、计算以及智能分析。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档