Just a second...

Start publishing with Android

Create an Android™ client that publishes data through topics on Diffusion™ Cloud .

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 a named user that has a role with the modify_topic and update_topic permissions. For example, the "ADMINISTRATOR" role. For more information about roles and permissions, see Role-based authorization.

This example steps through the lines of code required to publish to a JSON 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 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.control.topics.TopicControl;
    import com.pushtechnology.diffusion.client.features.control.topics.TopicUpdateControl;
    import com.pushtechnology.diffusion.client.session.Session;
    import com.pushtechnology.diffusion.client.session.SessionFactory;
    import com.pushtechnology.diffusion.client.topics.details.TopicType;
    import com.pushtechnology.diffusion.datatype.json.JSON;
    import com.pushtechnology.diffusion.datatype.json.JSONDataType;
    
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicInteger;
              
    public class MainActivity extends AppCompatActivity {
    
    }

    The com.pushtechnology.diffusion.client packages contain the classes to use to interact with Diffusion Cloud .

  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, add the code required to create the foo/counter topic and update it with an incrementing value.
    1. Use the TopicControl feature to create a JSON topic.
                  // Create a JSON topic 'foo/counter'
                  session.feature(TopicControl.class).addTopic(
                      "foo/counter",
                      TopicType.JSON,
                      new TopicControl.AddCallback.Default());
    2. Get the TopicUpdateControl feature and JSON data type.
                   // Get the TopicUpdateControl feature and JSON data type
                   final JSONDataType jsonDataType = Diffusion.dataTypes().json();
                   final TopicUpdateControl updateControl = session
                   .feature(TopicUpdateControl.class);
    3. Loop once a second updating the foo/counter topic with an incrementing count from 0 to 1000.
      Use the non-exclusive updateControl.updater().update() method to update the topic while still allowing other clients to update the topic.
                final AtomicInteger i = new AtomicInteger(0);
                
                Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                    // Create the json value
                    final JSON value = jsonDataType.fromJsonString(
                        String.format("{\"count\" : %d }", i.getAndIncrement()));
                
                    // Update the topic
                    updateControl.updater().update(
                    "counter",
                    value,
                    new TopicUpdateControl.Updater.UpdateCallback.Default());
                    }
                }, 1000, 1000, TimeUnit.MILLISECONDS);
                  
  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 .
        @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);
                  }
            }
    Or you can connect securely, using Secure Sockets Layer (SSL):
        Diffusion.sessions().principal("principal").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 publishes a JSON value to the foo/counter topic every second. You can subscribe to the foo/counter topic by using the Diffusion Cloud Dashboard's test client or by creating a client to subscribe to the topic. For more information, see Start subscribing with Android.

Full example

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

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.control.topics.TopicControl;
import com.pushtechnology.diffusion.client.features.control.topics.TopicUpdateControl;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.client.session.SessionFactory;
import com.pushtechnology.diffusion.client.topics.details.TopicType;
import com.pushtechnology.diffusion.datatype.json.JSON;
import com.pushtechnology.diffusion.datatype.json.JSONDataType;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

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;


            // Create a JSON topic 'foo/counter'
            session.feature(TopicControl.class).addTopic(
                "foo/counter",
                TopicType.JSON,
                new TopicControl.AddCallback.Default());


            // Get the TopicUpdateControl feature and JSON data type
            final JSONDataType jsonDataType = Diffusion.dataTypes().json();
            final TopicUpdateControl updateControl = session
                    .feature(TopicUpdateControl.class);


            final AtomicInteger i = new AtomicInteger(0);

            // Schedule a recurring task that increments the counter and updates the "counter" topic with a json value
            // every second
            Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    // Create the json value
                    final JSON value = jsonDataType.fromJsonString(
                        String.format("{\"count\" : %d }", i.getAndIncrement()));
            
                    // Update the topic
                    updateControl.updater().update(
                        "counter",
                        value,
                        new TopicUpdateControl.Updater.UpdateCallback.Default());
                }
            }, 1000, 1000, TimeUnit.MILLISECONDS);
        }

        @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("ws://host:port", sessionHandler);
        }
    }

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

        super.onDestroy();
    }
}