Finding the Last Known Location

To add location support to MyFirstAndroidApp, edit the file First, you must add the appropriate import statements: import android.location.Location; import android.location.LocationManager;

Now, create a new method called getLocation() in your class and make a call to this method in your onCreate() method.The getLocation() method gets the last known location on the phone and logs it as an informational message. If the operation fails for some reason, the method logs an error.

The getLocation() method should look something like this:

public void getLocation() { try {

LocationManager locMgr = (LocationManager)

getSystemService(LOCATION_SERVICE); Location recentLoc = locMgr.

getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.i(DEBUG_TAG, "loc: " + recentLoc.toString());

Log.e(DEBUG_TAG, "Location failed", e);

Figure 3.16 Setting the location of the emulator to Yosemite Valley.

Finally, your application requires special permissions to access location-based functionality. You must register this permission in your AndroidManifest.xml file.To add location-based service permissions to your application, perform the following steps:

1. Double-click the AndroidManifest.xml file.

2. Switch to the Permissions tab.

3. Click the Add button and choose Uses Permission.

4. In the right pane, select android.permission.ACCESS_FINE_LOCATION.

5. Save the file.

Now, if you run My First Android App in the emulator, your application logs the GPS coordinates you provided to the emulator as an informational message, viewable in the LogCat pane of Eclipse.

Easy Software Profits

Easy Software Profits

Here's How Anyone Can Start, Build and Run their Own Successful Software Empire Without Knowing the First Thing About Programming, Scripting Or Any 'Coder' Stuff. There is no doubt about it software sells. Software has a high percieved value and it solves problems for people.  A claim that can't always be made for PDF books, Video products and the like.

Get My Free Ebook

Post a comment