Category Archives: Google Map Gps Cell Phone Tracker

How the Android Gps Tracker Client Works

I finally had the time to rewrite the android client and to get the background service working as I’ve wanted to for a long time. Gps Tracker is now based on work I had done previously on my other website, mycelltracker.com. The big difference between the old mycelltracker app and the new Gps Tracker is the introduction of Google Play location services.

With that I want to go into an in-depth discussion of how Gps Tracker now works on Android devices. We’ll start by looking at the structure of the application beginning with the five classes used in the app. I’ll first give a brief description of each. Here are the class files on github if you want to follow along:

GpsTracker android client class files on github

GpsTrackerActivity – This is the one and only screen of the application. It displays two text fields. One for the user name and one for the upload website. There are a set of radio buttons that allow the user to set the interval (from one minute, 5, 15, 30, 60). And there is a start tracking button.

Android Gps Tracker

GpsTrackerAlarmReceiver – This class has an onReceive method that is called periodically from a repeating AlarmManager. When the method is called, the background service is started.

GpsTrackerBootReceiver – This class also has an onReceive method that is called but this one is called when the phone is rebooted. When the method is called, it creates a new AlarmManager. The AlarmManager starts the background service periodically using the receiver class above.

LocationService – This background service is called periodically from the AlarmManager above. When it starts, it uses google play location services to get the location of the device and send it to the update website using an open source asynchronous http client library. The service then terminates itself.

LoopjHttpClient – This class wraps a third party library that does asynchronous http calls.

The first thing that happens is that the main activity starts up and in onCreate, a sharedPreference file is opened and the currentlyTracking variable is set:

This is an important variable and will be used throughout the application. When onResume is called, two other methods are called. The first is displayUserSettings which just restores the UI to its previous state and the second is setTrackingButtonState which displays the correct button state (either tracking or not tracking). When a user taps on the start tracking button, the currentlyTracking variable is set to true and the method startAlarmManager is called:

In this method, a repeating AlarmManager is created and the interval is set to the variable intervalInMinutes. intervalInMinutes is chosen by the user using the radio buttons on the screen. The interval is set to 1 minute, 5, 15, 30 or 60. The AlarmManager class is an interface to the phone’s system alarm services and allows us to run code at a specific time even if the GpsTracker app is not running. In this method, we create a pending intent which allows AlarmManager to run our code using our application’s permissions. So what happens here is that every one minute, for instance, the alarmManager will execute the onReceive method of the GpsTrackerAlarmReceiver class.

Let’s take a look at the GpsTrackerAlarmReceiver class. First of all you’ll see that it extends the WakefulBroadcastReceiver class. This is very important. This is a helper class that creates a partial wake lock. Creating this wake lock insures that the cpu doesn’t go back to sleep while the background service is running. You need to set this permission in the AndroidManifest file:

As you can see the GpsTrackerAlarmReceiver class is very simple, with only one method.

When the alarmManager calls the onReceive method it starts the LocationService background service. If it’s already started, like if you have the interval set to one minute, then it only calls the onStartCommand method in the LocationService class. As long as the phone is running, the alarmManager will continue to start this service over and over again, get the phone’s location and then send the location to your update website.

What happens if somebody turns the phone off and then back on again, will we still get location updates? Well, glad you asked and the answer is yes, so let me show you how it’s done. There is another class called GpsTrackerBootReceiver which extends BroadcastReceiver. This time we will not use the wakeful receiver because all we are doing is creating a repeating alarmManager. This is a very fast operation and since we are not starting a service as in the previous class, we do not need to create an additional wake lock.

Note also that we are checking the variable currentlyTracking:

if we are currently tracking (as set by the user in the gpsTrackerActivity screen when they tap on the start tracking button), then start the alarmManager, otherwise cancel it.

This broadcast receiver’s onResume method is called every time the phone is rebooted. We’ll need to look at the AndroidManifest.xml file for a moment to see how that happens.

