Using the Particle Android SDK

by Jun 23, 2017Particle

Add the Particle SDK to your Android Project

The very first step in getting your Android app to interface with the Particle Cloud is to add the Particle Android SDK to your Android project. This is done the same way that you would include any other dependency in your Android project and it is an easy task. All we need to do is add a single compile statement to the dependencies section of the Gradle build file.

So, in Android Studio, expand the Gradle Scripts section of the project file manager. Inside you will find two Gradle files. The one we need here is the one labeled build.gradle (Module: app).

opening Gradle build file

Open the build.gradle (Module: app) file

Now we need to add a line to the Gradle build file that will tell Gradle to compile the Particle Android SDK with our app. In the build.gradle file, you will find a dependencies element. Add the compile statement below underneath the other dependencies inside the dependencies element:

compile 'io.particle:cloudsdk:0.4.5'

The Gradle build file will look something like the one in the picture below. After adding the compile statement to the build.gradle file, you will need to sync the project to Gradle. Android Studio should give you a yellow prompt at the top of the screen with a link to sync the file.

compile statement

Add a compile statement to the build.gradle file.

Set up Android Manifest Permissions

Next up, using the Particle SDK to interface with the Particle Cloud obviously requires that the app access the Internet. We will need to add an element to the Android Manifest to give the app permission to access the device’s Internet connection.

To do this, expand the Manifests section in the Project file view. You should only have one file in this section, the AndroidManifest.xml file. Open this file.

Open the AndroidManifest.xml file

We will need to add an element to the Android Manifest to grant the app permission to access the Internet. Between the closing  </application> tag and the closing </manifest> tag, insert this statement:

<uses-permission android:name="android.permission.INTERNET" />

Your AndroidManifest.xml file should look something like the one in the picture below.

Android Manifest file

Initialize the Particle Android SDK

The final bit of setup we need to do before the Android app can use the Particle SDK is initializing the SDK. This is done in the Java class file for your current activity.

We will need to use the initialization method for the Particle SDK inside the onCreate method for your current activity. Place the line of code below inside the onCreate method, underneath the setContentView line:

ParticleCloudSDK.init(this);

When you are done, your Java class file will look a little like the one in the picture below. However, you may already have a lot more code in your Java file.

Initialize the Particle SDK

About Using AsyncTask

At this point, after adding the compile statement to the build.gradle file, the Internet permission element to the Android Manifest file, and the initialization statement to the Java class file, we are ready to start actually using the Particle Android SDK. For everything else we do using the SDK, we will need to be very familiar with the concept of asynchronous tasks in Android. If you are not familiar with the idea of synchronous versus asynchronous tasks, I would highly recommend brushing up on the subject before continuing with this tutorial because everything else on this page will involve using worker threads for Particle Cloud interactions.

If you just need a refresher, the basic idea of using asynchronous tasks in Android is take long-running operations that would normally clog up the user interface, and perform them in a background thread. Some tasks in Android are considered immediate. For example, taps on the screen, updates to on-screen elements, and interactions with menus are all considered immediate. However, some tasks, especially tasks involving an Internet connection, are not instantaneous. If we were to, for example, log in to the Particle Cloud in the main thread, the app would basically freeze for a few seconds while the app tries to connect. This is extremely bad for the user experience. This is so bad for the user experience, that Android actually forces network tasks to be performed in a separate thread so they do not interfere with the main part of the code execution. These actions performed in background threads are called AsyncTasks in Android.

In this tutorial, we will use the template below to create AsyncTasks for running Particle SDK actions. Multiple blocks like this one can be created for doing several things with the Particle SDK. For example, one block like the one below can be used to log in to the cloud, and another block can be used to subscribe to an event.

// Create a new AsyncTask for running Particle Cloud interactions
new AsyncTask<Void, Void, String>() {
    protected String doInBackground(Void... params) {
        try {
            // Add your Particle SDK code here to do something
            // with the Particle Cloud
            return "Some success message";
        }
        catch(ParticleCloudException e) {
            // We end up here if an error happens
            // Add code here to deal with errors
            Log.e(TAG, "Error: " + e.toString());
            return "Some error message";
        }
    }

    protected void onPostExecute(String msg) {
        // This code runs after the stuff in doInBackground finishes
        // Add code here to do something after the Particle Cloud 
        // stuff is done
    }
}.execute();

