Tech & Giveaways

Create a GPS tracking application with Firebase Realtime Database

There are lots of other ways in which you’ll use location knowledge on your Android apps. In the past, we’ve noticed how you’ll show the person’s location on a Google Map; opposite geocode coordinates into a side road cope with; and tips on how to mix location knowledge with the Puts API.

All of those examples have something in commonplace: the site knowledge most effective ever exists in the community at the person’s instrument. On this instructional I’m going to turn you tips on how to document the instrument’s location to Firebase Realtime Database, so you’ll view this knowledge remotely.

Whilst an app that necessarily acts as a GPS tracker would possibly sound invasive, this capability bureaucracy the root of quite a lot of other packages, together with social apps similar to To find My Pals, and safety-focused packages like Circle of relatives GPS tracker. The power to view a instrument’s location remotely could also be very important for any app that is helping reunite house owners with their misplaced or stolen instrument.

Through the top of this instructional, you’ll have created a easy app that screens the instrument’s location after which data this knowledge to a Firebase Realtime Database. Since Firebase Realtime Database receives knowledge in, smartly, 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 mission

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

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

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

Firebase Realtime Database GPS app

  • Choose “Set up sign-in method.”
  • Select “Email/password” after which push the slider into the “On” place. Click on “Save.”
  • Choose the “Users” tab after which click on “Add User.”
  • Input the e-mail and password for the test person; I’m choosing [email protected] and testpassword.
  • Click on “Add User.”

Attach your app to Firebase

Subsequent, you wish to have to attach this mission for your application, and upload fortify for each Firebase Realtime Database and Firebase Authentication.

  • Create a new Android mission after which open the Firebase Assistant, via deciding on Equipment > Firebase from the Android Studio toolbar.
  • Within the Firebase Assistant, amplify the “Authentication” segment after which make a selection “Email and password authentication.”

Firebase Realtime Database GPS app

  • Choose “Connect to Firebase.”
  • Within the next conversation, make a selection “Choose an existing Firebase or Google project.”
  • Choose the mission that you simply created, after which click on “Connect to Firebase.”
  • Click on “Add Firebase Authentication to your app.”
  • Test the following popup, and if you happen to’re satisfied to continue then click on “Accept Changes.”
  • As soon as the Firebase Assistant is showing the “Dependencies set up correctly” message, go out this a part of the Assistant via clicking the little backwards-arrow in its upper-left nook.
  • Extend the “Realtime Database” segment, after which make a selection the “Save and retrieve data” hyperlink.
  • Choose “Add the Realtime Database to your app.”
  • Test the adjustments that Android Studio is ready to make for your mission, after which click on “Accept Changes.”
  • Even supposing Android Studio must have added Firebase fortify for your mission effectively, it’s nonetheless price opening the construct.gradle record and checking that it’s added the newest variations of firebase-auth and firebase-database. Replace to a more moderen model of those libraries, if to be had.
  • Upload play-services-location as a mission dependency. Your mission’s “dependencies” segment must now glance one thing like this:
dependencies 

Gaining access to the site

Since our app goes to get admission to the instrument’s location after which ship this knowledge to a faraway database, it wishes the site and web permissions, so upload the next to the Manifest:



   
   

Be certain that the person is aware of they’re being tracked!

Each app that makes use of location knowledge must request both the ACCESS_COARSE_LOCATION or the ACCESS_FINE_LOCATION permission. Alternatively, when an app is in a position to tracking the person and sharing this knowledge out of doors of the instrument, merely issuing a permission request isn’t sufficient. Your app must supply a visible indication all the time it’s recording and sharing this doubtlessly delicate data, and the person should be capable to droop tracking at any time.

I’m going to create a power notification that’ll be onscreen all the time this application is recording the instrument’s location. The person can droop tracking via tapping this notification — which would be the most effective method of brushing aside the notification.

Let’s create the icon and textual content that we’ll use on this notification. One of the best ways so as to add notification icons for your mission, is by way of Android Studio’s integrated Asset Studio:

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

Subsequent, open the strings.xml record and create the notification textual content. Whilst the strings.xml record 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 test person we registered within the Firebase Console. Whilst it’s by no means a excellent thought to retailer usernames and passwords as simple textual content in manufacturing apps, on this example it’ll make our mission more straightforward to test.

Tracking is these days enabled. Faucet to cancel.
[email protected]
testpassword
location

Get started tracking the instrument’s location

We’ll carry out many of the heavy lifting in a separate location tracking carrier, however there’s nonetheless a few issues we want to do in MainActivity:

  • Request get admission to to the instrument’s location. In Android 6.zero and better, packages want to request permissions at runtime, and the person can revoke previously-granted permissions at any level. MainActivity will want to take a look at whether or not it these days has get admission to to the person’s location, each unmarried time it’s introduced.
  • Get started location tracking. The MainActivity must take a look at whether or not location tracking is enabled, after which get started the site tracking carrier if essential.
  • Show a toast. Any app that tracks the person’s location has the possible to really feel invasive, so you wish to have to make it very transparent when your app is collecting this knowledge. Along with the power notification, MainActivity must show a toast when location tracking is first enabled.
  • Go out the app. As soon as MainActivity has began the site tracking carrier, its paintings is completed. Moderately than looking forward to the person to near the application, MainActivity must take the initiative and close itself down mechanically.
import android.app.Task;
import android.fortify.v4.app.ActivityCompat;
import android.os.Package deal;
import android.fortify.v4.content material.ContextCompat;
import android.content material.Intent;
import android.location.LocationManager;
import android.Manifest;
import android.content material.pm.PackageManager;
import android.widget.Toast;

