Category Archives: android

Check out the first video in our Gps Tracker How-To Series!

I’m pleased to announce that I have created the first video in my new series explaining how the Gps Tracker application works. This first video focuses on the android client since that is by far the most popular platform. The series is going to comprise both a written tutorial and a video tutorial. All of the video tutorials will be on my youtube channel. You can subscribe to my channel to get notified when I create a new tutorial. The android video tutorial is here:

How the Android Gps Tracker Client Works Video on Youtube

and the written tutorial is here:

https://www.websmithing.com/2014/04/23/how-the-gpstracker-android-client-works/

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:

SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
currentlyTracking = sharedPreferences.getBoolean("currentlyTracking", false);

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:

    
private void startAlarmManager(Context context) {
    Log.d(TAG, "startAlarmManager");
    Context context = getBaseContext();
    alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    gpsTrackerIntent = new Intent(context, GpsTrackerAlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(context, 0, gpsTrackerIntent, 0);

    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime(),
        intervalInMinutes * 60000, // 60000 = 1 minute
        pendingIntent);
}

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:

<uses-permission android:name="android.permission.WAKE_LOCK" />

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

public class GpsTrackerAlarmReceiver extends WakefulBroadcastReceiver {
    private static final String TAG = "GpsTrackerAlarmReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, LocationService.class));
    }
}

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 (currentlyTracking) {
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime(),
        intervalInMinutes * 60000, // 60000 = 1 minute,
        pendingIntent);
} else {
    alarmManager.cancel(pendingIntent);
}

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.

<receiver android:name=".GpsTrackerBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

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:

<service android:name=".LocationService">
</service>

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:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (!currentlyProcessingLocation) {
        currentlyProcessingLocation = true;
        startTracking();
    }
    return START_STICKY;
}

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:

@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "onConnected");

    locationRequest = LocationRequest.create();
    locationRequest.setInterval(1000); // milliseconds
    locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    locationClient.requestLocationUpdates(locationRequest, this);
    }

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:

if (location.getAccuracy() < 100.0f) {
    stopLocationUpdates();
    sendLocationDataToWebsite(location);
}

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:

stopSelf();

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.

if (firstTimeGettingPosition) {
    editor.putBoolean("firstTimeGettingPosition", false);
} else {
    Location previousLocation = new Location("");

    previousLocation.setLatitude(sharedPreferences.getFloat("previousLatitude", 0f));
    previousLocation.setLongitude(sharedPreferences.getFloat("previousLongitude", 0f));

    float distance = location.distanceTo(previousLocation);
    totalDistanceInMeters += distance;
    editor.putFloat("totalDistanceInMeters", totalDistanceInMeters);
}

editor.putFloat("previousLatitude", (float)location.getLatitude());
editor.putFloat("previousLongitude", (float)location.getLongitude());
editor.commit();

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.

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

Android and iPhone gps tracker coming soon

I just wanted to let people know that I have been working on the google maps gps tracker for android and iphone. This will allow people to track their android or iphone and store routes. This can be very helpful for companies that need to track employees and see where an employee has been or currently is.

How to Update the UI in an Android Activity Using Data from a Background Service

Recently, I needed to update an activity in Android with data I gathered from a background Service. I couldn’t find any decent examples on the web or StackOverflow, so I decided to put one together. I really like when someone has a complete working sample, so I will provide that as well you can download the source code from Github at the end of this article. The Android project is very simple, with just two classes, the activity and the background service. We’ll take a look first at the background service to see how the data is generated.

The first thing that needs to be done is to create a string called BROADCAST_ACTION, this is simply a string that identifies what kind of action is taking place. Most of the time, it’s common to use the package name with the kind of action added to the end, so we’ll do that here. The next step is to create a handler that will be used to broadcast our data every 5 seconds. It’s better to use a Handler instead of Timer because a Timer creates a new thread.

public class BroadcastService  extends Service {
    private static final String TAG = "BroadcastService";
    public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
    private final Handler handler = new Handler();
    Intent intent;
    int counter = 0;

In onCreate, I’ve created a Intent and passed the BROADCAST_ACTION to the constructor of the intent. Notice that the Intent was defined as a global variable above. The intent will be called repeatedly in the Handler below and there is no reason to create a new intent every 5 seconds, so I’ll create it once here.

    @Override
    public void onCreate() {
        super.onCreate();
    	intent = new Intent(BROADCAST_ACTION);	
    }

In onStart, first we call removeCallbacks to remove any existing callbacks to the handler and make sure we don’t get more callbacks than we want. Then we call our handler with a one second delay. This will start our runnable object below.

    @Override
    public void onStart(Intent intent, int startId) {
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second   
    }

Our runnable object creates a new thread, performs whatever code is in the run method and then shuts down. In the run method, we do two things call the DisplayLoggingInfo method and then calls handler.postDelayed again but this time with a 5 second delay. This is how the repeating timer is created. One of the things that is nice about doing it this way, is that you can put a variable in place of 5000 and that way you can externally control the interval between call to the runnable object.

    private Runnable sendUpdatesToUI = new Runnable() {
    	public void run() {
    	    DisplayLoggingInfo();    		
    	    handler.postDelayed(this, 5000); // 5 seconds
    	}
    };  

In the following method, we add some data to our intent that was created above. I’m just adding the date and a simple counter that increments itself. Then we call sendBroadcast with that intent which sends a message and whoever is registered to receive that message will then get it.

    private void DisplayLoggingInfo() {
    	Log.d(TAG, "entered DisplayLoggingInfo");

    	intent.putExtra("time", new Date().toLocaleString());
    	intent.putExtra("counter", String.valueOf(++counter));
    	sendBroadcast(intent);
    }

At this point, the Service is completed and now it’s time to take a look at our Activity and see how we consume and display our data. The first thing we’ll do is create an intent with the name of the Service class. This will be passed to startService and stopService.

public class BroadcastTest extends Activity {
	private static final String TAG = "BroadcastTest";
	private Intent intent;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        intent = new Intent(this, BroadcastService.class);
    }

Now, we’ll create a BroadcastReceiver to receive the message that is going to be broadcast from the Service above. The BroadcastReceiver has one method, onReceive, it gets called and then the BroadcastReceiver object is destroyed. In the onReceive method, we call updateUI passing in our intent which is holding the data to display.

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	updateUI(intent);       
        }
    };    

In onResume and onPause, we start and stop our Service. This happens when the screen (Activity) displays and goes away. We also register our BroadcastReceiver by passing in an IntentFilter. Do you see that the IntentFilter is using the same static string, BROADCAST_ACTION, that we created in the Service above. This is how we identify the message that is broadcast. in onPause, we also make sure that we call unregisterReceiver to stop listening for broadcasts.

	@Override
	public void onResume() {
		super.onResume();		
		startService(intent);
		registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
	}
	
	@Override
	public void onPause() {
		super.onPause();
		unregisterReceiver(broadcastReceiver);
		stopService(intent); 		
	}

This last bit of code is pretty straight forward. We get our data out of the intent and set our two TextViews with the data. They will be updated every 5 seconds.

    private void updateUI(Intent intent) {
    	String counter = intent.getStringExtra("counter"); 
    	String time = intent.getStringExtra("time");
    	Log.d(TAG, counter);
    	Log.d(TAG, time);
    	
    	TextView txtDateTime = (TextView) findViewById(R.id.txtDateTime);  	
    	TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
    	txtDateTime.setText(time);
    	txtCounter.setText(counter);
    }

I’ve made the entire project available for download here on GitHub.

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!