Create a GPS tracking application with Firebase Realtime Database

1521720092 create a gps tracking application with firebase realtime database

Firebase Realtime Database GPS app

There are many various ways in which you’ll use location information on your Android apps. Previously, we’ve noticed how you’ll show the consumer’s location on a Google Map; opposite geocode coordinates into a boulevard cope with; and how one can mix location information with the Places API.

All of those examples have something in not unusual: the positioning information most effective ever exists in the community at the consumer’s instrument. In this instructional I’m going to turn you how one can report the instrument’s location to Firebase Realtime Database, so you’ll view this data remotely.

While an app that necessarily acts as a GPS tracker would possibly sound invasive, this capability bureaucracy the root of a number of other packages, together with social apps akin to Find My Friends, and safety-focused packages like Family GPS tracker. The skill to view a instrument’s location remotely could also be crucial for any app that is helping reunite house owners with their misplaced or stolen instrument.

By the top of this instructional, you’ll have created a easy app that screens the instrument’s location after which data this data to a Firebase Realtime Database. Since Firebase Realtime Database receives information in, neatly, realtime, you’ll be capable to view the instrument’s precise coordinates at any time, just by logging into the Firebase Console.

Create a new Firebase challenge

The Firebase Realtime Database is a NoSQL, cloud-hosted database that makes use of information synchronization to routinely obtain new knowledge in realtime from each attached shopper, with out requiring you to setup your individual application server.

Since Realtime Database is a Firebase provider, step one is developing a connection between our challenge and the Firebase Console. I’m additionally going to sign in a consumer account within the Firebase Console, which we’ll in the end use to check our challenge.

  • Head over to the Firebase console and make a selection “Add project.”
  • Give your challenge a call after which click on “Create Project,” adopted by means of “Continue.”
  • Select “Authentication” from the left-hand menu.

Firebase Realtime Database GPS app

  • Select “Set up sign-in method.”
  • Choose “Email/password” after which push the slider into the “On” place. Click “Save.”
  • Select the “Users” tab after which click on “Add User.”
  • Enter the e-mail and password for the take a look at consumer; I’m choosing take a look at@take a look and testpassword.
  • Click “Add User.”

Connect your app to Firebase

Next, you want to attach this challenge for your application, and upload toughen for each Firebase Realtime Database and Firebase Authentication.

  • Create a new Android challenge after which open the Firebase Assistant, by means of settling on Tools > Firebase from the Android Studio toolbar.
  • In the Firebase Assistant, make bigger the “Authentication” segment after which make a selection “Email and password authentication.”

Firebase Realtime Database GPS app

  • Select “Connect to Firebase.”
  • In the following conversation, make a selection “Choose an existing Firebase or Google project.”
  • Select the challenge that you simply created, after which click on “Connect to Firebase.”
  • Click “Add Firebase Authentication to your app.”
  • Check the following popup, and in case you’re satisfied to continue then click on “Accept Changes.”
  • Once the Firebase Assistant is exhibiting the “Dependencies set up correctly” message, go out this a part of the Assistant by means of clicking the little backwards-arrow in its upper-left nook.
  • Expand the “Realtime Database” segment, after which make a selection the “Save and retrieve data” hyperlink.
  • Select “Add the Realtime Database to your app.”
  • Check the adjustments that Android Studio is ready to make for your challenge, after which click on “Accept Changes.”
  • Even despite the fact that Android Studio will have to have added Firebase toughen for your challenge effectively, it’s nonetheless value opening the construct.gradle document and checking that it’s added the newest variations of firebase-auth and firebase-database. Update to a more recent model of those libraries, if to be had.
  • Add play-services-location as a challenge dependency. Your challenge’s “dependencies” segment will have to now glance one thing like this:

Getting get entry to to the positioning

Since our app goes to get entry to the instrument’s location after which ship this data to a far flung database, it wishes the positioning and web permissions, so upload the next to the Manifest:

<?xml model="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
   package deal="com.jessicathornsby.mytrackerapp">

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

Make positive the consumer is aware of they’re being tracked!

Every app that makes use of location information must request both the ACCESS_COARSE_LOCATION or the ACCESS_FINE_LOCATION permission. However, when an app is able to tracking the consumer and sharing this data out of doors of the instrument, merely issuing a permission request isn’t sufficient. Your app will have to supply a visible indication all of the time it’s recording and sharing this probably delicate knowledge, and the consumer should be capable to droop tracking at any time.

I’m going to create a chronic notification that’ll be onscreen all of the time this application is recording the instrument’s location. The consumer can droop tracking by means of tapping this notification — which would be the most effective approach of disregarding the notification.