Here you can see we have registered a receiver with the name of our class, .GpsTrackerBootReceiver (don’t forget the period before the class name), and this receiver has a filter that says only listen to BOOT_COMPLETED events. So every time the phone is rebooted, call my onReceive method.

While we are looking in the AndroidManifest, note that GpsTrackerAlarmReceiver is also registered and the LocationService as well:

This brings us to the next class in the application, the LocationService. This class extends Service and runs on the main thread of the application. It runs in the background and will continue running even if the application shuts down. Since it runs on the main thread, any long running operations should be on their own threads or else the user could experience having the app’s UI freeze up (something you want to avoid…). This service does two things:

a) gets the phone’s location using Google play location services
b) sends the location data to the upload website

The first operation uses the requestLocationUpdates method of the LocationClient class to start getting location data from the phone. When the phone has a location that meets the criteria that we specify then it returns that location back to a callback method. That method’s name is onLocationChanged. This all happens asynchronously so we never have to worry about freezing up the UI with this operation.

The second operation uses this cool open source library:

Android Asynchronous Http Client

written by James Smith. As you can see from the name of the library, this allows us to make http calls asynchronously so once again, we don’t have to worry about tying up the UI. Also, this library handles being called from a background service. One less thing we have to worry about.

So when the service starts, it calls onCreate (like an activity) and then calls onStartCommand. If the service is already running and something else tries to start the service, a new service is not created, what happens is onStartCommand is called again. This is where I call the startTracking method from:

I first check the variable currentlyProcessingLocation. If the service has already been started (which might happen when we have an interval of one minute) then we don’t want to call startTracking twice. Sometimes it can take more than a minute to get that first satellite fix if we are using gps. So, the moment we start tracking, we set that variable to true and that solves the problem. START_STICKY means that if the service is somehow killed, then the system will restart the service and the service can continue doing what it’s supposed to do.

The next thing we do is create our locationClient. Once the client is connected we can then create a LocationRequest object in the onConnected callback method. Let’s take a look at the properties we are setting on the locationRequest object:

We set our interval to 1 second and our priority to PRIORITY_HIGH_ACCURACY. This means get the highest accuracy possible as quickly as possible. So the phone will be trying to get it’s location from the google play’s fused location provider. Fused means that the location can be coming from either gps, wifi, cell towers or other means. In the new google play location services, you no longer worry about which provider to use, you simply tell it what accuracy you want and it will figure it out on it’s own. I tell you this is a welcome relief from how things have been in the past. Stackoverflow has countless questions about which provider to use (gps vs. wifi vs. cell tower etc…) and it has always been a serious point of confusion for lots of developers, so good riddance.

You’ll notice that I’m using requestLocationUpdates instead of something like getLastLocation. I wanted the ability to filter my location by accuracy. That’s why I have the if block here in the onLocationChanged method:

to only accept a location that has an accuracy of 100 meters or better. This can be adjusted to fit your own needs. onLocationChanged is going to be called about once a second (since we’re using requestLocationUpdates), so once we have a location that meets our criteria, let’s send that location to the update website and shut down the service.

In the sendLocationDataToWebsite method, we create a RequestParams object, which is part of the loopj async http library and set all of our parameters for our POST http operation. We do our async post and on either success or failure, we shut down the service with this line:

One thing you’ll notice within the sendLocationDataToWebsite method is a little if/else block that checks if firstTimeGettingPosition is true. If it is true, then we need to save our latitude and longitude to shared preferences only. If it’s not true, then we need to create a new location object with our previously saved latitude and longitude. Once we have this, we can use the distanceTo method of the Location class to figure out how far we have moved since the last location update. This allows us to calculate our total distance traveled.

When the alarmManager reaches its interval again, the background service is recreated and the whole process starts again. This process works well on larger intervals such as five minutes, on shorter intervals like one minute, there is a chance that it could take google play location services a longer time to get a location fix that meets our criteria. What I’m getting at is that for shorter intervals, it might be less of an energy drain to keep the background service running continuously and keep google play location services running continuously. It may be less of a battery drain. The two scenarios need to be tested.

