This blog post was written under the Pusher Guest Writer program.

We’d like to track and visualize our applications in a central place. Feeds are great for this! Let’s build an Android app with an activity feed showing the temperature of your home.

In this tutorial, using Pusher, we are going to build a feed as an Android app to monitor the activity of a Node.js REST API. Every time an endpoint of the API is hit, it will publish an event with some information (let’s say temperatures) to a channel. This event will be received in realtime, on all the connected Android devices.

This is how our final Android app will look like:

The app is simple, but this tutorial assumes a basic knowledge of how to make Android apps. If you need it, the source code of the final version of the application is available on Github.

For the back-end, we will be using Node.js with Express to create a simple REST API. A basic knowledge of Node/Express is required to understand the code, but we won’t be using a database or anything special so you can replace this stack with the one you’re most comfortable with. The source code of this part is also available on Github.

So let’s get started!

Setting up Pusher

Create a free account at https://pusher.com/signup.

When you first log in, you’ll be asked to enter some configuration options:

Enter a name, choose Android as your front-end tech, and Node.js as your back-end tech. This will give you some sample code to get you started:

But don’t worry, this won’t lock you into this specific set of technologies, you can always change them. With Pusher, you can use any combination of libraries.

Then go to the App Keys tab to copy your App ID, Key, and Secret credentials, we’ll need them later.

The Node server

First, let’s create a default package.json configuration file with:

npm init -y

We’ll need Express, Pusher, and other dependencies, let’s add them with:

npm install --save express body-parser pusher

In case a future version of a dependency breaks the code, here’s the dependencies section on the package.json file:

{
  ...
    "dependencies": {
    "body-parser": "1.16.0",
    "express": "4.14.1",
    "pusher": "1.5.1"
  }
}

Next, create a server.js file. First, let’s require the modules we’re going to need:

var express = require('express');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var Pusher = require('pusher');

Then, configure the Express object:

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Next, the Pusher object is created by passing the configuration object with the ID, key, and the secret for the app created in the Pusher Dashboard:

var pusher = new Pusher({
  appId      : process.env.PUSHER_APP_ID,
  key        : process.env.PUSHER_APP_KEY,
  secret     : process.env.PUSHER_APP_SECRET,
  encrypted  : true,
});

Pusher will be used to publish any events that happen in our application. These events have a channel, which allows events to relate to a particular topic, an event-name used to identify the type of the event, and a payload, which you can attach any additional information to the message.

We are going to publish an event to a Pusher channel when an endpoint of our API is called to create/update/delete a record, and send the information as an attachment so we can show it in an activity feed.

Here’s the definition of our API’s REST endpoints. Notice how an ID for the record is created using the first four characters of the hex string generated by crypto.randomBytes(16) (to avoid using an external library):

app.post('/api', function (req, res) {
  var event = {
    data: req.body.data,
    id: crypto.randomBytes(16).toString('hex').substring(0, 4),
  };

  // Do something with the data...

  // Publish event to the Pusher channel
  pusher.trigger(channel, 'created', event);

  res.status(200).json(event);
});

app.route('/api/:id')
  // PUT  endpoint to update a record
  .put(function (req, res) {
    var event = {
     data: req.body.data,
     id: req.params.id,
    };

    // Do something with the data...

    // Publish event to the Pusher channel
    pusher.trigger(channel, 'updated', event);

    res.status(200).json(event);
  })

  // DELETE  endpoint to delete a record
  .delete(function (req, res) {
    var event = {
      id: req.params.id,
    };

    // Do something with the data...

    // Publish event to the Pusher channel
    pusher.trigger(channel, 'deleted', event);

    res.status(200).json(event);
  });

This way, a POST request like this:

{
  "data": "Temperature: 75°F"
}

Will return something like the following:

{
  "data": "Temperature: 75°F",
  "id": "d2t6"
}

We start the server with:

app.listen(3000, function () {
  console.log('Node server running on port 3000');
});

And that’s all. To run the server, execute the following command passing your Pusher credentials:

PUSHER_APP_ID=XXXXXX PUSHER_APP_KEY=XXXXXX PUSHER_APP_SECRET=XXXXXX node server.js

The Android app

Open Android Studio and create a new project:

We’re not going to use anything special, so we can safely support a low API level:

Next, create an initial empty activity:

And use the default name of MainActivity with backward compatibility:

Once everything is set up, let’s install the project dependencies. In the dependencies section of the build.gradle file of your application module add:

dependencies {
    ...
    compile 'com.pusher:pusher-java-client:1.4.0'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.github.curioustechizen.android-ago:library:1.3.2'
    compile 'com.google.code.gson:gson:2.4'
    ...
}

At the time of this writing, the latest SDK version is 25, so that’s my target SDK version.

We’re going to use the RecyclerView and CardView components from the Support Library, so make sure you have it installed (in Tools -> Android -> SDK Manager -> SDK Tools tab the Android Support Repository must be installed).

Sync the Gradle project so the modules can be installed and the project built.

Before we forget (I always do), let’s add the INTERNET permission to the AndroidManifest.xml file. This is required so we can connect to Pusher and get the events in realtime:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pusher.feed">

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

    <application
        ...
    </application>

</manifest>

If you want to modify the style of the app, in the res/values folder, modify the colors.xml file so it looks like this:

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <color name="primary">#03A9F4</color>
    <color name="primary_dark">#0288D1</color>
    <color name="primary_light">#B3E5FC</color>
    <color name="accent">#FF4081</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#757575</color>
    <color name="icons">#FFFFFF</color>
    <color name="divider">#BDBDBD</color>
</resources>

As well as the styles.xml file to match these color definitions:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
    </style>

</resources>

Now, modify the layout file activity_main.xml so it looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.pusher.feed.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/recycler_view"
        android:scrollbars="vertical" />
</RelativeLayout>

We’re going to use a RecyclerView to display the events, which we’ll store in a list. Each item in this list is displayed in an identical manner, so let’s define another layout file to inflate each item.

Create the file event_row.xml with the following content:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="4dp"
    card_view:cardUseCompatPadding="true"
    card_view:contentPadding="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Event"
            android:id="@+id/event"
            android:layout_alignParentTop="true"
            android:textAlignment="center" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="ID"
            android:id="@+id/id"
            android:layout_below="@+id/event"
            android:textAlignment="center" />

        <com.github.curioustechizen.ago.RelativeTimeTextView
            android:id="@+id/timestamp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:layout_below="@+id/id"
            android:textAlignment="center" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Data"
            android:id="@+id/data"
            android:layout_below="@+id/timestamp"
            android:textAlignment="center"
            android:layout_marginTop="8dp" />
    </RelativeLayout>

</android.support.v7.widget.CardView>

Here we’re using a CardView to show the information inside a card, with shadows and rounded corners. For each item, we’re going to present:

  • A TextView for the name of the event (created, updated, or deleted).
  • A TextView for the ID of the record (for example, c2d6).
  • A RelativeTimeTextView, a custom TextView that displays the relative time with respect to the reference point (the moment the event is received), automatically refreshing the text as needed.
  • A TextView for the data contained in the record (anything the user sends, for example, Temperature: 80°F).

Now, to store the information of each event, let’s create a class, com.pusher.feed.Event:

public class Event  {
    private String name;
    private String id;
    private String data;

    public Event(String name, String eventId, String data) {
        this.name = name;
        this.id = eventId;
        this.data = data;
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getData() {
        return data;
   }
}

RecyclerView works with an Adapter to manage the items of its data source (in this case a list of Event instances), and a ViewHolder to hold a view representing a single list item, so first create the class com.pusher.feed.EventAdapter with the following code:

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
    private List<Event> items;

    public EventAdapter(List<Event> items) {
        this.items = items;
    }

    public void addEvent(Event event) {
        // Add the event at the beginning of the list
        items.add(0, event);
        // Notify the insertion so the view can be refreshed
        notifyItemInserted(0);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    @Override
    public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    }

    @Override
    public void onBindViewHolder(EventViewHolder viewHolder, int i) {

    }
}

We initialize the class with a list of Event, provide a method to add Event instances at the beginning of the list (addEvent(Event)) and then notify the insertion so the view can be refreshed, and implement getItemCount so it returns the size of the list.

Then, let’s add the ViewHolder as an inner class, it references the View components for each item in the list:

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
    private ArrayList<Event> items;

    public static class EventViewHolder extends RecyclerView.ViewHolder {
        // Card fields
        public TextView event;
        public TextView id;
        public RelativeTimeTextView timestamp;
        public TextView data;

        public EventViewHolder(View v) {
            super(v);
            event = (TextView) v.findViewById(R.id.event);
            id = (TextView) v.findViewById(R.id.id);
            timestamp = (RelativeTimeTextView) v.findViewById(R.id.timestamp);
            data = (TextView) v.findViewById(R.id.data);
        }
    }

    ...
}

And implement the methods onCreateViewHolder and onBindViewHolder:

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
    ...

    @Override
    public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.event_row, viewGroup, false);

        return new EventViewHolder(v);
    }

    @Override
    public void onBindViewHolder(EventViewHolder viewHolder, int i) {
        Event event = items.get(i);

        viewHolder.event.setText(event.getName());
        viewHolder.id.setText(event.getId());
        viewHolder.timestamp.setReferenceTime(System.currentTimeMillis());
        viewHolder.data.setText(event.getData());
    }
}

