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中添加如下内容

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

//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. 添加如下全局的连接字符串

//Azure IoTHub

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

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

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

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

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();
}

Microsoft Azure IoTHub Serials 2 - 如何为android应用添加IoTHub支持的更多相关文章

  1. 为Android设备添加A2SD支持

          相信很多用Android设备的用户都有这个问题,内部存储太小导致应用只能装那么几个,虽然rom也有提供移动到sd卡的选项,但是仅仅是移动程序文件到sd卡,并不能解决多少问题,多装几个还是会 ...

  2. 如何为Myeclipse手工添加dtd支持

    一.引言 在MyEclipse中开发三大框架的项目时候经常会写一些配置的xml文件,例如:Struts2的struts.xml和Hibernate的hibernate.cfg.xml.Spring的a ...

  3. Microsoft Azure Point to Site VPN替代方案

    Microsoft Azure提供了Point to Site VPN,但有时候这并不能满足我们的需求,例如:Point to Site VPN是SSTP VPN,只能支持Window客户端拨入,而且 ...

  4. Microsoft Azure 负载平衡服务

     Microsoft Azure 为在其中托管的虚拟机(IaaS) 和云服务(PaaS) 提供负载平衡服务.负载平衡支持应用程序伸缩,并且提供应用程序故障恢复以及其他优势. 可以通过以下方式访问负 ...

  5. Microsoft Azure IoTHub Serials 1 - 使用Android设备与Azure IoTHub进行交互

    Azure IoTHub的目标是为物联网的应用场景提供方便的设备接入,完成消息的发送和接收(C2D和D2C).经过持续不断的努力,目前Azure IoTHub已经支持多种操作系统设备的接入,包括And ...

  6. 如何使用 Microsoft Azure Media Services 现场直播,(Live Streaming) 直播流媒体系统

    不久之前,微软公司宣布了 Microsoft Azure Media Services 实时直播服务 ( Live ) 开始进入技术预览阶段,公开接受用户测试. 而这些实时直播服务其实早已被 NBC ...

  7. Microsoft Azure 微软云平台系列新品发布

    在移动为先,云为先的今天,微软为拥抱云文化的企业提供了技术和工具.利用创新且全面的移动解决方案和开发者工具,微软有独到之处,它帮助所有客户在云为先时代中发现潜在价值. 正如希望加快云创新步伐的你们所期 ...

  8. 【Microsoft Azure 的1024种玩法】四. 利用Azure Virtual machines 打造个人专属云盘,速度吊打某云盘

    [简介] 1.Azure Virtual machines是Azure 提供的多种可缩放按需分配计算资源之一,Nextcloud是一款开源免费的私有云存储网盘项目,可以让你快速便捷地搭建一套属于自己或 ...

  9. Microsoft Azure Web Sites应用与实践【4】—— Microsoft Azure网站的“后门”

    Microsoft Azure Web Sites应用与实践 系列: [1]—— 打造你的第一个Microsoft Azure Website [2]—— 通过本地IIS 远程管理Microsoft ...

随机推荐

  1. pythone函数基础(15)接口开发初识

    导入需要的第三方模块 import flaskimport toolsimport json,redisimport random server = flask.Flask(__name__)#新建一 ...

  2. 8.Redis内存分配

    8.Redis内存分配8.1 内存消耗8.1.1 内存使用统计8.1.2 内存消耗划分8.1.3 子进程内存消耗8.2 内存管理8.2.1 设置内存上限8.2.2 动态调整内存上限8.2.3 内存回收 ...

  3. slot-scope

    插槽,也就是slot,是组件的一块HTML模板,这块模板显示不显示.以及怎样显示由父组件来决定. 实际上,一个slot最核心的两个问题在这里就点出来了,是显示不显示和怎样显示. 由于插槽是一块模板,所 ...

  4. python中的继承和多态

    继承 继承的表现方式: class Animal(): pass class Cat(Animal): #animal是cat的父类,也可以说是基类 pass print(Cat.__bases__) ...

  5. 《C++实践之路.pdf》源码

    > 源码下载方法 < >> 打开微信 >> 扫描下方二维码 >> 关注林哥私房菜 >> 输入对应编号获取百度网盘提取密码 全书源码[已更新完 ...

  6. Python 中 Iterator和Iterable的区别

    Python中 list,truple,str,dict这些都可以被迭代,但他们并不是迭代器.为什么? 因为和迭代器相比有一个很大的不同,list/truple/map/dict这些数据的大小是确定的 ...

  7. MySQL ERROR 1064(42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

    通常出现该错误的原因是使用了 MySQL 的保留字 解决方法是对使用的保留字使用反引号  (Tab键上面)

  8. 浅析b-树 b+树 以及Mysql的Innodb,Myisam引擎

    B-树性质 B-树可以看作是对2-3查找树的一种扩展,即他允许每个节点有M-1个子节点. 1根节点至少有两个子节点 2每个节点有M-1个key,并且以升序排列 3位于M-1和M key的子节点的值位于 ...

  9. 大面积project.pbxproj冲突问题解决

    在团队开发中,经常会有project.pbxproj的冲突出现. 所以我们添加过新的文件后,要及时的提交,养成好习惯.以免出问题. 但是总有一些时候忘记提交出现大面积的冲突,然后把==== <& ...

  10. select、poll、epoll

    1.概念 select.poll.epoll都是事件触发机制,当等待的事件发生就触发进行处理,用于I/O复用 2.简单例子理解 3.select函数 3.1函数详解 int select(int ma ...