Build a location feed app for Android with Kotlin

  • Christian Nwamba
May 17th, 2018
You will need Android Studio 3+ and Node.js installed on your machine. Some knowledge of Android development will be helpful.

Introduction

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 Node.js 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.

Here’s the app in action:

Prerequisites

This tutorial uses the following technologies

To follow along, you’ll need to sign up with Pusher 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 download and install Node if you don’t already have it installed.

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 build.gradle file and update the dependencies like so:

    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.pusher:pusher-java-client:1.5.0'
    implementation 'com.google.android.gms:play-services-maps:15.0.0'
    implementation 'com.google.android.gms:play-services-location:15.0.0'

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

Next, sync the project by clicking Sync Now with the gradle file to install the added dependencies.

Application activities

Login activity

By default creating the Android project also creates a MainActivity class and an associating activity_main.xml file for you. Now we need a login Activity to collect the users username. So create a new activity, right-click on MainActivity >> New >> Activity >> Empty Activity, then name it LoginActivity. Once this activity is created, it’ll create a default layout file activity_login.xml inside the layout folder under res. The layout will be a rather simple one, it will have a text input to collect the user’s username and a button to share their location. Here’s a snippet for the activity_login.xml file:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_margin="16dp"
        tools:context=".LoginActivity">

        <EditText
            android:paddingStart="10dp"
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:hint="Username"
            android:background="@drawable/input_bg"
            android:layout_marginEnd="5dp"/>

        <Button
            android:id="@+id/enterButton"
            android:layout_marginTop="15dp"
            android:layout_width="wrap_content"
            android:padding="10dp"
            android:text="Share Location"
            android:textColor="@android:color/white"
            android:background="@drawable/button"
            android:layout_gravity="center"
            android:layout_height="wrap_content" />

    </LinearLayout>

Here we have a simple LinearLayout with two view objects, an EditText input to collect the user’s username and a share button to send the location to the server.

Android default styling isn’t always appealing so let’s add some custom styles to our layout simply for aesthetic purposes. Under res folder, open the values folder and navigate into colors.xml file and update it with this code :

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="colorPrimary">#8e0517</color>
        <color name="colorPrimaryDark">#4c060f</color>
        <color name="colorAccent">#FF4081</color>

    </resources>

Secondly to achieve the button and Input styles, we create two drawable files. Under res right-click on drawable >>New >> Drawable resource file, name it input_bg and update it with this code:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" android:padding="10dp" >
        <solid android:color="#FFFFFF"
            />
        <corners
            android:radius="10dp"/>
    </shape>

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 button and set it up like so:

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" android:padding="10dp" >
        <solid android:color="#4c060f" />
        <corners
            android:radius="10dp"/>
    </shape>

Finally update your styles.xml file inside the values folder in the layout directory:

    <resources>
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
        </style>
        <style name="AppTheme.NoActionBar">
            <item name="windowActionBar">false</item>
            <item name="windowNoTitle">true</item>
        </style>

     <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
    </resources>

At this point, your output in the xml visualizer should look exactly like this:

Next lets create a new layout file called custom_view.xml. We’ll use this file to render each individual map of a user on our recyclerview object. Inside the layout folder under res, create the new layout resource file and set it up like so:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <com.google.android.gms.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_margin="10dp"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="200dp" />

    </LinearLayout>

Okay, we are done with login and UI lets hook it up with it’s Java file to handle the logic. Open LoginActivity.kt file and set it up like so:

    //package your_project_package_here

    import android.content.Intent
    import android.os.Bundle
    import android.support.v7.app.AppCompatActivity
    import kotlinx.android.synthetic.main.activity_login.*

    class LoginActivity : AppCompatActivity() {

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_login)
            enterButton.setOnClickListener {
                if (userName.text.isNotEmpty()){
                    val intent = Intent(this@LoginActivity,MainActivity::class.java)
                    intent.putExtra("username",userName.text.toString())
                    startActivity(intent)
                }
            }
        }
    }