As the application stands now, I think it’s a good starting point for any further work. It works reliably and periodically in the background and restarts when the phone reboots. This would be a good starter app for other apps. If you want to see this app in action, you can download it from google play:

https://play.google.com/store/apps/details?id=com.websmithing.gpstracker

and then start tracking. Then go to the test webpage and search for your username in the routes dropdown box below the map. It should be near the top of the list:

https://www.websmithing.com/gpstracker/displaymap.php

The full source code can be found in my repo on github in the phoneClients android directory.

How to set up the Gps Tracker MySql database using phpMyAdmin

This problem has plagued a lot of people. I even made a video in 2008 explaining how to use phpMyAdmin. I just watched it again and it’s still relevant 6 years later. Check out the video on my youtube channel, it’s only four minutes and will help:

Google Map GPS Cell Phone Tracker and PhpMyAdmin

The following are the written instructions for those who prefer it. The first thing you need to do is create a new database. When you have the name of the database, make sure and change it in the php connection file:

https://github.com/nickfox/GpsTracker/blob/master/servers/php/dbconnect.php

You need to make sure all those values are correct.

Next take a look at the sql script in the github repo, you’ll first want to cut and paste the CREATE TABLE command into the SQL tab of phpMyAdmin. After you’ve created the table, you’ll want to add all the stored procedures. When you look in the sql script, you’ll see something like this for the procedure prcGetRouteForMap:

This is generated automatically by mySql but should not be used if you are creating the procedure by hand. This is how the procedure should be run:

Note that the DEFINER is now gone. Now look in the lower left hand corner of the SQL tab of phpMyAdmin. Do you see the delimiter box? Remove the semi-colon ; if there is one and add two forward slashes // to the box. Do this for each of the stored procedures (total of 6) and you’re almost done. Finally do the INSERT INTO command and insert the location data into the db. Now are you done setting up the database. The next step is to test your installation by going to the following page:

http://www.yoursite.com/gpstracker/displaymap.php

on your website. You should see the red message at top saying “Choose a route below” and with that you should be good to go. Just point one of the phone clients to your updatelocation.php file and start receiving updates.

Android Version of Gps Tracker Now in Google Play Store!

Finally something that has been requested for some time, the android version of GpsTracker is in the Google Play Store:

Gps Tracker on Google Play

https://play.google.com/store/apps/details?id=com.websmithing.gpstracker

This version has many significant enhancements. The most important is that it now has google play location services running in a background service. Also, location updates will restart automatically if the phone is restarted. Please download and test the app and let me know how it works! If you want to have a look at the source code, you can find it here:

https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android

Recent outages on websmithing

Hey everyone, I want to apologize about the recent outages on websmithing.com. I was installing an ssl certificate so that I could serve https and installing it was a bit of a challenge.

Developers please note that this website is now using https and all test urls need to be changed on the phone or they won’t work.

https://www.websmithing.com/gpstracker/updatelocation.php

Search for this string in the phone source code.

Nick

Help! I lost my cell phone.

First off, I’m sorry that you lost your cell phone. That is a bummer. At this point, I’m sure you have retraced your steps and have tried calling your cell phone to see if someone kind hears it and picks it up. You can call your cell phone from your computer using Google voice if you do not have access to another phone:

https://www.google.com/voice

If it’s a real emergency (ie. a missing person), then you should contact the police and they in turn might be able to contact the phone company and find the phone’s location.

At this point, if you are still unable to find your cell phone I will cut to the chase and let you know where you stand.

If you did not have any tracking software installed and activated on your phone before you lost it, you most likely are not going to find it.

Sorry for the bad news but that’s the way it is and I really don’t want you going to another website that promises to find your phone for a fee or is simply trying to get at your personal information.

One more thing to mention, it’s important to contact your cell phone provider and let them know your phone is missing. Ask them to put a hold on your account so that you don’t incur any charges that may be made on the phone.

