Recipe 8.4 Using a BroadcastReceiver to Obtain Locations
Rather than use the LocationListener class to obtain location data, you can instead use a PendingIntent object together with a BroadcastReceiver class. Using this approach, you can continue to listen for location data even if your application is closed by the user.
Solution
In the first recipe in this chapter (“Obtaining Geographical Location Using GPS, Wi-Fi, or Cellular Networks”), you learned how to obtain your geographical location using an instance of the LocationListener class. The LocationListener class is useful if you are monitoring the location from within an activity. However, if the activity is destroyed, the LocationListener object would also be destroyed, and you would no longer be able to track your location. An alternative for getting your location is to create a BroadcastReceiver class together with a PendingIntent object. To see how it works, create a class in your package and name it MyLocationReceiver.java. Code it as follows:
package net.learn2develop.lbsreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.widget.Toast; public class MyLocationReceiver extends BroadcastReceiver { @Override ...
Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.