您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:控制连接到 IoT 中心的设备 (Android)Quickstart: Control a device connected to an IoT hub (Android)

IoT 中心是一项 Azure 服务,可将大量遥测数据从 IoT 设备引入云,并从云管理设备。IoT Hub is an Azure service that enables you to ingest high volumes of telemetry from your IoT devices into the cloud and manage your devices from the cloud. 在本快速入门中,会使用直接方法来控制连接到 IoT 中心的模拟设备 。In this quickstart, you use a direct method to control a simulated device connected to your IoT hub. 可使用直接方法远程更改连接到 IoT 中心的设备的行为。You can use direct methods to remotely change the behavior of a device connected to your IoT hub.

本快速入门使用两个预先编写的 Java 应用程序:The quickstart uses two pre-written Java applications:

  • 模拟设备应用程序,可响应从后端服务应用程序调用的直接方法。A simulated device application that responds to direct methods called from a back-end service application. 为了接收直接方法调用,此应用程序会连接到 IoT 中心上特定于设备的终结点。To receive the direct method calls, this application connects to a device-specific endpoint on your IoT hub.

  • 服务应用程序,可在 Android 设备上调用直接方法。A service application that calls the direct method on the Android device. 为了在设备上调用直接方法,此应用程序会连接到 IoT 中心上的服务端终结点。To call a direct method on a device, this application connects to service-side endpoint on your IoT hub.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 通过 Cloud Shell 可以将 bashPowerShell 与 Azure 服务配合使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To launch Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。 Select Try It in the upper-right corner of a code block. 选择“试用” 不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell” 按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window
选择 Azure 门户右上方菜单栏中的“Cloud Shell” 按钮。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 打开 Cloud Shell。Open Cloud Shell.
  2. 选择代码块上的“复制”按钮 以复制代码。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上使用 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上使用 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. Enter 运行此代码。Press Enter to run the code.

如果还没有 Azure 订阅,可以在开始前创建一个免费帐户If you don’t have an Azure subscription, create a free account before you begin.

先决条件Prerequisites

创建 IoT 中心Create an IoT hub

如果已完成上一快速入门:将遥测数据从设备发送到 IoT 中心,则可跳过此步骤,使用已创建的 IoT 中心。If you completed the previous Quickstart: Send telemetry from a device to an IoT hub, you can skip this step and use the IoT hub you have already created.

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 选择“创建资源”,然后在“搜索市场”字段中输入“IoT 中心”。 Choose Create a resource, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。Select IoT Hub from the search results, and then select Create.

  4. 在“基本信息”选项卡上,按如下所示填写字段: On the Basics tab, complete the fields as follows:

    • 订阅:选择要用于中心的订阅。Subscription: Select the subscription to use for your hub.

    • 资源组:选择一个资源组或新建一个资源组。Resource Group: Select a resource group or create a new one. 若要新建资源组,请选择“新建”并填写要使用的名称。 To create a new one, select Create new and fill in the name you want to use. 若要使用现有的资源组,请选择它。To use an existing resource group, select that resource group. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    • 区域:选择中心所在的区域。Region: Select the region in which you want your hub to be located. 选择最靠近你的位置。Select the location closest to you.

    • IoT 中心名称:输入中心的名称。IoT Hub Name: Enter a name for your hub. 该名称必须全局唯一。This name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.

    重要

    由于 IoT 中心将作为 DNS 终结点公开可发现,因此请务必避免在命名它时输入任何敏感信息或个人身份信息。Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    在 Azure 门户中创建中心

  5. 在完成时选择“下一步: 大小和规模”,以继续创建中心。Select Next: Size and scale to continue creating your hub.

    使用 Azure 门户为新的中心设置大小和规模

    在此屏幕中可以设置以下值:This screen allows you to set the following values:

    • 定价和缩放层:选择的层。Pricing and scale tier: Your selected tier. 可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层中进行选择。You can choose from several tiers depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT Hub in the free tier.

    • IoT 中心单元:每日每单位允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    • 高级设置 > 设备到云的分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数中心只需要 4 个分区。Most hubs only need four partitions.

  6. 对于本教程,请接受默认选项,然后选择“查看 + 创建”以查看所做的选择。 For this tutorial, accept the default choices, and then select Review + create to review your choices. 会显示类似于以下的屏幕。You see something similar to this screen.

    查看用于创建新中心的信息

  7. 选择“创建”以创建新的中心 。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

注册设备Register a device