Here we are simply getting the value of the input we defined in the layout file and passing it into the MainActivity class with an intent . Once the user has entered a value (username) in the Edittext 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

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 LoginActivity 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.

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 res, right-click on layout >> New >> Layout resource file and name it content_main, (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:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"
        android:layout_margin="16dp"
        tools:showIn="@layout/activity_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 activity_main.xml and update it:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.AppBarLayout>

        <include layout="@layout/content_main" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"
            app:srcCompat="@android:drawable/ic_menu_send" />

    </android.support.design.widget.CoordinatorLayout>

Application logic

Since we used a RecyclerView in our layout file, we’ll need an adapter class. RecyclerView works with an Adapter to manage the items of its data source and a ViewHolder to hold a view representing a single list item. Before we create the Adapter class, lets first create a Model 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 MainActivity >> New >> Kotlin File/Class, name it Model, under the Kind dropdown, select Class and set it up like so:

    // java/package/Model

    data class Model(val latitude:Double,
                     val longitude:Double,
                     val username:String)

Now that we have that, lets create the Adapter class. Right-click on MainActivity >> New >> Kotlin File/Class, name it Adapter, under the Kind dropdown, select Class again and set it up with the code:

    // java/package/Adapter
    //package your_project_package_here

    // imports  
    import android.content.Context
    import android.support.v7.widget.RecyclerView
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.TextView

    class Adapter(private val mContext: AppCompatActivity)
        : RecyclerView.Adapter<Adapter.MyViewHolder>() {

        private var arrayList: ArrayList<Model> = ArrayList()
        override fun getItemCount(): Int {
            return arrayList.size
        }
        override fun onBindViewHolder(holder: Adapter.MyViewHolder, position: Int) {
          val latLng = LatLng(arrayList[position].latitude,arrayList[position].longitude)
            holder.mapView.onCreate(null)
            holder.mapView.getMapAsync(OnMapReadyCallback {
                it.addMarker(MarkerOptions()
                        .title(arrayList[position].username)
                        .position(latLng))
            val cameraPosition = CameraPosition.Builder().target(latLng).zoom(17f).build()
                it.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
            })
        }
         override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val view = LayoutInflater.from(mContext).inflate(R.layout.custom_view, parent, false)
            return MyViewHolder(view)
        }

        inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val mapView:MapView = itemView.findViewById(R.id.map)
        }

        fun addItem(model: Model) {
            this.arrayList.add(model)
            notifyDataSetChanged()
        }
    }

Here we have defined an arrayList from our Model class that will be used by the adapter to populate the R``ecycler``V``iew. In the onBindViewHolder() 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.

Then in the onCreateViewHolder() method we define the design of the layout for individual items on the list. Finally the addItem() method adds a new instance of our model class to the arrayList and refresh the list every time we get a new addition.

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 MainActivity >> New >> Kotlin File/Class, under the Kind dropdown, select Interface name it Service and set it up like so:

    // imports ...
    import retrofit2.Call
    import retrofit2.http.GET
    import retrofit2.http.Path

    interface Service {
        @POST("/location")
        fun sendLocation(@Body coordinates: RequestBody): Call<String>
    }

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 network parameters. So follow the previous steps and create a class called Client.kt and set it up like this:

    // imports...

    import okhttp3.OkHttpClient
    import retrofit2.Retrofit
    import retrofit2.converter.gson.GsonConverterFactory
    import retrofit2.converter.scalars.ScalarsConverterFactory

    class Client {
        fun getClient(): Service {
            val httpClient = OkHttpClient.Builder()

            val builder = Retrofit.Builder()
                    .baseUrl("your_server_url")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())

            val retrofit = builder
                    .client(httpClient.build())
                    .build()

            return retrofit.create(Service::class.java)
        }
    }

Replace the Base URL with your localhost address for the Node server. We’ll

The baseUrl 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 MainActivity.kt and initialize the necessary objects and update it with the classes we’ve created above.

    // imports ...

    import android.Manifest
    import android.annotation.SuppressLint
    import android.content.DialogInterface
    import android.content.pm.PackageManager
    import android.location.Location
    import android.os.Bundle
    import android.support.design.widget.Snackbar
    import android.support.v4.app.ActivityCompat
    import android.support.v4.content.ContextCompat
    import android.support.v7.app.AlertDialog
    import android.support.v7.app.AppCompatActivity
    import android.support.v7.widget.LinearLayoutManager
    import android.util.Log
    import com.google.android.gms.location.FusedLocationProviderClient
    import com.google.android.gms.location.LocationServices
    import com.google.android.gms.maps.model.LatLng
    import com.google.android.gms.maps.model.MarkerOptions
    import com.pusher.client.Pusher
    import com.pusher.client.PusherOptions
    import kotlinx.android.synthetic.main.activity_main.*
    import kotlinx.android.synthetic.main.content_main.*
    import okhttp3.MediaType
    import okhttp3.RequestBody
    import org.json.JSONObject
    import retrofit2.Call
    import retrofit2.Callback
    import retrofit2.Response

    class MainActivity : AppCompatActivity() {

        var adapter: Adapter = Adapter(this@MainActivity)
        lateinit var pusher:Pusher
        val MY_PERMISSIONS_REQUEST_LOCATION = 100
        private lateinit var fusedLocationClient: FusedLocationProviderClient

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            setSupportActionBar(toolbar)

            }
    }

Here we’ve just initialized the objects we’ll need, our Adapter class, Pusher, location request and the fusedLocationClient.

In the onCreate() method we’ll setup our RecyclerView with the adapter. We’ll also call the setupPusher() method and the sendLocation() action with the floating action button:

    // java/package/MainActivity.onCreate()
     setupPusher()
    fab.setOnClickListener { view ->
        if (checkLocationPermission())
            sendLocation()
    }
    with(recyclerView){
        layoutManager = LinearLayoutManager(this@MainActivity)
        adapter = this@MainActivity.adapter
    }
    //... continue from next snippet

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 setupPusher() method later on in the tutorial but first off, let’s define and setup the sendLocation() method this time, outside the onCreate():

    //java/package/MainActivity

    //... continue from the last snippet above, outside the onCreate() method
    @SuppressLint("MissingPermission")
    private fun sendLocation() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationClient.lastLocation
                .addOnSuccessListener { location: Location? ->
                    if (location!=null){
                        Log.e("TAG","location is not null")
                        val jsonObject = JSONObject()
                        jsonObject.put("latitude",location.latitude)
                        jsonObject.put("longitude",location.longitude)
                        jsonObject.put("username",intent.extras.getString("username"))

                        val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
                        Log.e("TAG",jsonObject.toString())
                        Client().getClient().sendLocation(body).enqueue(object: Callback<String> {
                            override fun onResponse(call: Call<String>, response: Response<String>) {}

                            override fun onFailure(call: Call<String>?, t: Throwable) {
                                Log.e("TAG",t.message)
                            }

                        })

                    } else {
                        Log.e("TAG","location is null")
                    }
                }

    }
    //MainActivity

With the fusedLocationClient 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 username into our body object. We then use it to build our HTTP request with the jsonObjects as our request parameters.

We also called the checkLocationPermission() method in the onCreate() method however we haven’t defined it yet. Lets now create this method and set it up like so:

    private fun checkLocationPermission(): Boolean {
        if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)) {

                AlertDialog.Builder(this)
                        .setTitle("Location permission")
                        .setMessage("You need the location permission for some things to work")
                        .setPositiveButton("OK", DialogInterface.OnClickListener { dialogInterface, i ->

                            ActivityCompat.requestPermissions(this@MainActivity,
                                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                                    MY_PERMISSIONS_REQUEST_LOCATION)
                        })
                        .create()
                        .show()

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                        MY_PERMISSIONS_REQUEST_LOCATION)
            }
            return false
        } else {
            return true
        }
    }

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 sendLocation() method, add:

    // MainActivity
    override fun onRequestPermissionsResult(requestCode: Int,
     permissions: Array<String>, grantResults: IntArray) {
      when (requestCode) {
            MY_PERMISSIONS_REQUEST_LOCATION -> {
                // If request is cancelled, the result arrays are empty.
       if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
        Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                     sendLocation()
             }
         } else {
               // permission denied!
            }
              return
          }
      }
    }
    //MainActivity

And now let’s define the setUpPusher() method we called earlier in the onCreate() method:

    // MainActivity
    private fun setupPusher() {
        val options = PusherOptions()
        options.setCluster("eu")
        pusher = Pusher("9117088b176802bda36f", options)
        val channel = pusher.subscribe("feed")
        channel.bind("location") { _, _, data ->
            val jsonObject = JSONObject(data)
            Log.d("TAG",jsonObject.toString())
            val lat:Double = jsonObject.getString("latitude").toDouble()
            val lon:Double = jsonObject.getString("longitude").toDouble()
            val name:String = jsonObject.getString("username").toString()
            runOnUiThread {
                val model = Model(lat,lon,name)
                adapter.addItem(model)
            }
        }
    }
    //MainActivity

Here we simply pass in our Pusher configs to the Pusher object and subscribe to the feed channel to listen for location 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.

Next we implement the onStart() and onStop() methods to connect and disconnect Pusher respectively in our app:

    override fun onStart() {
        super.onStart()
        pusher.connect()
    }

    override fun onStop() {
        super.onStop()
        pusher.disconnect()
    }

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 RequestPayload and set it up like so:

    // java/package/RequestPayload

    //package your_project_package_here

    data class RequestPayload(var latitude:Double,var longitude:Double,var username:String)

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 here. 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 along with your project api keys:

Then go to the App Keys tab and copy your app_id, key, and secret credentials, we'll need them later.

Set up a Node server

For this we will use Node. So check that you have node and npm installed on your machine by running this command in command prompt:

    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:

    npm 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 eventChannel, which allows them to relate to a particular topic, an eventName that is used to identify the type of the event, and a *payload*, which you can attach any additional information to and send back to the client.

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 adapter to pass it to the V``iewHolder and lay it out on the screen. When you’re done, your server.js file should look like this:

    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 server.js file. Then run the server with:

    $ node server

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 Run from the menu and click Run ‘app’ 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 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 Create New Virtual Device. This will launch a hardware selection modal where you will select any device of your choice for instance ( Nexus 5) and click Next. 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 Next again to give your emulator a custom name and then click Finish 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 Ok to run.

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 Github and the server side code also available on this gist.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.