Getting GPS location using FusedLocationProvider and LiveData easily in background (Kotlin, Android)

Getting GPS location is one of the most important and necessary aspects of developing apps in Android.

For a brief overview, we will be trying to get GPS location in such a way that we do not need to write the boilerplate code every time we try to access the location. Also, we will be using Singleton pattern to save the instance of FusedLocationProvider to avoid it being instantiated every time we try and fetch location.

LiveData will help us observe the location every time an update is received. Also it fully coordinates with the lifecycle of its parent (Activity, Fragments).

Step 1

Add permissions in the manifest.

Step 2

Create your LocationUtils class and add an instance variable of FusedLocationProviderClient.

Step 3

Using Singleton pattern, get the instance of the above FusedLocationProviderClient variable.

Now we have created the instance of FusedLocationProvider. Only one such instance will exist.

Step 4

Add another instance variable of type MutableLiveData<Location>.

Create a function that returns the above location variable.

Full Code:

Step 5

Get the location in an Activity or Fragment in the following manner:

Therefore, we get our location easliy.

Note: This is my first post on Medium. Forgive me if any errors might have crept in. Feel free to give any feedback .

Thank You for reading.