Just a second...

Start subscribing with Android

Create an Android™ client application within minutes that connects to Diffusion™ Cloud . This example creates a client that prints the value of a JSON topic to the console when the topic is updated.

To complete this example, you need Android Studio installed on your development system and a Diffusion Cloud service. For more information about getting a Diffusion Cloud service, see Getting started with Diffusion Cloud.

This example was tested in Android Studio 2.3.3. If you are using a different version of Android Studio, the details of some steps may vary slightly.

You also require that anonymous client connections are assigned a role with the select_topic and read_topic permissions. For example, the "CLIENT" role. For more information about roles and permissions, see Role-based authorization.

This example steps through the lines of code required to subscribe to a topic. The full code example is provided after the steps.
  1. Set up a project in Android Studio that uses the Diffusion API.
    1. Create a new project using API Level 21 or later.
    2. Copy the diffusion-android-x.x.x.jar file into the app/libs folder of your project.
    3. In Android Studio, right-click on the libs folder in the left-hand panel (the Project Tool Window), then select Add as Library.
      If the libs folder is not shown in the left-hand panel, use the pull-down menu at the top of the panel to select Project view.
  2. In your project's AndroidManifest.xml file set the INTERNET permission.
    <uses-permission android:name="android.permission.INTERNET"/>
    Insert the element between the opening <manifest> tag and the opening <application> tag. This permission is required to use the Diffusion API .
  3. Open your project's MainActivity.java file.
    This file is where you develop the code to interact with Diffusion Cloud .
    The empty MainActivity.java file contains the following boilerplate code:
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }
  4. Import the following packages and classes:
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
                        
    import com.pushtechnology.diffusion.client.Diffusion;
    import com.pushtechnology.diffusion.client.callbacks.ErrorReason;
    import com.pushtechnology.diffusion.client.features.Topics;
    import com.pushtechnology.diffusion.client.features.Topics.TopicStream;
    import com.pushtechnology.diffusion.client.session.Session;
    import com.pushtechnology.diffusion.client.session.SessionFactory;
    import com.pushtechnology.diffusion.client.topics.details.TopicSpecification;
    import com.pushtechnology.diffusion.datatype.json.JSON;
    import com.pushtechnology.diffusion.datatype.json.JSONDataType;
    
    public class MainActivity extends AppCompatActivity {
    
    }
  5. Create a SessionHandler inner class that implements SessionFactory.OpenCallback.
    This inner class will contain the code that interacts with Diffusion Cloud .
    private class SessionHandler implements SessionFactory.OpenCallback {
        private Session session = null;
    
        @Override
        public void onOpened(Session session) {
            this.session = session;
        }
    
        @Override
        public void onError(ErrorReason errorReason) {
            
        }
    
        public void close() {
            if ( session != null ) {
                session.close();
            }
        }
    }
  6. In the onOpened method, create the code required to subscribe to the foo/counter topic.
    1. Get the Topics feature.
          // Get the Topics feature to subscribe to topics
          final Topics topics = session.feature( Topics.class );
    2. Add an instance of Topics.ValueStream.Default<JSON> as the topic stream for the foo/counter topic, and subscribe to the topic.
          topics.addStream("foo/counter", JSON.class, new Topics.ValueStream.Default<JSON>() {
              @Override
              public void onSubscription(String topicPath, TopicSpecification specification) {
                  Log.i("diffusion", "Subscribed to: " + topicPath);
          }
    3. Override the onValue method to print the value of the topic to the log when it changes.
              @Override
              public void onValue(
                  String topicPath,
                  TopicSpecification specification,
                  JSON oldValue,
                  JSON newValue) {
                  
                  Log.i("diffusion", topicPath + ": " + newValue.toJsonString());
              }
  7. In the MainActivity class, declare an instance of session handler.
        private SessionHandler sessionHandler = null;
  8. Override the onCreate method of the MainActivity class to open the session with Diffusion Cloud .
        private SessionHandler sessionHandler = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            if (sessionHandler == null) {
                sessionHandler = new SessionHandler();
    
                Diffusion.sessions()
                    .principal("username")
                    .password("password")
                    .open("ws://host:port", sessionHandler);
                }
            }
    You can connect securely, using Secure Sockets Layer (SSL):
            Diffusion.sessions().open("wss://host:443", sessionHandler);
    Or you can connect with a principal and credentials if that principal is assigned a role with the select_topic and read_topic permissions:
            Diffusion.sessions().principal("username").password("password").open("wss://host:443", sessionHandler);
    Replace the host, principal, and password values with your own information.
  9. Override the onDestroy method of the MainActivity class to close the session with Diffusion Cloud .
            if ( sessionHandler != null ) {
                sessionHandler.close();
                sessionHandler = null;
            }
            super.onDestroy();
  10. Compile and run your client.

The client outputs the value to the log console every time the value of the foo/counter JSON topic is updated. You can update the value of the foo/counter topic by using the Diffusion Cloud Dashboard's test client or by creating a publishing client to update the topic. To create and publish to the foo/counter topic, you require a user with the modify_topic and update_topic permissions. For more information, see Start publishing with Android.

Full example

The completed MainActivity class contains the following code:
package com.pushtechnology.demo.subscribe;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.callbacks.ErrorReason;
import com.pushtechnology.diffusion.client.features.Topics;
import com.pushtechnology.diffusion.client.features.Topics.TopicStream;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.client.session.SessionFactory;
import com.pushtechnology.diffusion.client.topics.details.TopicSpecification;
import com.pushtechnology.diffusion.datatype.json.JSON;
import com.pushtechnology.diffusion.datatype.json.JSONDataType;

public class MainActivity extends AppCompatActivity {
    /**
     * A session handler that maintains the diffusion session.
     */
    private class SessionHandler implements SessionFactory.OpenCallback {
        private Session session = null;

        @Override
        public void onOpened(Session session) {
            this.session = session;

            // Get the Topics feature to subscribe to topics
            final Topics topics = session.feature( Topics.class );

            // Subscribe to the "counter" topic and establish a JSON value stream
            topics.addStream("foo/counter", JSON.class, new Topics.ValueStream.Default<JSON>() {
                @Override
                public void onSubscription(String topicPath, TopicSpecification specification) {
                    Log.i("diffusion", "Subscribed to: " + topicPath);
                }
                    
                @Override
                public void onValue(
                    String topicPath,
                    TopicSpecification specification,
                    JSON oldValue,
                    JSON newValue) {
                                            
                    Log.i("diffusion", topicPath + ": " + newValue.toJsonString());
                }
          });

            topics.subscribe("foo/counter", new Topics.CompletionCallback.Default());

        }

        @Override
        public void onError(ErrorReason errorReason) {
            Log.e( "Diffusion", "Failed to open session because: " + errorReason.toString() );
            session = null;
        }

        public void close() {
            if (session != null) {
                session.close();
            }
        }
    }

    private SessionHandler sessionHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (sessionHandler == null) {
            sessionHandler = new SessionHandler();

            Diffusion.sessions()
                     .principal("username")
                     .password("password")
                     .open("wss://host:port", sessionHandler);

        }
    }

    @Override
    protected void onDestroy() {
        if (sessionHandler != null ) {
            sessionHandler.close();
            sessionHandler = null;
        }

        super.onDestroy();
    }
}

}