Also, if you have thoughts of chasing somebody who has stolen your cell phone, please be careful. In today’s world, you just don’t know if someone is going to pull out a weapon and use it against you. I’m just suggesting that you might not want to provoke someone into doing so. Your life and safety is much more valuable than a cell phone.

Now if you haven’t lost your phone yet but want to protect it then please keep reading…

If you have an iPhone or any kind of newer Apple mobile device then Apple has you covered with this, Find My iPhone:

http://www.apple.com/icloud/find-my-iphone.html

Make sure you set that up on all of your apple devices.

If you have an Android cell phone, I recommend installing this, Where’s My Droid:

https://play.google.com/store/apps/details?id=com.alienmanfc6.wheresmyandroid

This is by far the most widely used application for finding lost Android phones. The basic version is free and it works just fine. Google has come out with something new called Android Device Manager. It’s very similar to Apple’s Find my iPhone but it’s not yet out on all android cell phones (January, 2014). To see if it’s on yours check out this support page from Google and use the Android Device Manager if your phone has it:

https://support.google.com/accounts/answer/3265955?hl=en

If you have a Windows Phone, Microsoft has created this site to help you find your cell phone:

http://www.windowsphone.com/en-us/how-to/wp7/basics/find-a-lost-phone

Finally, if you have an old java phone (think old Razr flip phones), the only application that I could find to track those old phones is put out by Mcaffee. Unlike the other three applications I mentioned above, this product costs money. I have not used it and only present it here as a solution if you have an older java phone.

https://www.wavesecure.com/products/java.aspx

That covers just about any cell phone that is out there right now.

And finally, always use a passcode to get into your phone. Don’t worry, you’ll get used to it. Besides protecting a huge amount of your personal information, it will make it a lot harder for someone to get into your phone settings and turn off tracking. That may give you just enough time to locate your phone with one of the online trackers you have set up.

If you have any questions at all that weren’t covered in this post, please feel free to ask and good luck in finding your phone.

Quick Start Guide for Gps Tracker

Servers

Cell phone clients

There are 2 parts to the gps tracker application. The server and the clients. The server part needs to be installed on a public web server. It can be installed on a local machine and clients can be tested over wifi so strictly speaking, you do not need a public facing web server but for our purposes, we will assume you have one. There are 2 different server stacks:

  • one for asp.net and sql server
  • one for php and mysql

You do not need to install both. How do you choose which one to use? It’s personal preference, but if you work primarily on windows machines, it makes sense to install the asp.net version.

Asp.Net and Sql Server

The asp.net version requires you to install IIS (Internet Information Services 7 or greater) onto your machine and when you do install it, do not forget to install asp.net, you have to click a separate checkbox. Forgetting to install asp.net will result in a very interesting and hard to solve error… In IIS manager, right click on “Default Web Site” and create a new application named gpstracker and put all the files from the dotNet server directory that you downloaded and put it into that application. The application will probably be mapped to the physical directory C:\inetpub\wwwroot\gpstracker. Add files there.

You need to also install sql server. I used sql server express 2012 which is a free download. Once sql server in installed you need to do a restore. The file is in the servers > dotNet > sqlserver directory and is called gpstracker.bak. In the sql server management console, expand the System Databases and right click on one of the databases and go to Tasks > Restore > Database and restore GpsTracker bak file. Once that is done, your database is ready to go. Make sure to set a user name and password on that DB. I beleive that username “gpstracker” and password “gpstracker” are in that DB currently. Don’t forget to change that if you use the DB in production…

Download Visual Studio Express 2012 for Web and on the File menu, click “Open Web Site” and then choose local IIS on the left and then gpstracker on the right. I had to open visual studio as administrator for it to work right with IIS permissions. Now you can see all the website files. DisplayMap.aspx is the one that you want to view. Use visual studio to establish the connection with sql server (under Tools > Connect To Database). You can set DisplayMap.aspx as the start page and then run the application on the menu. That should get you going on the asp.net server.