Let’s create the icon and textual content that we’ll use on this notification. The best possible approach so as to add notification icons for your challenge, is by means of Android Studio’s integrated Asset Studio:

  • Control-click your challenge’s “res/drawable” folder after which make a selection New > Image Asset.
  • Open the “Icon Type” dropdown after which make a selection “Notification Icons.”
  • Click the little button that looks along the “Clip Art” label.
  • Choose the icon you wish to have to make use of; I’m choosing “My Location.” Click “OK.”
  • Name this icon “tracking_enabled,” after which click on “Next.”
  • Check the ideas at the next display, after which click on “Finish.”

Next, open the strings.xml document and create the notification textual content. While the strings.xml document is open, I’m additionally including a firebase_path label that’ll seem along the knowledge in Firebase, plus the e-mail and password for the take a look at consumer we registered within the Firebase Console. While it’s by no means a excellent concept to retailer usernames and passwords as undeniable textual content in manufacturing apps, on this example it’ll make our challenge more straightforward to check.

<string call="tracking_enabled_notif">Tracking is recently enabled. Tap to cancel.</string>
<string call="test_email">take a look at@take a look</string>
<string call="test_password">testpassword</string>
<string call="firebase_path">location</string>

Start tracking the instrument’s location

We’ll carry out lots of the heavy lifting in a separate location tracking provider, however there’s nonetheless a few issues we wish to do in PrimaryActivity:

  • Request get entry to to the instrument’s location. In Android and better, packages wish to request permissions at runtime, and the consumer can revoke previously-granted permissions at any level. PrimaryActivity will wish to take a look at whether or not it recently has get entry to to the consumer’s location, each unmarried time it’s introduced.
  • Start location tracking. The PrimaryActivity will have to take a look at whether or not location tracking is enabled, after which get started the positioning tracking provider if important.
  • Display a toast. Any app that tracks the consumer’s location has the prospective to really feel invasive, so you want to make it very transparent when your app is accumulating this data. In addition to the chronic notification, PrimaryActivity will have to show a toast when location tracking is first enabled.
  • Exit the app. Once PrimaryActivity has began the positioning tracking provider, its paintings is finished. Rather than looking ahead to the consumer to near the application, PrimaryActivity will have to take the initiative and close itself down routinely.
import android.os.Bundle;
import android.toughen.v4.content material.ContextCompat;
import android.content material.Intent;
import android.location.LocationSupervisor;
import android.Manifest;
import android.content;
import android.widget.Toast;

public magnificence PrimaryActivity extends Activity 

Create a location-tracking provider

We now wish to create the provider that’s chargeable for sending the instrument’s location to Firebase. I’m additionally going to create the chronic notification that’ll supply that all-important visible reminder that the consumer is recently being tracked.

Create a new provider, by means of settling on File > New > Service > Service from the Android Studio toolbar. Name the provider “TrackingService,” after which upload the next:

import result;


import android.content material.BroadcastReceiver;
import android.content material.Context;
import android.toughen.v4.content material.ContextCompat;
import android.os.IBinder;
import android.content material.Intent;
import android.content material.IntentClear out;
import android.util.Log;
import android.Manifest;
import android.location.Location;
import android.content;

