Quickstart: Control a device connected to an IoT hub (Android)

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. In this quickstart, you use a direct method to control a simulated device connected to your IoT hub. You can use direct methods to remotely change the behavior of a device connected to your IoT hub.

The quickstart uses two pre-written Java applications:

  • A simulated device application that responds to direct methods called from a back-end service application. To receive the direct method calls, this application connects to a device-specific endpoint on your IoT hub.

  • A service application that calls the direct method on the Android device. To call a direct method on a device, this application connects to service-side endpoint on your IoT hub.

Open Azure Cloud Shell

Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Common Azure tools are preinstalled and configured in Cloud Shell for you to use with your account. Select Copy to copy the code, paste it in Cloud Shell, and then press Enter to run it. There are a few ways to open Cloud Shell:

Select Try It in the upper-right corner of a code block. Example of Try It for Azure Cloud Shell
Open Cloud Shell in your browser. Launch Azure Cloud Shell button
Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. Cloud Shell button in the Azure portal

If you don’t have an Azure subscription, create a free account before you begin.

Prerequisites

Create an IoT hub

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.

This section describes how to create an IoT hub using the Azure portal.

  1. Log in to the Azure portal.

  2. Choose +Create a resource, then choose Internet of Things.

  3. Click Iot Hub from the list on the right. You see the first screen for creating an IoT hub.

    Create a hub in the Azure portal

    Fill in the fields.

    Subscription: Select the subscription to use for your IoT hub.

    Resource Group: You can create a new resource group or use an existing one. To create a new one, click Create new and fill in the name you want to use. To use an existing resource group, click Use existing and select the resource group from the dropdown list. For more information, see Manage Azure Resource Manager resource groups.

    Region: This is the region in which you want your hub to be located. Select the location closest to you from the dropdown list.

    IoT Hub Name: Put in the name for your IoT Hub. This name must be globally unique. If the name you enter is available, a green check mark appears.

    Important

    The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

  4. Click Next: Size and scale to continue creating your IoT hub.

    Set the size and scale for a new IoT hub using the Azure portal

    On this screen, you can take the defaults and just click Review + create at the bottom.

    Pricing and scale 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. It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in the free tier.

    IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the IoT hub to support ingress of 700,000 messages, you choose two S1 tier units.

    For details about the other tier options, see Choosing the right IoT Hub tier.

    Advanced / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most IoT hubs only need four partitions.

  5. Click Review + create to review your choices. You see something similar to this screen.

    Review information for creating the new IoT hub

  6. Click Create to create your new IoT hub. Creating the hub takes a few minutes.

Register a device

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.

A device must be registered with your IoT hub before it can connect. In this quickstart, you use the Azure Cloud Shell to register a simulated device.

  1. Run the following command in Azure Cloud Shell to create the device identity.

    YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

    MyAndroidDevice: This value is the name given for the registered device. 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. Run the following commands in Azure Cloud Shell to get the device connection string for the device you just registered:

    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

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. The following command retrieves the service connection string for your IoT hub:

YourIoTHubName: Replace this placeholder below with the name you chose for your IoT hub.

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

Make a note of the service connection string, which looks like:

HostName={YourIoTHubName}.azure-devices.net;SharedAccessKeyName=iothubowner;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

The device SDK sample application can be run on a physical Android device or an Android emulator. 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. Open the GitHub sample Android project in Android Studio. 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. 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. In Android Studio, click File > Sync Project with Gradle Files. Verify the build completes.

    Note

    If the project sync fails, it may be for one of the following reasons:

    • The versions of the Android Gradle plugin and Gradle referenced in the project are out of date for your version of Android Studio. Follow these instructions to reference and install the correct versions of the plugin and Gradle for your installation.
    • The license agreement for the Android SDK has not been signed. 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'. Configure the app to run on a physical Android device or an Android emulator. For more information on running an Android app on a physical device or emulator, see Run your app.

  5. Once the app loads, click the Start button to start sending telemetry to your IoT Hub:

    Sample screenshot of client device android app

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

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. Using the Azure Cloud Shell, run the following command to connect and read messages from your IoT hub:

    YourIoTHubName: Replace this placeholder below with the name you choose for your IoT hub.

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

    The following screenshot shows the output as the IoT hub receives telemetry sent by the Android device:

    Read the device messages using the Azure CLI

By default the telemetry app is sending telemetry from the Android device every 5 seconds. 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

The service application connects to a service-side endpoint on your IoT Hub. The application makes direct method calls to a device through your IoT hub and listens for acknowledgements.

Run this app on a separate physical Android device or Android emulator.

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. 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. Open the GitHub service sample Android project in Android Studio. 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. 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=iothubowner;SharedAccessKey={YourSharedAccessKey}
    DeviceId=MyAndroidDevice
    
  3. In Android Studio, click File > Sync Project with Gradle Files. Verify the build completes.

    Note

    If the project sync fails, it may be for one of the following reasons:

    • The versions of the Android Gradle plugin and Gradle referenced in the project are out of date for your version of Android Studio. Follow these instructions to reference and install the correct versions of the plugin and Gradle for your installation.
    • The license agreement for the Android SDK has not been signed. 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'. Configure the app to run on a separate physical Android device or an Android emulator. For more information on running an Android app on a physical device or emulator, see Run your app.

  5. Once the app loads, update the Set Messaging Interval value to 1000 and click Invoke.

    Th telemetry messaging interval is in milliseconds. The default telemetry interval of the device sample is set for 5 seconds. This change will update the Android IoT device so that telemetry is sent every second.

    Enter telemetry interval

  6. The app will receive an acknowledgement indicating whether the method executed successfully or not.

    Direct Method Acknowledgement

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.

Otherwise, you can delete the Azure resources created in this article to avoid charges.

Important

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. 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. Sign in to the Azure portal and click Resource groups.

  2. 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, click ... then Delete resource group.

    Delete

  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 click 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.