PHP and MySql

For this, you need a LAMP stack or one of its derivatives (MAMP, WAMP etc). LAMP stands for linux, apache, mysql and php. You can download packages that will install all at once, just google lamp, mamp and wamp. They are all similar but just different based on the platform you have, windows, mac or linux. Once you have your server software installed, you need to create a website on your apache webserver and create a directory called gpstracker. Put all of the files from the php download directory into there.

From the command line, you need to do the following (windows users may need to install cygwin, which will give them a unix-like terminal prompt). Login in to MySql with this command:

Change root_password to your root password and note that there is no space between the -p and your password.

and now from the mysql prompt, create the gps tracker database with this command:

and don’t forget the semi-colon ; at the end, all MySql commands must end in semi-colons. Now exit MySql with the following command:

Now lets get our data and stored procedures into the database using the following command:

Please note that the date on the sql file (03-14-14) may be more current. Use the most current from the github repo.

Now log back into MySql with the above command and switch to the gpstracker DB with this command:

and then have a look at your location records with this:

Finally, create a user called gpstracker_user for the web application:

the final ‘gpstracker’ in parentheses is the password for gpstracker_user. You need to change that to your own password and then you need to change it also in dbconnect.php here:

While you are in dbconnect.php, make sure that the database name is the same as the one you just created. If you are using phpMySql, the database name will probably be different.

and finally exit out of mysql with this:

Ok, at this point displaymap.php should work in your browser and you should be able to see the one location stored in the database.

At this point in time, you should have one of the two servers above installed. Now its time to look at the clients. There are currently 4 clients. One for android, ios, windows phone and java me/j2me. You only need one client but all four clients work with either server, this is a very flexible system. We’ll start with android since that is the one that people seem to be testing the most.

Android Cell Phones

You can get the android client in one of two ways now. If you do not need to customize the app, you can download it directly from google play and easily change the upload directory to point to your Gps Tracker website. It’s available here:

Gps Tracker in the Google Play Store

If you need to modify and compile the android client, that requires Android Studio.

http://developer.android.com/sdk/installing/studio.html

I urge android developers to start using Android Studio (AS) if you haven’t started already. Google has done an excellent job with AS, the gradle build system is excellent. After you install AS, open up the application by selecting import project (in the first popup window of Android Studio or on the File menu) and then selecting the build.gradle file in the GpsTracker > phoneClients > android directory. From the menu, select Tools > Android > SDK Manager. Select everything under Tools, Android 4.4.2 and Extras (down at the bottom). Then install those packages. In the next screen, click on the top Package on the left side, then on the right select “Accept License”, then click Install. This could take some time depending on your internet speed. Once this has completed, reopen the SDK Manager and make sure that the installs actually happened. It’s easy to mess this up if it’s your first time, so best to check. This hopefully should take care of gradle build issues that some people have been having. Finally, attach your android phone and make sure that its set up for development as explained here:

http://developer.android.com/tools/device.html

From the Android Studio Run menu, select Run to start the application on the phone. Enter a user name and then tap the tracking button. When you start tracking, the phone will send a gps location to the websmithing test website.

You can go to this webpage after you have run the app on the phone and find your location.

https://www.websmithing.com/gpstracker/displaymap.php

It’s a good idea to use the test page first because that let’s you know later on when you try to use your own server whether its the phone that is not working or the server that is not working. Once you have confirmed that the phone works with websmithing’s displaymap page, the it’s time to change the upload website to one of the servers you created above. Just change the server url text field when you start the application and then save it.

Ok, this should get you going on android, let’s turn our attention to iOS.

iOS Devices

Getting your iOS device working requires xcode. Xcode can be found in the app store here:

https://itunes.apple.com/us/app/xcode/id497799835?mt=12