public elegance MainActivity extends Task 

Create a location-tracking carrier

We now want to create the carrier that’s liable for sending the instrument’s location to Firebase. I’m additionally going to create the power notification that’ll supply that all-important visible reminder that the person is these days being tracked.

Create a new carrier, via deciding on Document > New > Provider > Provider from the Android Studio toolbar. Title the carrier “TrackingService,” after which upload the next:

import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.duties.OnCompleteListener;
import com.google.android.gms.duties.Activity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import android.content material.BroadcastReceiver;
import android.content material.Context;
import android.fortify.v4.content material.ContextCompat;
import android.os.IBinder;
import android.content material.Intent;
import android.content material.IntentFilter;
import android.util.Log;
import android.Manifest;
import android.location.Location;
import android.app.Notification;
import android.content material.pm.PackageManager;
import android.app.PendingIntent;
import android.app.Provider;

public elegance TrackingService extends Provider {

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

   @Override
   public IBinder onBind(Intent intent) 

   @Override
   public void onCreate() 

//Create the power notification//

   personal void buildNotification() 

   secure 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);

//Name OnCompleteListener if the person is signed in effectively//

       FirebaseAuth.getInstance().signInWithEmailAndPassword(
               electronic mail, password).addOnCompleteListener(new OnCompleteListener() );
   }

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

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

//Specify how frequently your app must request the instrument’s location//

     request.setInterval(10000);

//Get probably the most correct location knowledge to be had//

       request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
       FusedLocationProviderClient consumer = LocationServices.getFusedLocationProviderClient(this);
       ultimate String trail = getString(R.string.firebase_path);
       int permission = ContextCompat.checkSelfPermission(this,
               Manifest.permission.ACCESS_FINE_LOCATION);

//If the app these days has get admission to to the site permission...//

     if (permission == PackageManager.PERMISSION_GRANTED) {

//...then request location updates//

           consumer.requestLocationUpdates(request, new LocationCallback() , null);
        }
   }
}

You’ll be able to to find all the code for the GPS tracker on GitHub.

Checking out the application

When checking out any application that makes use of location knowledge, it might assist to spoof your location.

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

In the event you’re checking out your app on a bodily Android smartphone or pill, then one of the best ways to spoof your location is via putting in a 3rd birthday party app, similar to Pretend GPS Location.

In the event you’re the use of Android Digital Software (AVD) then you have already got the whole lot you wish to have to faux a location:

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

Firebase Realtime Database GPS app

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

To test that your app is recording the instrument’s location to Firebase:

  • Set up the mission for your Android instrument.
  • When caused, grant the app get admission to for your location. You must see a toast, informing you that GPS tracking is now enabled.
  • Open the notification drawer, and take a look at that the power notification has been created.
  • For your internet browser, head over to the Firebase Console and open the mission that’s connected for your tracking app.
  • Within the left-hand menu, make a selection “Database.”
  • Choose the “Data” tab, and also you must see that location knowledge is now showing within the Firebase Console.

Studying the Firebase Realtime knowledge

Firebase items its knowledge as JSON items, that are units of attribute-value pairs. Those pairs will 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 knowledge varieties:

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

The JSON tree incorporates quite a lot of knowledge, however one of the best ways to test that Firebase is recording knowledge accurately, is to duplicate/paste the longitude and longitude values into Google Maps. If this information is right kind, then it must go back your present location, or the site you’re these days spoofing.

We’re sending location knowledge to Firebase the use of the setValue() method, which replaces the former knowledge access. Which means that Firebase Realtime Database will most effective ever include the person’s remaining identified location. You’ll be able to even see new knowledge changing the outdated knowledge, if in case you have the Firebase database open on your internet browser whilst spoofing other places for your Android instrument.

When operating with Firebase on your personal initiatives, you might every now and then wish to document greater than a unmarried piece of knowledge. You’ll be able to upload knowledge to Firebase with out changing the former values, via the use of any of the next strategies as a substitute of setValue():

  • setRawJsonValueAsync(). Replaces knowledge with uncooked JSON.
  • push(). Provides a new kid to a checklist of knowledge. Every time you name push(), Firebase generates a distinctive key in line with a timestamp, so although more than one purchasers upload youngsters to the similar location on the identical time, it received’t purpose a write warfare.
  • updateChildAsync(). Writes knowledge to the required location, with out writing over different kid nodes. Through 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 should utilize this method if you wish to have to replace advanced knowledge that might grow to be corrupted via concurrent updates.

In the event you do retailer more than one units of kid knowledge inside of your JSON tree, then you definitely must moderately construction your database to verify it doesn’t get too advanced.

As well as, when the use of the Firebase Realtime Database on your personal initiatives, you might wish to setup some Database Safety Laws, which outline how your knowledge must be structured, listed, and when your knowledge will also be learn and written to. You’ll be able to additionally use laws to specify who has get admission to for your Firebase database, despite the fact that Firebase already restricts get admission to to authenticated customers via default.

You’ll be able to view your Database Safety Laws, via deciding on the “Rules” tab within the Firebase Console.

Firebase Realtime Database GPS app

Wrapping up

On this article, we checked out tips on how to document the person’s location to a faraway database. As soon as this knowledge is to be had in Firebase, you’ll use it in quite a lot of other ways, as an example, it’s essential to assist the person find their friends and family; document their day by day run to Google Maps, and even ship them distinctive content material in line with their converting location.

Have you ever noticed any apps that use GPS tracking in a distinctive method? Or do you’ve gotten any concepts about how it’s possible you’ll use this selection on your long run initiatives? Tell us within the feedback!

error: Content is protected !!
%d bloggers like this: