Using the Location API

Posted on Nov 18, 2009 (4 years ago). Seen 61,834 times. 17 comments. Permalink Feed
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Stream Posts: 42
Tagged as: Android Tutorial

Android supports location-based services, as you'd expect from any modern mobile OS. In Android, LocationManager is responsible for handling this.

To get the location manager, we ask the context to getSystemService() for location services. Next we ask the location manager for list of all available providers.

You may not care about all available location providers but just want to get the best one available. To do this, we specify our criteria for "best". For example, do we require altitude and bearing, allow cost, etc.

We can now ask the location manager for the last known location, for the specific provider. This is helpful to quickly place you close to last location, while waiting for updates to come in.

It is important to register with the location manager to receive the location updates. To do so, we recommend the onResume(). Also, you should unregister from location notifications in your onPause(). Tracking your location can be expensive on the battery and CPU of the device, so this is good practice to stop doing the work while we are paused and normally don't care about the updates. This is important.

The LocationListener which we are implementing will allow us to get certain callbacks. Those callbacks include location, provider and status changes.


LocationDemo.java
Code:

package com.marakana;

import java.util.List;

import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;

public class LocationDemo extends Activity implements LocationListener {
private static final String TAG = "LocationDemo";
private static final String[] S = { "Out of Service",
"Temporarily Unavailable", "Available" };

private TextView output;
private LocationManager locationManager;
private String bestProvider;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get the output UI
output = (TextView) findViewById(R.id.output);

// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// List all providers:
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
printProvider(provider);
}

Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
output.append("\n\nBEST Provider:\n");
printProvider(bestProvider);

output.append("\n\nLocations (starting with last known):");
Location location = locationManager.getLastKnownLocation(bestProvider);
printLocation(location);
}

/** Register for the updates when Activity is in foreground */
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
}

/** Stop the updates when Activity is paused */
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}

public void onLocationChanged(Location location) {
printLocation(location);
}

public void onProviderDisabled(String provider) {
// let okProvider be bestProvider
// re-register for updates
output.append("\n\nProvider Disabled: " + provider);
}

public void onProviderEnabled(String provider) {
// is provider better than bestProvider?
// is yes, bestProvider = provider
output.append("\n\nProvider Enabled: " + provider);
}

public void onStatusChanged(String provider, int status, Bundle extras) {
output.append("\n\nProvider Status Changed: " + provider + ", Status="
+ S[status] + ", Extras=" + extras);
}

private void printProvider(String provider) {
LocationProvider info = locationManager.getProvider(provider);
output.append(info.toString() + "\n\n");
}

private void printLocation(Location location) {
if (location == null)
output.append("\nLocation[unknown]\n\n");
else
output.append("\n\n" + location.toString());
}

}

The layout file for this application is trivial. It uses a single TextView for the output. Yes, we could use maps to show the location, but that's subject of another demo.


/res/layout/main.xml
Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/output" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>


And finally, remember to add the appropriate permissions to your AndroidManifest.xml file

AndroidManifest.xml Code:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana" android:versionCode="1" android:versionName="1.0.0">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.Light">
<activity android:name=".LocationDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

The output should look similar to this:



Source Code:

http://thenewcircle.com/static/tutorials/LocationDemo.zip

Comments

Posted on Sep 6, 2010
Photo Noraziahtulhidayu Kamarudin
UTeM
Member since Sep 6, 2010
Thank you for uploading such a nice tutorial for a newbie developer like me.. who just trying to develop application for android.. your tutorial helping me lots.. thanks again:D
Posted on Oct 5, 2010
Photo Stanislaw Nalepa
N/A
Member since Oct 4, 2010
Hello.
I agree with the above member. Thanks.
I have a problem with the permissions when installing this example on my physical device. When running on a virtual device these problems don't occur but there is no information on location providers.
On my real phone the console (in Eclipse) says:

[2010-10-05 07:18:54 - LekfullaAdresser] Android Launch!
[2010-10-05 07:18:54 - LekfullaAdresser] adb is running normally.
[2010-10-05 07:18:54 - LekfullaAdresser] Performing eu.webstudiolund.ladresser.mapAddress activity launch
[2010-10-05 07:19:11 - LekfullaAdresser] Uploading LekfullaAdresser.apk onto device '80A352166044493735'
[2010-10-05 07:19:11 - LekfullaAdresser] Installing LekfullaAdresser.apk...
[2010-10-05 07:19:14 - LekfullaAdresser] Success!
[2010-10-05 07:19:14 - LekfullaAdresser] Starting activity eu.webstudiolund.ladresser.mapAddress on device 80A352166044493735
[2010-10-05 07:19:14 - LekfullaAdresser] ActivityManager: Unable to chmod /data/nv/FRStatus.txt: Operation not permitted
[2010-10-05 07:19:14 - LekfullaAdresser] ActivityManager: Unable to chmod /data/nv/factoryreset_ongoing.txt: Operation not permitted
[2010-10-05 07:19:15 - LekfullaAdresser] ActivityManager: cannot create /data/reboot_enable_menu/reboot_enable_menu: permission denied
[2010-10-05 07:19:15 - LekfullaAdresser] ActivityManager: scandir: Permission denied
[2010-10-05 07:19:15 - LekfullaAdresser] ActivityManager: cannot create /sys/module/pm2/parameters/hidden_reset: permission denied
[2010-10-05 07:19:16 - LekfullaAdresser] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=eu.webstudiolund.ladresser/.mapAddress }


What is wrong?
The phone's display is like this:
Posted on Oct 5, 2010
Photo Noraziahtulhidayu Kamarudin
UTeM
Member since Sep 6, 2010
i think you better try to install the .apk file which is located in the bin folder of your project, hope this may helps
Posted on Oct 5, 2010
Photo Stanislaw Nalepa
N/A
Member since Oct 4, 2010
Thank you for your answer, Noraziahtulhidayu. I tried as you said, installing the apk from the bin folder and got hopeful as I was asked for granting permissions. But unfortunately the result was the same as before, when running the app: "Provider Disabled: network". Does the code really contain all necessary includes?
Or is the android.location library restricted in some way in some countries, like mine, Sweden?
Posted on Oct 5, 2010
Photo Noraziahtulhidayu Kamarudin
UTeM
Member since Sep 6, 2010
Have you turn on your mobile internet services?
Posted on Oct 5, 2010
Photo Stanislaw Nalepa
N/A
Member since Oct 4, 2010
Yes, they are turned on. I hope I dont need root access for this demo to work?
Posted on Oct 5, 2010
Photo Stanislaw Nalepa
N/A
Member since Oct 4, 2010
I wonder, does this demo work with gps, or gsm triangulation?
Posted on Oct 6, 2010
Photo Noraziahtulhidayu Kamarudin
UTeM
Member since Sep 6, 2010
for mine i'm using with gps that also need to be turned on
Posted on Oct 22, 2010
Photo Ravi S
Consultant
Member since Oct 22, 2010
Thanks for tha app.

I was successfully able to run the app on the real device but Location is shown as Unknown.

I am not able to find the location on the screen it shows Provider Disabled:network

I have selected the option GPS.

Can you please help me regarding the same.
Posted on Oct 22, 2010
Photo Noraziahtulhidayu Kamarudin
UTeM
Member since Sep 6, 2010
Hi Ravi S

Please turn on your mobile internet services and also GPS.Hope it helps
Posted on Oct 22, 2010
Photo Ravi S
Consultant
Member since Oct 22, 2010
I have done that, but not solved.
Posted on Nov 2, 2010
Photo JaganMohan Reddy
SE
PGC Info Tech Pvt.Ltd
Member since Nov 2, 2010
Thanks alot Marko, you are my friend yar
this GPS application is working fine for me.

really very very thanks to uploading such code.

I am new to this android.
Posted on Dec 21, 2010
Photo David Zachariah
Software
ATK
Member since Dec 21, 2010
Dear Marko,

Thank you for the Demo codes. I learned so much from them.

Anyway, I am having problem when I convert it from Activity to Service:
public class MyService extends Service implements LocationListener

The problem seems to be in this function:

@Override
public void onStart(Intent intent, int startid) {
....
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
locationManager.requestLocationUpdates(provider, 10000, 1, this);
}
....
}

I think requestLocationUpdates() expects "activity" call back. When I run in my phone, it crashes at this line.

How do we setup the call back in Service type class?

Thank you,
Davidz
Posted on Mar 3, 2011
Photo Richard Frainier
Self
Member since Mar 3, 2011
Still a useful introduction. Thanks!
Posted on Apr 11, 2011
Photo Mitch McCann
Self
Member since Apr 11, 2011
Here is the link to a picture of what I got from cutting and pasting the code into Eclipse:

https://docs.google.com/leaf?id=0B3f8beUFJqZlOTVmMDhlNWEtZTdhMi00OTBkLThmMGEtZDdkNzQwNDgzODhj&sort=name&layout=list&num=50

I did send a lat and lon combo to the emulator via DDMS..

I will now try entering the code from the zip file?

I see no location...
Posted on Jul 21, 2011
Photo Sahitya Rao
Smsk
Member since Jul 21, 2011
can any one tell me how to create a service for this location manager program, so that i can send all longitude and latitude points to a external Database.I want to install that service on my client mobile phone...
Posted on Dec 10, 2011
Photo Ando Dev
Zzz
Member since Dec 10, 2011
Hi Ravi

is your issue got resolved, I am also getting the same response as you are getting....
any update into this ???