This project uses AFNetworking, a popular http library. I decided to use it because it has a method to easily convert a dictionary of strings into the required format needed for sending a post request and also it automatically handles making http calls in a background task. Well worth the effort of installing it. So, to install it, you need to install cocoapods, which is a dependency manager (java users think maven…) more or less. Here are instructions on installing cocoapods:

http://guides.cocoapods.org/using/getting-started.html

Once you have that installed, go to the phoneClients > ios directory (where the Podfile is located) and from the command prompt run the following command:

To open the project, you need to click on the GpsTracker.xcworkspace icon, not the normal GpsTracker.xcodeproj. This is to make sure AFNetworking loads properly. When you start xcode, it may ask you if you want to enter developer mode, select yes.

Plug in your phone and in the upper left hand corner, make sure it is selected from the drop down box. As with the Android device above, you can test the application with the websmithing displaymap test page. When you have confirmed that the app is working with websmithing, change defaultUploadWebsite on line 181 of WSViewController.m to point to your web server that you have set up above.

Windows Phone

The windows phone app can be opened with Visual Studio Express 2012 for Windows Phone.

http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff630878(v=vs.105).aspx

With windows phone, you need to register your phone for development. Microsoft explains how to do it here:

http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769508(v=vs.105).aspx

Make sure your phone is unlocked and then install the app on the phone. After you have tested the phone with the websmithing displaymap page, you can point the phone to your own webserver by changing defaultUploadWebsite on line 77 of MainPage.xaml.cs. Don’t forget to change line 87, phonenumber, to something other than windowsPhoneUser. It will help you in testing.

Java Me / J2Me Phones

This is what Gps Tracker was originally written for. Before iPhone and android came out, most phones were j2me phones. The reason why I continue to support these old phones is because there is a possibility that there are still more of these (mostly inexpensive) phones still being used than there are android phones! Android may not be the mostly widely used mobile platform! Android may not be the mostly widely used mobile platform according to Fortune magazine. So I continue to support it.

To work with the java me application, I used Netbeans version 7.4 on Windows. I ended up installing it in my windows 8 virtualbox. I tried running it on my macbook pro but had some real problems with it. It was easier to run it in virtualbox. Anyway, here is the netbeans download:

https://netbeans.org/downloads/

I only tested the app out in the browser because I did not have one of those older phones easily available. But in essence, you created a .jad file and install that on the java me phone. You can even email the file to your phone and open that up on the phone.

Now that I have finished this quick guide, I will be writing more in depth tutorials for each of the servers and clients. They will be coming soon!

Version 3 of Gps Tracker has been released!

gps trackerI’m happy to report that version 3 of GpsTracker has shipped. This is a major change and the application now supports tracking of android, ios, windows phone and java me/j2me cell phones using google maps. What the application does is track cell phones periodically using gps, wifi and/or cell towers. It allows you to track a phone every minute or every 5 minutes or whatever you want and display it on a google map. You can view the tracking in real time or view previously saved routes.

The software is open source and MIT licensed. It took me a couple of months to write the new phone clients and this is now my full time job. Please donate with the button on the right if this software is useful to you and I hope you enjoy it.

I have put the software in 2 places, on github of course:

https://github.com/nickfox/GpsTracker

and on sourceforge:

https://sourceforge.net/projects/gpsmapper

I’m keeping the sourceforge account up to date because it still gets a lot of traffic, around 7,000 downloads a week. If you want the very latest then go to my github account, I am making commits daily.

Feel free to follow this blog by clicking on the orange button up to the right, tutorial and training videos on youtube will be coming soon.

Find your lost Android Cell Phone!

I’ve taken the open source GPS cell phone tracker and rewrote it so that it works with Android cell phones. Since I wrote the original tracker, I’ve had many people who are not developers ask me how they can track their cell phone. So I created a website that allows people to do that. You can download the app from the Android Market by searching for MyCellTracker and then going to:

www.mycelltracker.com

You can try the app free for 7 days and then subscribe for either $1.99/month or $19.95/year. Please give it a try and also click on the facebook like button if you would be so kind!