, our weekly sponsor, makes communication and collaboration APIs that power apps all over the world, supported by easy to integrate SDKs for web, mobile, as well as most popular backend stacks. Pusher Get started. Often times we like to track and visualize our applications in a central place. Feeds are great for this! In this tutorial, we’ll build an Android app with an activity feed that allows users to broadcast their locations and share with all other connected users in realtime. We’ll build the Android app to monitor the activities of a REST API. Every time the endpoint of the API is hit, Pusher will publish an event with some information (location shared by the user) to a channel. This event will be received in realtime, on all the connected Android devices. Node.js Here’s the app in action: Prerequisites This tutorial uses the following technologies Pusher Android Studio Node To follow along, you’ll need to and gain access to your dashboard to create a Pusher project. You will also need to have Android Studio v3+ installed to build the client part of this application. To build our server side script, you’ll need to if you don’t already have it installed. sign up with Pusher download and install Node Client side Now that you have that sorted out, let’s start building our Android app. Launch Android Studio and create a new project. Be sure to include Kotlin support. Enter an application name, in our case — Pusher-Location-Feeds Select application’s target SDK: Choose the basic activity template: When the project build is completed, open your app level file and update the dependencies like so: build.gradle Next, sync the project by clicking with the gradle file to install the added dependencies. Sync Now Application activities Login activity By default creating the Android project also creates a class and an associating file for you. Now we need a login Activity to collect the users username. So create a new activity, right-click on , then name it . Once this activity is created, it’ll create a default layout file inside the folder under . The layout will be a rather simple one, it will have a text input to collect the user’s and a button to share their location. Here’s a snippet for the file: MainActivity activity_main.xml MainActivity >> New >> Activity >> Empty Activity LoginActivity activity_login.xml layout res username activity_login.xml Here we have a simple with two view objects, an input to collect the user’s and a share button to send the location to the server. LinearLayout EditText username Android default styling isn’t always appealing so let’s add some custom styles to our layout simply for aesthetic purposes. Under folder, open the folder and navigate into file and update it with this code : res values colors.xml Secondly to achieve the button and Input styles, we create two files. Under right-click on , name it and update it with this code: drawable res drawable >>New >> Drawable resource file input_bg This simply adds round edges to the EditText object. For the button styles, follow the same steps as the one above and create a new drawable file, name it and set it up like so: button Finally update your file inside the folder in the directory: styles.xml values layout At this point, your output in the xml visualizer should look exactly like this: Next let’s create a new layout file called . We’ll use this file to render each individual map of a user on our recyclerview object. Inside the folder under , create the new layout resource file and set it up like so: custom_view.xml layout res Okay, we are done with login and UI lets hook it up with it’s Java file to handle the logic. Open file and set it up like so: LoginActivity.kt Here we are simply getting the value of the input we defined in the layout file and passing it into the class with an intent . Once the user has entered a value (username) in the object, we set a listener on the button to call the intent action when clicked. This action will only execute if the input value is not empty. MainActivity Edittext MainActivity Next we define a layout where we’ll render the map locations of each user when they share their location. We’ll get their latitude and longitude coordinates along with the username they provided in the and send it to our server, which then returns a map of the location with the provided username on the map-marker and display it on screen for all users. LoginActivity Before we get into MainActivity, let’s first define a new layout file with a RecyclerView object to hold these location widgets as the users share them. Under , right-click on and name it , (if you selected the basic activity template while setting up the project, then you should have this file by default). Open this file and set it up like so: res layout >> New >> Layout resource file content_main As seen, we simply have a RecyclerView object where we’ll render each individual user’s location so they can all appear in a list. Lastly, Open up and update it: activity_main.xml Application logic Since we used a RecyclerView in our layout file, we’ll need an adapter class. works with an to manage the items of its data source and a to hold a view representing a single list item. Before we create the class, lets first create a class that will interface between our remote data and the adapter. It’ll have the values that we’ll pass data to our recyclerview. Now right-click on , name it under the dropdown, select and set it up like so: RecyclerView Adapter ViewHolder Adapter Model MainActivity >> New >> Kotlin File/Class Model, Kind Class Now that we have that, lets create the class. Right-click on , name it , under the dropdown, select Class again and set it up with the code: Adapter MainActivity >> New >> Kotlin File/Class Adapter Kind Here we have defined an from our Model class that will be used by the adapter to populate the . In the method, we bind the locations coming from our server (as longitude and latitude) to the view holder we defined for it. We also passed the user’s username to the map marker. arrayList R``ecycler``V``iew onBindViewHolder() Then in the method we define the design of the layout for individual items on the list. Finally the method adds a new instance of our model class to the and refresh the list every time we get a new addition. onCreateViewHolder() addItem() arrayList Next let’s establish a connection to our Node server using the Retrofit library we installed at the beginning. First we create a new Kotlin interface to define the API endpoint we’ll be calling for this project. Right-click on , under the dropdown, select Interface name it and set it up like so: MainActivity >> New >> Kotlin File/Class Kind Service We also need a class that’ll give us an instance of Retrofit for making networking calls. It’ll also be the class where we’ll define the server URL and parameters. So follow the previous steps and create a class called and set it up like this: network Client.kt Replace the Base URL with your localhost address for the Node server. We’ll The we used here points to our local Node server running on your machine as shown above but we’ll get to that later on in the tutorial. For now let’s go back to and initialize the necessary objects and update it with the classes we’ve created above. baseUrl MainActivity.kt Here we’ve just initialized the objects we’ll need, our Adapter class, Pusher, location request and the . fusedLocationClient In the method we’ll setup our RecyclerView with the adapter. We’ll also call the method and the action with the floating action button: onCreate() setupPusher() sendLocation() While adding this code to your _onCreate()_ method, be careful not to miss the curly braces So we called methods we haven’t defined yet, that’s no problem we’ll define the method later on in the tutorial but first off, let’s define and setup the method this time, outside the : setupPusher() sendLocation() onCreate() With the object we initialized earlier, we are getting the user’s location. If we succeed in getting the location, we pass the the longitude and latitude along with the user’s into our object. We then use it to build our HTTP request with the as our request parameters. fusedLocationClient username body jsonObjects We also called the method in the method however we haven’t defined it yet. Lets now create this method and set it up like so: checkLocationPermission() onCreate() Of course we can’t just grab every user’s location without first asking for their permission, so here’s how we set up the method that requests permission to access their location. Just after the method, add:x sendLocation() And now let’s define the method we called earlier in the method: setUpPusher() onCreate() Here we simply pass in our Pusher configs to the Pusher object and subscribe to the channel to listen for events. Then we get the data returned from the server into our defined variables and pass them to our model class to update the adapter. feed location Next we implement the and methods to connect and disconnect Pusher respectively in our app: onStart() onStop() Finally on the client side, we create a Kotlin data class that will define the payload we’ll be requesting from the server. Following the previous steps, create a class called and set it up like so: RequestPayload Server side Set up Pusher Now that we have all the client side functionalities, lets go ahead and build our server. But first, if you haven’t, now will be a good time to create a free account . When you first log in, you’ll be asked to enter some configuration options: here Enter a name, choose as your front-end , and as your back-end tech. This will give you some sample code to get you started along with your project api keys: Android tech Node.js Then go to the tab and copy your app_id, key, and secret credentials, we’ll need them later. App Keys Set up a Node server For this we will use Node. So check that you have and installed on your machine by running this command in command prompt: node npm node --version//should display version numbers npm --version//should display version numbers If that is not the case, . Download and Install Node Next lets start building our server side script. Still in command prompt, run: mkdir pusherLocationFeeds//this creates a project directory to host your project files cd pusherLocationFeeds// this navigates into the just created directory npm init -y//this creates a default package.json file to host our project dependencies Let’s install the Node modules we’ll need for this project. Basically we’ll need Express, Pusher and body-parser. Inside the project directory, run: install express, body-parser, pusher You can always verify these installations by opening your `package.json` file, at this point the dependency block should look like this: "dependencies": {"body-parser": "^1.18.2","express": "^4.16.3","pusher": "^1.5.1"} Next create a server.js file in the project directory. First we require the Node modules we installed: var express = require("express")var pusher = require("pusher")var bodyParser = require("body-parser") Next we configure Express: var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false })); Lets now create the Pusher object 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: "pusher_app_id",key: "pusher_app_key",secret: "pusher_app_secret",cluster: "pusher_app_cluster"}); As we described earlier, we’ll use Pusher to publish events that happen in our application. These events have an , which allows them to relate to a particular topic, an that is used to identify the type of the event, and a , which you can attach any additional information to and send back to the client. eventChannel eventName payload In our case, we’ll publish an event to a Pusher channel (“feed”) when the endpoint of our API is called. Then send the information as an attachment so we can show it in an activity feed on the client side. Here’s how we define our API’s REST endpoint: app.post('/location', (req, res,next)=>{ var longitude = req.body.longitude; var latitude = req.body.latitude; var username = req.body.username; ... Here when we receive request parameters, we’ll extract the longitude, latitude and the username of the sender from the request and send back as response to the client like so: ...pusher.trigger('feed', 'location', {longitude, latitude,username});res.json({success: 200});}); Now when a user types in a username and clicks the share location button, the server returns the data like: {"longitude" : "longitude_value""latitude" : "latitude_value""username" : "username_value"} From here, we then use the to pass it to the and lay it out on the screen.When you’re done, your server.js file should look like this: adapter ViewHolder var pusher = require("pusher")var express = require("express")var Pusher = require("pusher")var bodyParser = require("body-parser")var pusher = new Pusher({appId: "app_id",key: "app_key",secret: "app_secrete",cluster: "app_cluster"});var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false })); app.post('/location', (req, res,next)=>{ var longitude = req.body.longitude; var latitude = req.body.latitude; var username = req.body.username; pusher.trigger('feed', 'location', {longitude, latitude,username}); res.json({success: 200}); }); app.listen(4040, function () { console.log('Listening on 4040') }) Now navigate to the terminal and cd into the file. Then run the server with: server.js node server.js Run app Once the server is live, go ahead and run the Android app. To run the app, keep your system connected to the internet. Back in Android Studio, click the green play icon on the menu bar to run the application or select from the menu and click from the dropdown. This action will launch your device modal for you to see all connected devices and emulators. If you’re using a physical device, simply select your device from the list of available devices shown and click . Run Run ‘app’ OK If you’re running on an emulator, select your preferred emulator from the list of devices if you have one setup or follow these instructions to set up a new emulator: On the devices modal, select This will launch a hardware selection modal where you will select any device of your choice for instance ( Nexus 5) and click This will launch another modal where you will select the API level you will like to run on the device. Your can choose any of the available options for you or stick with the default and select API level 25. Click again to give your emulator a custom name and then click to complete the setup. Now when you run the app again, you will see your emulator listed on the available devices modal. With your system still connected to the internet, select your preferred device and click to run. Create New Virtual Device. Next. Next Finish Ok Conclusion Hopefully, this tutorial has shown you in an easy way, how to build an activity feed for Android apps with Pusher. As you continue to build stuff, Perhaps you’ll see for yourself that realtime updates are of great importance. When you do, Pusher has all you’ll need to get pushing. Project is available on and the server side code also available . Github on this gist Originally published at Pusher’s blog . , our weekly sponsor, makes communication and collaboration APIs that power apps all over the world, supported by easy to integrate SDKs for web, mobile, as well as most popular backend stacks. Pusher Get started.