如果已完成上一快速入门:将遥测数据从设备发送到 IoT 中心,则可跳过此步骤,使用在上一快速入门中注册的设备。If you completed the previous Quickstart: Send telemetry from a device to an IoT hub, you can skip this step and use the same device registered in the previous quickstart.

必须先将设备注册到 IoT 中心,然后该设备才能进行连接。A device must be registered with your IoT hub before it can connect. 在本快速入门中,将使用 Azure Cloud Shell 来注册模拟设备。In this quickstart, you use the Azure Cloud Shell to register a simulated device.

  1. 在 Azure Cloud Shell 中运行以下命令,以创建设备标识。Run the following command in Azure Cloud Shell to create the device identity.

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    MyAndroidDevice:此值是为注册的设备提供的名称。MyAndroidDevice: This value is the name given for the registered device. 请按显示的方法使用 MyAndroidDevice。Use MyAndroidDevice as shown. 如果为设备选择其他名称,则可能还需要在本文中从头至尾使用该名称,并在运行示例应用程序之前在其中更新设备名称。If you choose a different name for your device, you may also need to use that name throughout this article, and update the device name in the sample applications before you run them.

    az iot hub device-identity create \
      --hub-name YourIoTHubName --device-id MyAndroidDevice
    
  2. 在 Azure Cloud Shell 中运行以下命令,以获取刚注册设备的_设备连接字符串_:Run the following commands in Azure Cloud Shell to get the device connection string for the device you just registered:

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you choose for your IoT hub.

    az iot hub device-identity show-connection-string \
      --hub-name YourIoTHubName \
      --device-id MyAndroidDevice \
      --output table
    

    记下如下所示的设备连接字符串:Make a note of the device connection string, which looks like:

    HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyAndroidDevice;SharedAccessKey={YourSharedAccessKey}

    稍后会在快速入门中用到此值。You use this value later in the quickstart.

检索服务连接字符串Retrieve the service connection string

还需一个服务连接字符串 ,以便后端服务应用程序能够连接到 IoT 中心以执行方法并检索消息。You also need a service connection string to enable the back-end service applications to connect to your IoT hub in order to execute methods and retrieve messages. 以下命令检索 IoT 中心的服务连接字符串:The following command retrieves the service connection string for your IoT hub:

YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

az iot hub show-connection-string --name YourIoTHubName --policy-name service --output table

记下如下所示的服务连接字符串:Make a note of the service connection string, which looks like:

HostName={YourIoTHubName}.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey={YourSharedAccessKey}

稍后会在快速入门中用到此值。You use this value later in the quickstart. 服务连接字符串与设备连接字符串不同。The service connection string is different from the device connection string.

侦听直接方法调用Listen for direct method calls

设备 SDK 示例应用程序可以在物理 Android 设备或 Android 模拟器上运行。The device SDK sample application can be run on a physical Android device or an Android emulator. 示例会连接到 IoT 中心的特定于设备的终结点,发送模拟遥测数据,并侦听中心的直接方法调用。The sample connects to a device-specific endpoint on your IoT hub, sends simulated telemetry, and listens for direct method calls from your hub. 在本快速入门中,中心的直接方法调用告知设备对其发送遥测的间隔进行更改。In this quickstart, the direct method call from the hub tells the device to change the interval at which it sends telemetry. 执行直接方法后,模拟设备会将确认发送回中心。The simulated device sends an acknowledgement back to your hub after it executes the direct method.

  1. 在 Android Studio 中打开 GitHub 示例 Android 项目。Open the GitHub sample Android project in Android Studio. 此项目位于克隆的或下载的 azure-iot-sample-java 存储库副本的以下目录中。The project is located in the following directory of your cloned or downloaded copy of azure-iot-sample-java repository.

     \azure-iot-samples-java\iot-hub\Samples\device\AndroidSample
    
  2. 在 Android Studio 中打开示例项目的 gradle.properties,将 Device_Connection_String 占位符替换为此前记下的设备连接字符串。In Android Studio, open gradle.properties for the sample project and replace the Device_Connection_String placeholder with your device connection string you noted earlier.

    DeviceConnectionString=HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyAndroidDevice;SharedAccessKey={YourSharedAccessKey}
    
  3. 在 Android Studio 中,单击“文件” > “将项目与 Gradle 文件同步”。In Android Studio, click File > Sync Project with Gradle Files. 验证生成是否已完成。Verify the build completes.

    备注

    如果项目同步失败,可能是由于以下某个原因:If the project sync fails, it may be for one of the following reasons:

    • 项目中引用的 Android Gradle 插件和 Gradle 的版本对于 Android Studio 版本来说已经过时。The versions of the Android Gradle plugin and Gradle referenced in the project are out of date for your version of Android Studio. 请按照这些说明操作,以引用并安装正确版本的插件和 Gradle 以进行安装。Follow these instructions to reference and install the correct versions of the plugin and Gradle for your installation.
    • Android SDK 的许可协议尚未签署。The license agreement for the Android SDK has not been signed. 请按照 Build 输出中的说明签署许可协议并下载 SDK。Follow the instructions in the Build output to sign the license agreement and download the SDK.
  4. 生成完成以后,请单击“运行” > “运行‘应用’”。Once the build has completed, click Run > Run 'app'. 将应用配置为在物理 Android 设备或 Android 模拟器上运行。Configure the app to run on a physical Android device or an Android emulator. 若要详细了解如何在物理设备或模拟器上运行 Android 应用,请参阅运行您的应用For more information on running an Android app on a physical device or emulator, see Run your app.

  5. 待应用加载以后,请单击“启动”按钮,开始将遥测数据发送到 IoT 中心: Once the app loads, click the Start button to start sending telemetry to your IoT Hub:

    客户端设备 android 应用的示例屏幕截图