public magnificence TrackingService extends Service {

   personal static ultimate String TAG = TrackingService.magnificence.getSimpleName();

   public IBinder onBind(Intent intent) 

   public void onCreate() 

//Create the chronic notification//

   personal void constructNotification() 

   safe BroadcastReceiver stopReceiver = new BroadcastReceiver() ;

   personal void loginToFirebase() {

//Authenticate with Firebase, the use of the e-mail and password we created previous//

       String electronic mail = getString(R.string.test_email);
       String password = getString(R.string.test_password);

//Call OnCompleteListener if the consumer is signed in effectively//

               electronic mail, password).uploadOnCompleteListener(new OnCompleteListener<AuthResult>() );

//Initiate the request to trace the instrument's location//

   personal void requestLocationUpdates() {
       LocationRequest request = new LocationRequest();

//Specify how steadily your app will have to request the instrument’s location//


//Get essentially the most correct location information to be had//

       FusedLocationProviderClient shopper = LocationServices.getFusedLocationProviderClient(this);
       ultimate String trail = getString(R.string.firebase_path);
       int permission = ContextCompat.checkSelfPermission(this,

//If the app recently has get entry to to the positioning permission...//

     if (permission == PackageManager.PERMISSION_GRANTED) {

//...then request location updates//

           shopper.requestLocationUpdates(request, new LocationCallagain() , null);

You can in finding all of the code for the GPS tracker on GitHub.

Testing the application

When trying out any application that makes use of location information, it may well lend a hand to spoof your location.

With our tracking app, simply strolling round your own home or administrative center received’t dramatically modify the longitude and latitude coordinates, which may make it tricky to identify whether or not the ideas in Firebase actually is converting. By spoofing your location, you’ll ship dramatically other coordinates to Firebase, so that you don’t need to scour lengthy strings of numbers, on the lookout for a unmarried digit that may have modified.

If you’re trying out your app on a bodily Android smartphone or pill, then one of the best ways to spoof your location is by means of putting in a 3rd birthday party app, akin to Fake GPS Location.

If you’re the use of Android Virtual Device (AVD) then you have already got the whole lot you want to faux a location:

  • Select “More” from the strip of buttons that looks along the emulator window (the place the cursor is situated within the following screenshot).

Firebase Realtime Database GPS app

  • Select “Location” from the left-hand menu.
  • Enter your new coordinates into the “Longitude” and “Latitude” fields, after which click on “Send.” The emulator will now use those new coordinates.

To take a look at that your app is recording the instrument’s location to Firebase:

  • Install the challenge to your Android instrument.
  • When brought on, grant the app get entry to for your location. You will have to see a toast, informing you that GPS tracking is now enabled.
  • Open the notification drawer, and take a look at that the chronic notification has been created.
  • In your internet browser, head over to the Firebase Console and open the challenge that’s related for your tracking app.
  • In the left-hand menu, make a selection “Database.”
  • Select the “Data” tab, and also you will have to see that location information is now showing within the Firebase Console.

Reading the Firebase Realtime information

Firebase gifts its information as JSON gadgets, that are units of attribute-value pairs. These pairs may also be numbers, strings, true/false Booleans, arrays of 0 or extra values, collections of name-value pairs, and nulls, so the entire following are legitimate JSON information sorts:

accuracy : 1.6430000066757202
entire: true
bearing: zero
supplier: “fused”

The JSON tree incorporates a number of information, however one of the best ways to test that Firebase is recording information accurately, is to duplicate/paste the longitude and longitude values into Google Maps. If this information is right kind, then it will have to go back your present location, or the positioning you’re recently spoofing.

We’re sending location information to Firebase the use of the setValue() manner, which replaces the former information access. This signifies that Firebase Realtime Database will most effective ever comprise the consumer’s remaining recognized location. You will also see new information changing the previous information, when you have the Firebase database open on your internet browser whilst spoofing other places to your Android instrument.

When operating with Firebase on your personal tasks, you might occasionally wish to report greater than a unmarried piece of knowledge. You can upload information to Firebase with out changing the former values, by means of the use of any of the next strategies as an alternative of setValue():

  • setRawJsonValueAsync(). Replaces information with uncooked JSON.
  • push(). Adds a new kid to a checklist of knowledge. Each time you name push(), Firebase generates a distinctive key according to a timestamp, so even supposing more than one purchasers upload youngsters to the similar location on the identical time, it received’t motive a write warfare.
  • updateChildAsync(). Writes information to the desired location, with out writing over different kid nodes. By specifying other paths, you’ll carry out simultaneous updates in more than one spaces of the JSON tree, with a unmarried name to UpdateChildrenAsync().
  • runTransaction(). You will have to use this system if you want to replace complicated information that would turn out to be corrupted by means of concurrent updates.

If you do retailer more than one units of kid information inside your JSON tree, then you definitely will have to sparsely construction your database to verify it doesn’t get too complicated.

In addition, when the use of the Firebase Realtime Database on your personal tasks, you might wish to setup some Database Security Rules, which outline how your information will have to be structured, listed, and when your information may also be learn and written to. You too can use regulations to specify who has get entry to for your Firebase database, despite the fact that Firebase already restricts get entry to to authenticated customers by means of default.

You can view your Database Security Rules, by means of settling on the “Rules” tab within the Firebase Console.

Firebase Realtime Database GPS app

Wrapping up

In this text, we checked out how one can report the consumer’s location to a far flung database. Once this data is to be had in Firebase, you’ll use it in a number of other ways, as an example, you should lend a hand the consumer find their friends and family; report their day-to-day run to Google Maps, and even ship them distinctive content material according to their converting location.

Have you noticed any apps that use GPS tracking in a distinctive approach? Or do you have got any concepts about how you could use this option on your long run tasks? Let us know within the feedback!

Leave a Reply

Your email address will not be published. Required fields are marked *