Yandex Cloud
Search
Contact UsGet started
  • Blog
  • Pricing
  • Documentation
  • All Services
  • System Status
    • Featured
    • Infrastructure & Network
    • Data Platform
    • Containers
    • Developer tools
    • Serverless
    • Security
    • Monitoring & Resources
    • ML & AI
    • Business tools
  • All Solutions
    • By industry
    • By use case
    • Economics and Pricing
    • Security
    • Technical Support
    • Customer Stories
    • Gateway to Russia
    • Cloud for Startups
    • Education and Science
  • Blog
  • Pricing
  • Documentation
Yandex project
© 2025 Yandex.Cloud LLC
Yandex IoT Core
    • All tutorials
    • Working with Yandex IoT Core from an Android device in Java
    • Working with Yandex IoT Core in C#
    • Working with Yandex IoT Core in Java
    • Writing data from a device into a database
    • Status monitoring of geographically distributed devices
    • Monitoring sensor readings and event notifications
    • Testing message delivery
    • Emulating multiple IoT devices
  • Access management
  • Pricing policy
  • Terraform reference
  • Monitoring metrics
  • Audit Trails events
  • Release notes
  • FAQ

In this article:

  • Getting started
  • Create the required Yandex IoT Core resources
  • Create a registry and add a certificate to it
  • Create a device and add a certificate to it
  • Connect to Yandex IoT Core
  • Get authenticated in Yandex IoT Core
  • Authentication using X.509 certificates
  • Authenticating by username and password
  • Establish a connection
  • Subscribe to a topic and get data messages
  • Send a data message
  • Terminate the connection
  1. Tutorials
  2. Working with Yandex IoT Core from an Android device in Java

Working with Yandex IoT Core from an Android device in Java

Written by
Yandex Cloud
Updated at April 9, 2025
  • Getting started
  • Create the required Yandex IoT Core resources
    • Create a registry and add a certificate to it
    • Create a device and add a certificate to it
  • Connect to Yandex IoT Core
  • Get authenticated in Yandex IoT Core
    • Authentication using X.509 certificates
    • Authenticating by username and password
  • Establish a connection
  • Subscribe to a topic and get data messages
  • Send a data message
  • Terminate the connection

In this tutorial, you will learn how to connect to Yandex IoT Core from an Android device using the Paho library and Java. To use this tutorial, you must know how to develop Android apps in Java using Android Studio.

Note

The source code for this tutorial is available in a GitHub repository.

Once connected, you can exchange messages between your device and registry:

  • Send messages.
  • Subscribe a device or registry to receive messages.

To connect to Yandex IoT Core and start messaging:

  • Create the required Yandex IoT Core resources:
    • Create a registry and add a certificate to it.
    • Create a device and add a certificate to it.
  • Connect to Yandex IoT Core.
  • Authenticate in Yandex IoT Core:
    • Authentication using X.509 certificates.
    • Authentication by username and password.
  • Establish a connection.
  • Subscribe to a topic and receive data messages.
  • Send a data message.
  • Terminate the connection.

Getting startedGetting started

  1. If you do not have the Yandex Cloud CLI yet, install and initialize it.
  2. Download and install Android Studio, a development environment for Android.

Create the required Yandex IoT Core resourcesCreate the required Yandex IoT Core resources

Create a registry and add a certificate to itCreate a registry and add a certificate to it

If you already have a certificate, go directly to the second step.

  1. Create a certificate for the registry (skip this step if you already have a registry certificate):

    openssl req -x509 \
      -newkey rsa:4096 \
      -keyout registry-key.pem \
      -out registry-cert.pem \
      -nodes \
      -days 365 \
      -subj '/CN=localhost'
    
  2. Create a registry:

    yc iot registry create --name my-registry
    
  3. Add a certificate to the registry:

    yc iot registry certificate add \
    --registry-name my-registry \ # Registry name.
      --certificate-file registry-cert.pem # Path to the public part of the certificate.
    

Create a device and add a certificate to itCreate a device and add a certificate to it

If you already have a certificate, go directly to the second step.

  1. (Optional) Create a certificate for the device:

    openssl req -x509 \
      -newkey rsa:4096 \
      -keyout device-key.pem \
      -out device-cert.pem \
      -nodes \
      -days 365 \
      -subj '/CN=localhost'
    
  2. Create a device:

    yc iot device create --name my-device
    
  3. Add a certificate to the device:

    yc iot device certificate add \
      --device-name my-device \ # Device name.
      --certificate-file device-cert.pem # Path to the public part of the certificate.
    

Connect to Yandex IoT CoreConnect to Yandex IoT Core

Before connecting, configure the connection parameters using the following code:

String clientId = "YandexIoTCoreAndroidTextClient";
int connectionTimeout = 60;
int keepAliveInterval = 60;
MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(getApplicationContext(),"ssl://mqtt.cloud.yandex.net:8883", clientId);

// Setting up the connection parameters.
MqttConnectOptions options = new MqttConnectOptions();
options.setKeepAliveInterval(keepAliveInterval);

