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(); }
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
标签:
Azure IoTHub
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2010-05-23 第五届MobileDev Day