Log In to the Particle Cloud

It is finally time to start using the Particle SDK to do something useful. First let’s take a look at how to log in to the Particle Cloud. Logging in to the Particle Cloud is the first step in many of the other actions covered in this tutorial.

Just like every other action we will be performing with the Particle Android API, logging in to Particle will be done inside an AsyncTask object following the template above.

/* ///////////////////////////
   /// LOG IN TO PARTICLE ///
*/ //////////////////////////
new AsyncTask<Void, Void, String>() {
  protected String doInBackground(Void... params) {
      //  LOG IN TO PARTICLE
      try {
          // Log in to Particle Cloud using username and password
          ParticleCloudSDK.getCloud().logIn("your@username.com", "SecredPassword");
          return "Logged in!";
      }
      catch(ParticleCloudException e) {
          Log.e(TAG, "Error logging in: " + e.toString());
          return "Error logging in!";
      }
  }

  protected void onPostExecute(String msg) {
      // Show Toast containing message from doInBackground
      Toaster.s(WelloMainActivity.this, msg);
  }
  }.execute();

In this example, the Particle username and password are hard-coded into the function. Normally, however, you would probably not want to take this approach. There are any number of different ways you could place user-provided credentials into this method.

Subscribe to an Event

One of the major functions of the Particle Cloud is to allow different devices to share information by sending information to the Particle Cloud for other devices to receive and act upon. This section of the tutorial covers how to get the Android app to subscribe to events on the Particle Cloud.

First, of course, there must be events published by Particle devices for the app to receive. Particle devices can use the Particle.publish method to send information to the Particle Cloud. Particle events basically consist of strings that are sent to the Particle Cloud.

The particular events the Android app acts upon can be filtered in a number of ways. Events can be filtered so that the app responds only to events published by a particular device. The app can be made to act only upon events published by devices owned by the user. Events can also be filtered according to strings they contain. The example below filters the events so that the app acts only upon events that contain the string “example.”

Note that it is likely you will have multiple AsyncTask objects in your code to do different things with the Particle Cloud. For example, you might have used the code above to log in to the Particle Cloud. To do multiple things with the Particle Cloud, simply create a new AsyncTask object. In other words, you could copy/paste the code above to log in to the Particle Cloud, and then copy/paste the subscription code below and both would run.

/* ///////////////////////////
   /// SUBSCRIBE TO EVENT ///
*/ //////////////////////////
new AsyncTask<Void, Void, String>() {
  protected String doInBackground(Void... params) {
      try {
          // Subscribe to an event
          long subscriptionId = ParticleCloudSDK.getCloud().subscribeToAllEvents(
                  "example",  // Subscribe to events containing "example"
                  new ParticleEventHandler() {
                      // Trigger this function when the event is received
                      public void onEvent(String eventName, ParticleEvent event) {
                          Toaster.s(WelloMainActivity.this, 
                              "Example event happened!");
                      }

                      public void onEventError(Exception e) {
                          Log.e(TAG, "Event error: ", e);
                      }
                  });
          return "Subscribed!";
      }
      catch(IOException e) {
          // We end up here if there was an error subscribing
          Log.e(TAG, e.toString());
          return "Error subscribing!";
      }
  }

  // This code is run after the doInBackground code finishes
  protected void onPostExecute(String msg) {
      Toaster.s(WelloMainActivity.this, msg);
  }
  }.execute();

The code here is still based on the AsyncTask template from above. In this example, when an event is published to the Particle Cloud that fits the filtration you set up, in this case an event containing the string “example,” the app will run the code inside the onEvent function.

As another example, you may wish to have your app respond only to events published by a specific device. The code above uses the subscribeToAllEvents function and then filters the output by a string. In the example below, a different function is used to subscribe only to events from a specific device, by supplying the device ID. This function is subscribeToDeviceEvents.