Where:

  • MqttAndroidClient: Class that specifies the Yandex IoT Core connection parameters. the client address, port, and ID.
  • MqttConnectOptions: Class that sets the connection options. You can use the default settings, but we recommend setting the KeepAliveInterval parameter. Its value determines the frequency of sending PINGREQ commands. The smaller this parameter is, the sooner the client will realize the connection was terminated abnormally. However, this increases the frequency of billable PINGREQ commands.

Get authenticated in Yandex IoT CoreGet authenticated in Yandex IoT Core

There are two authentication methods:

  • Using X.509 certificates.
  • Using a username and password.

Authentication using X.509 certificatesAuthentication using X.509 certificates

For this type of authentication, it is most convenient to use PKCS#12 certificates in PFX format. You can generate a certificate in PKCS#12 format from PEM certificates using this command:

openssl pkcs12 -export -in cert.pem -inkey key.pem -out keystore.p12

To load certificates in your project, use the following method:

private SSLSocketFactory getSocketFactory(final InputStream caCrtFile, final InputStream devCert, final String password)

Certificates are loaded in several stages:

  1. Load the certificate used for server authentication:

    // Loading the CA certificate.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate caCert = (X509Certificate) cf.generateCertificate(caCrtFile);
    
    // Using the CA certificate for server authentication.
    KeyStore serverCaKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    serverCaKeyStore.load(null, null);
    serverCaKeyStore.setCertificateEntry("ca", caCert);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(serverCaKeyStore);
    
  2. Load the client certificate used for authentication on the server:

    KeyStore clientKeystore = KeyStore.getInstance("PKCS12");
    clientKeystore.load(devCert, password.toCharArray());
    

As a result, the method returns AdditionalKeyStoresSSLSocketFactory:

return new AdditionalKeyStoresSSLSocketFactory(clientKeystore, serverCaKeyStore);

Inherited from SSLSocketFactory, the AdditionalKeyStoresSSLSocketFactory class is used for operations with self-signed certificates. At the final stage, provide the obtained sslSocketFactory to the connection parameters:

options.setSocketFactory(sslSocketFactory);

Authenticating by username and passwordAuthenticating by username and password

Since Yandex IoT Core requires the TLS protocol for authentication with a username and password, initialize the AdditionalKeyStoresSSLSocketFactory class with this method:

private SSLSocketFactory getSocketFactory(final InputStream caCrtFile, final InputStream devCert, final String password)

In devCert, provide the null value. This only loads the certificate from the server certification authority:

// Loading the CA certificate.
CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate caCert = (X509Certificate) cf.generateCertificate(caCrtFile);

// Using the CA certificate for server authentication.
KeyStore serverCaKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
serverCaKeyStore.load(null, null);
serverCaKeyStore.setCertificateEntry("ca", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(serverCaKeyStore);

return new AdditionalKeyStoresSSLSocketFactory(null, serverCaKeyStore);

In the connection settings, specify the username (registry or device ID) and password:

options.setUserName(mqttUserName);
options.setPassword(mqttPassword.toCharArray());

and the SSLSocketFactory you got from the above code:

options.setSocketFactory(sslSocketFactory);

Establish a connectionEstablish a connection

Establish a connection to Yandex IoT Core using the following code:

mqttAndroidClient.connect(options,null, new IMqttActionListener() {
   @Override
   public void onSuccess(IMqttToken asyncActionToken) {
   }

   @Override
   public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
   }
});

Subscribe to a topic and get data messagesSubscribe to a topic and get data messages

Use a callback function to process the received data:

mqttAndroidClient.setCallback(new MqttCallback() {
   @Override
   public void messageArrived(String topic, MqttMessage message) throws Exception {   }
});

Subscribe to a topic using the following code. In the subscribe method, specify the topic you want to subscribe to and the QoS level.

IMqttToken subToken = mqttAndroidClient.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
   @Override
   public void onSuccess(IMqttToken asyncActionToken) {
       // Publishing a message.
   }

   @Override
   public void onFailure(IMqttToken asyncActionToken,
                         Throwable exception) {
       // The message can't be subscribed to. The user may not have been
       // authorized to subscribe to the specified topic.
       System.out.println("Failed to subscribe");
   }
});

Send a data messageSend a data message

Send messages using the following code. In the publish method, specify the topic you want to send a message to and the message text. You can also specify the preferred QoS level for a MqttMessage class instance, if needed.

IMqttDeliveryToken publish = mqttAndroidClient.publish("<topic>", new MqttMessage("Your message text.".getBytes()));

Handle connection loss events and track message delivery using callback functions:

mqttAndroidClient.setCallback(new MqttCallback() {
   @Override
   public void connectionLost(Throwable cause) {

   }

   @Override
   public void deliveryComplete(IMqttDeliveryToken token) {

   }
});

Terminate the connectionTerminate the connection

Disconnect from Yandex IoT Core using the following methods:

mqttAndroidClient.disconnect();
mqttAndroidClient.close();

Where:

  • The disconnect method closes the connection to the server.
  • The close method releases the MqttAndroidClient class resources.

Was the article helpful?

Previous
Subscribing a device or registry to receive messages
Next
Working with Yandex IoT Core in C#
Yandex project
© 2025 Yandex.Cloud LLC