在运行时期间执行服务 SDK 示例以更新遥测时间间隔时,需要让此应用在物理设备或模拟器上运行。This app needs to be left running on a phycial device or emulator while you execute the service SDK sample to update the telemetry interval during run-time.

从中心读取遥测数据Read the telemetry from your hub

在本部分,将使用具有 IoT 扩展的 Azure Cloud Shell 监视 Android 设备发送的设备消息。In this section, you will use the Azure Cloud Shell with the IoT extension to monitor the device messages that are sent by the Android device.

  1. 通过 Azure Cloud Shell 运行以下命令以建立连接并从 IoT 中心读取消息:Using the Azure Cloud Shell, run the following command to connect and read messages from your IoT hub:

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName: Replace this placeholder below with the name you choose for your IoT hub.

    az iot hub monitor-events --hub-name YourIoTHubName --output table
    

    以下屏幕截图显示了 IoT 中心接收 Android 设备发送的遥测数据后的输出:The following screenshot shows the output as the IoT hub receives telemetry sent by the Android device:

    使用 Azure CLI 读取设备消息

默认情况下,遥测应用每 5 秒钟从 Android 设备发送一次遥测数据。By default the telemetry app is sending telemetry from the Android device every 5 seconds. 在下一部分,将使用直接方法调用更新 Android IoT 设备的遥测时间间隔。In the next section, you will use a direct method call to update the telemetry interval for the Android IoT device.

调用直接方法Call the direct method

服务应用程序会连接到 IoT 中心的服务端终结点。The service application connects to a service-side endpoint on your IoT Hub. 应用程序通过 IoT 中心对设备进行直接方法调用,并侦听确认。The application makes direct method calls to a device through your IoT hub and listens for acknowledgements.

请在单独的物理 Android 设备或 Android 模拟器上运行此应用。Run this app on a separate physical Android device or Android emulator.