/* ///////////////////////////
   /// SUBSCRIBE TO EVENT ///
*/ //////////////////////////
new AsyncTask<Void, Void, String>() {
  protected String doInBackground(Void... params) {
      try {
          // Subscribe to an event
          long subscriptionId = ParticleCloudSDK.getCloud().subscribeToDeviceEvents(
                  null,  
                  "53ff6c065075535119511687", // Subscribe to events from a specific device
                  new ParticleEventHandler() {
                      // Trigger this function when the event is received
                      public void onEvent(String eventName, ParticleEvent event) {
                          Toaster.s(WelloMainActivity.this, 
                              "Example event happened!");
                      }

                      public void onEventError(Exception e) {
                          Log.e(TAG, "Event error: ", e);
                      }
                  });
          return "Subscribed!";
      }
      catch(IOException e) {
          // We end up here if there was an error subscribing
          Log.e(TAG, e.toString());
          return "Error subscribing!";
      }
  }

  // This code is run after the doInBackground code finishes
  protected void onPostExecute(String msg) {
      Toaster.s(WelloMainActivity.this, msg);
  }
  }.execute();

Aside from the change in the function used, which changes the way the app responds to events, the rest of the code is exactly the same. This is a convenient model because it allows you to leave all your event response logic the same, and easily change the types of events to which your app responds.

Get a List of the User’s Devices

There are many reasons why, while developing your Android app, it would be useful to have a list of the Particle devices claimed by the current user. You can, for example, modify the subscription code above to subscribe only to devices owned by the current user. You can event get more specific than that. Once you have a list of the user’s device, a for loop can be used to go through the list of devices and subscribe only to devices with specific properties.

Before getting a list of the user’s devices, your app must use the code above to log in to the Particle cloud. After logging in, we will once again use an AsyncTask object to get a list of the user’s devices. Since you probably want your list of devices to be accessible outside the AsyncTask used to get the list, we will start by creating a List interface to store the device list. Place the statement below above the onCreate method in your activity Java class file.

// Create a list interface to store a list of the user's devices
List <ParticleDevice > devices;

The beginning part of your activity Java class file will look something like the image below.

create list interface

Create a List interface to store the list of the user’s devices.

With a list interface created to store the list of devices, we can create the actual AsyncTask, again following the template, to populate the list.

/*  ///////////////////////////
     ///  GET USER DEVICES   ///
*/  ////////////////// /////////
new AsyncTask <Void, Void, String >() {
    // Get a list of the user's devices
    protected String doInBackground(Void... params) {
        try {
            devices = ParticleCloudSDK.getCloud().getDevices();
            return devices.toString();
        }
        catch(ParticleCloudException e) {
            Log.e(TAG, e.toString());
            return "Error getting devices!";
        }
    }

    protected void onPostExecute(String msg) {
        Log.d(TAG, msg);
    }
}.execute();

This code will return a list of ParticleDevice objects. It will probably be useful to loop through the devices, so you can perform some action on each one, or check the properties of each one as a way of selecting certain devices with which to interact. You can loop through the list using the for statement below.

for(int i = 0; i < devices.size(); i++) {
    // Do something with each device in here
}

The Particle Android SDK allows you to get a bunch of information about each device:

// 'myDevice' here is a ParticleDevice instance
String nameString = myDevice.getName();
int productIdInt = myDevice.getProductID();
int platformIdInt = myDevice.getPlatformID();
String ipAddressString = myDevice.getIpAddress();
String lastNameString = myDevice.getLastAppName();
String statusString = myDevice.getStatus();
Date lastHeardDate = myDevice.getLastHeard();
boolean cellularBoolean = myDevice.isCellular();
String imeiString = myDevice.getImei();
String currentBuildString = myDevice.getCurrentBuild();
String defaultBuildString = myDevice.getDefaultBuild();

Doing Other Things

There are many other ways to use the Particle Android SDK, and the Particle Cloud in general, for your projects. Check out the documentation for the Particle Android SDK for a full list of functions to try. The SDK is fairly big, so this tutorial will not cover everything. But, if you are planning to use any of the other functions provided by the Particle Android SDK, just remember to use the AsyncTask template above to handle all your Particle Cloud interactions.

Share This