Microsoft Azure IoTHub Serials 2 - 如何为android应用添加IoTHub支持
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支持的更多相关文章
- 为Android设备添加A2SD支持
相信很多用Android设备的用户都有这个问题,内部存储太小导致应用只能装那么几个,虽然rom也有提供移动到sd卡的选项,但是仅仅是移动程序文件到sd卡,并不能解决多少问题,多装几个还是会 ...
- 如何为Myeclipse手工添加dtd支持
一.引言 在MyEclipse中开发三大框架的项目时候经常会写一些配置的xml文件,例如:Struts2的struts.xml和Hibernate的hibernate.cfg.xml.Spring的a ...
- Microsoft Azure Point to Site VPN替代方案
Microsoft Azure提供了Point to Site VPN,但有时候这并不能满足我们的需求,例如:Point to Site VPN是SSTP VPN,只能支持Window客户端拨入,而且 ...
- Microsoft Azure 负载平衡服务
Microsoft Azure 为在其中托管的虚拟机(IaaS) 和云服务(PaaS) 提供负载平衡服务.负载平衡支持应用程序伸缩,并且提供应用程序故障恢复以及其他优势. 可以通过以下方式访问负 ...
- Microsoft Azure IoTHub Serials 1 - 使用Android设备与Azure IoTHub进行交互
Azure IoTHub的目标是为物联网的应用场景提供方便的设备接入,完成消息的发送和接收(C2D和D2C).经过持续不断的努力,目前Azure IoTHub已经支持多种操作系统设备的接入,包括And ...
- 如何使用 Microsoft Azure Media Services 现场直播,(Live Streaming) 直播流媒体系统
不久之前,微软公司宣布了 Microsoft Azure Media Services 实时直播服务 ( Live ) 开始进入技术预览阶段,公开接受用户测试. 而这些实时直播服务其实早已被 NBC ...
- Microsoft Azure 微软云平台系列新品发布
在移动为先,云为先的今天,微软为拥抱云文化的企业提供了技术和工具.利用创新且全面的移动解决方案和开发者工具,微软有独到之处,它帮助所有客户在云为先时代中发现潜在价值. 正如希望加快云创新步伐的你们所期 ...
- 【Microsoft Azure 的1024种玩法】四. 利用Azure Virtual machines 打造个人专属云盘,速度吊打某云盘
[简介] 1.Azure Virtual machines是Azure 提供的多种可缩放按需分配计算资源之一,Nextcloud是一款开源免费的私有云存储网盘项目,可以让你快速便捷地搭建一套属于自己或 ...
- Microsoft Azure Web Sites应用与实践【4】—— Microsoft Azure网站的“后门”
Microsoft Azure Web Sites应用与实践 系列: [1]—— 打造你的第一个Microsoft Azure Website [2]—— 通过本地IIS 远程管理Microsoft ...
随机推荐
- php下kafka实践
Kafka是一种高吞吐的分布式发布订阅消息系统 kafka安装和简单测试 安装kafka 下载 wget https://www-us.apache.org/dist/kafka/2.1.1/kafk ...
- AFNetworking Delete请求,报参数为空的错误
使用AFNetWorking进行网络请求的时候,AFNetWorking会默认把get head delete这三个方法的请求参数拼到了url的后面,然后造成body为空,一行代码解决: manage ...
- 14. Redis配置统计字典
14. Redis配置统计字典14.1 info系统状态说明14.1.1 命令说明14.1.2 详细说明14.2 standalone配置说明和分析14.2.1 总体配置14.2.2 最大内存及策略1 ...
- centos-0 基础
netstat -nap #会列出所有正在使用的端口及关联的进程/应用kill -9 1777 #杀掉编号为1777的进程(请根据实际情况输入) http://www.cnblogs.c ...
- 《笨方法学Python》加分题32
注意一下 range 的用法.查一下 range 函数并理解它在第 22 行(我的答案),你可以直接将 elements 赋值为 range(0, 6) ,而无需使用 for 循环?在 python ...
- 颜色16进制转为RGB格式
<script> 2 function getRGB(str){ var arr = str.split(""); var myred = arr[1]+arr[2]; ...
- WCF系列_WCF常用绑定选择
一.五种常用绑定常用绑定的传输协议以及编码格式 名称 传输协议 编码格式 互操作性 BasicHttpBinding HTTP/HTTPS Text,MTOM Yes NetTcpBinding TC ...
- 【Python】【BugList12】python自带IDLE执行print(req.text)报错:UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 93204-93204
[代码] # -*- coding:UTF-8 -*- import requests if __name__ == '__main__': target = 'https://unsplash.co ...
- Vue 获取登录用户名
本来是打算登录的时候把用户名传过去,试了几次都没成功,然后改成用cookie保存用户名,然后在读取就行了, 登录时候设置cookie setCookie(c_name,c_pwd,exdays) { ...
- RHCSA之路(1) -- 重拾RHEL 7
去年就买了Linux就该这么学这本书,在自己电脑上和实验室里的电脑都按照书上写的配置安装好了RHEL 7系统,然后看到了第二章就被别的事情吸引了注意力就再也没碰过了.现在希望自己能专注下来,一步一步做 ...