IoT 中心后端服务应用程序通常在云中运行,这样可以更轻松地减轻与敏感的连接字符串相关联的风险。该字符串控制某个 IoT 中心的所有设备。An IoT Hub back-end service application typically runs in the cloud where it is easier to mitigate the risks associated with the sensitive connection string that controls all devices on an IoT Hub. 在此示例中,我们将它作为 Android 应用运行,仅仅是为了演示。In this example, we are running it as an Android app for demonstration purposes only. 其他语言版本的本快速入门提供其他与后端服务应用程序更匹配的示例。The other language versions of this quickstart provide other examples that align more closely with a back-end service application.

  1. 在 Android Studio 中打开 GitHub 服务示例 Android 项目。Open the GitHub service sample Android project in Android Studio. 此项目位于克隆的或下载的 azure-iot-sample-java 存储库副本的以下目录中。The project is located in the following directory of your cloned or downloaded copy of azure-iot-sample-java repository.

     \azure-iot-samples-java\iot-hub\Samples\service\AndroidSample
    
  2. 在 Android Studio 中打开示例项目的 gradle.properties,将 ConnectionStringDeviceId 属性的值更新为此前记下的服务连接字符串和已注册的 Android 设备 ID。In Android Studio, open gradle.properties for the sample project and update the value for ConnectionString and DeviceId properties with your service connection string you noted earlier and the Android device ID you registered.

    ConnectionString=HostName={YourIoTHubName}.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey={YourSharedAccessKey}
    DeviceId=MyAndroidDevice
    
  3. 在 Android Studio 中,单击“文件” > “将项目与 Gradle 文件同步”。In Android Studio, click File > Sync Project with Gradle Files. 验证生成是否已完成。Verify the build completes.

    备注

    如果项目同步失败,可能是由于以下某个原因:If the project sync fails, it may be for one of the following reasons:

    • 项目中引用的 Android Gradle 插件和 Gradle 的版本对于 Android Studio 版本来说已经过时。The versions of the Android Gradle plugin and Gradle referenced in the project are out of date for your version of Android Studio. 请按照这些说明操作,以引用并安装正确版本的插件和 Gradle 以进行安装。Follow these instructions to reference and install the correct versions of the plugin and Gradle for your installation.
    • Android SDK 的许可协议尚未签署。The license agreement for the Android SDK has not been signed. 请按照 Build 输出中的说明签署许可协议并下载 SDK。Follow the instructions in the Build output to sign the license agreement and download the SDK.
  4. 生成完成以后,请单击“运行” > “运行‘应用’”。Once the build has completed, click Run > Run 'app'. 将应用配置为在单独的物理 Android 设备或 Android 模拟器上运行。Configure the app to run on a separate physical Android device or an Android emulator. 若要详细了解如何在物理设备或模拟器上运行 Android 应用,请参阅运行您的应用For more information on running an Android app on a physical device or emulator, see Run your app.

  5. 待应用加载以后,将“设置消息传送时间间隔”值更新为 1000,然后单击“调用”。 Once the app loads, update the Set Messaging Interval value to 1000 and click Invoke.

    遥测消息传送时间间隔以毫秒为单位。Th telemetry messaging interval is in milliseconds. 设备示例的默认遥测时间间隔设置为 5 秒钟。The default telemetry interval of the device sample is set for 5 seconds. 此更改会更新 Android IoT 设备,使遥测数据每秒发送一次。This change will update the Android IoT device so that telemetry is sent every second.

    输入遥测时间间隔

  6. 应用会收到一个表明方法是否已成功执行的确认。The app will receive an acknowledgement indicating whether the method executed successfully or not.

    直接方法确认

清理资源Clean up resources

如果想要继续学习下一篇建议的文章,可以保留已创建的资源,以便重复使用。If you will be continuing to the next recommended article, you can keep the resources you've already created and reuse them.

否则,可删除本文中创建的 Azure 资源,避免收费。Otherwise, you can delete the Azure resources created in this article to avoid charges.

重要

删除资源组的操作不可逆。Deleting a resource group is irreversible. 资源组以及包含在其中的所有资源将被永久删除。The resource group and all the resources contained in it are permanently deleted. 请确保不会意外删除错误的资源组或资源。Make sure that you do not accidentally delete the wrong resource group or resources. 如果在现有的包含要保留资源的资源组中创建了 IoT 中心,则只删除 IoT 中心资源本身,而不要删除资源组。If you created the IoT Hub inside an existing resource group that contains resources you want to keep, only delete the IoT Hub resource itself instead of deleting the resource group.

若要按名称删除资源组,请执行以下操作:To delete a resource group by name:

  1. 登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal and select Resource groups.

  2. 在“按名称筛选”文本框中,键入包含 IoT 中心的资源组的名称 。In the Filter by name textbox, type the name of the resource group containing your IoT Hub.

  3. 在结果列表中的资源组右侧,选择“...”,然后选择“删除资源组” 。To the right of your resource group in the result list, select ... then Delete resource group.

    删除

  4. 系统会要求确认是否删除资源组。You will be asked to confirm the deletion of the resource group. 再次键入资源组的名称进行确认,然后选择“删除” 。Type the name of your resource group again to confirm, and then select Delete. 片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all of its contained resources are deleted.

后续步骤Next steps

在本快速入门中,已从后端应用程序调用了设备上的直接方法,并在模拟设备应用程序中响应了直接方法调用。In this quickstart, you called a direct method on a device from a back-end application, and responded to the direct method call in a simulated device application.

若要了解如何将设备到云的消息路由到云中的不同目标,请继续学习下一教程。To learn how to route device-to-cloud messages to different destinations in the cloud, continue to the next tutorial.