In the onCreateViewHolder method, we inflate the layout with the content of the event_row.xml file we created earlier, and in onBindViewHolder, we set the values of the views with the event in turn. Notice how we set the reference time on RelativeTimeTextView so it can display a text like Just now or 10 minutes ago.

In the class com.pusher.feed.MainActivity, let’s start by defining the private fields we’re going to need:

public class MainActivity extends AppCompatActivity {
    private RecyclerView.LayoutManager lManager;
    private EventAdapter adapter;
    private Pusher pusher = new Pusher("ENTER_PUSHER_APP_KEY_HERE");
    private static final String CHANNEL_NAME = "events_to_be_shown";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ....
    }
}

RecyclerView works with a LayoutManager to handle the layout and scroll direction of the list. We declare the EventAdapter, the Pusher object and the identifier for the Pusher channel. Remember to replace your Pusher app key, if you still don’t have one, this would be a good time to sign up for a free account and create you app.

Inside the onCreate method, let’s assign a LinearLayoutManager to the RecyclerView and create the EventAdapter with an empty list:

public class MainActivity extends AppCompatActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the RecyclerView
        RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler_view);

        // Use LinearLayout as the layout manager
        lManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(lManager);

        // Set the custom adapter
        List<Event> eventList = new ArrayList<>();
        adapter = new EventAdapter(eventList);
        recycler.setAdapter(adapter);
    }
}

For the Pusher part, we first subscribe to the channel:

public class MainActivity extends AppCompatActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        Channel channel = pusher.subscribe(CHANNEL_NAME);
}

Then, we create the listener that will be executed when an event arrives:

public class MainActivity extends AppCompatActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    SubscriptionEventListener eventListener = new SubscriptionEventListener() {
            @Override
            public void onEvent(String channel, final String event, final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("Received event with data: " + data);
                        Gson gson = new Gson();
                        Event evt = gson.fromJson(data, Event.class);
                        evt.setName(event + ":");
                        adapter.addEvent(evt);
                        ((LinearLayoutManager)lManager).scrollToPositionWithOffset(0, 0);
                    }
                });
            }
        };
    }
}

Here, the JSON string that we receive is converted to an Event object, the name of the event is set to the name of the event received, and the object is added to the adapter. Finally, we move to the top of the list.

Next, bind the events to this listener and call the connect method on the Pusher object:

public class MainActivity extends AppCompatActivity {
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        channel.bind("created", eventListener);
        channel.bind("updated", eventListener);
        channel.bind("deleted", eventListener);

        pusher.connect();
    }
}

The connect method can take a listener that can be helpful to debug problems you might have:

pusher.connect(new ConnectionEventListener() {
    @Override
    public void onConnectionStateChange(ConnectionStateChange change) {
        System.out.println("State changed to " + change.getCurrentState() +
            " from " + change.getPreviousState());
    }

   @Override
    public void onError(String message, String code, Exception e) {
        System.out.println("There was a problem connecting!");
        e.printStackTrace();
    }
});

Finally, MainActivity also needs to implement the onDestroy() method so we can have the opportunity to unsubscribe from Pusher when the activity is destroyed:

public class MainActivity extends AppCompatActivity {
    ...

    @Override
    public void onDestroy() {
        super.onDestroy();
        pusher.disconnect();
    }
}

And that’s all the code on the Android part. Let’s test it.

Testing the app

Execute the app, either on a real device or a virtual one:

You’ll be presented with an almost blank screen:

For the back-end, you can use something to call the API endpoints with a JSON payload, like cURL:

# POST
curl -H "Content-Type: application/json" -X POST -d '{"data":"Temperature: 80°F"}' http://localhost:3000/api
# PUT
curl -H "Content-Type: application/json" -X PUT -d '{"data":"Temperature: 85°F"}' http://localhost:3000/api/aqw3
# DELETE
curl -X DELETE http://localhost:3000/api/aqw3

# In Windows, change single quotes to quotation marks and escape the ones inside curly brackets
curl -H "Content-Type: application/json" -X POST -d "{\"data\":\"Temperature: 80°F\"}" http://localhost:3000/api

# Or use file, for example data.json
curl -H "Content-Type: application/json" -X POST --data @data.json http://localhost:3000/api

Or use a tool like Postman:

When a request is received on the API side, the event will show up in the app:

Or if you only want to test the app, you can use the Pusher Debug Console on your dashboard:

Conclusion

You can find the final version of the server here and the final version of the Android app here.

Hopefully, this tutorial has shown you in an easy way how to build an activity feed for Android apps with Pusher. You can improve the app by changing the design, showing more information, or saving it to a database. Remember that your forever free Pusher account includes 100 connections, unlimited channels, 200k daily messages, SSL protection, and there are more features than just Pub/Sub Messaging. Sign up here.

Further reading