Getting the current GPS location on Android
Asked Answered
M

5

4

I'm trying to get the user's current location via GPS capability,

Wrote a simple class that implements LocationListener

public class LocationManagerHelper implements LocationListener {

    private static double latitude;
    private static double longitude;

    @Override
    public void onLocationChanged(Location loc) {
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();
    }

    @Override
    public void onProviderDisabled(String provider) { }

    @Override
    public void onProviderEnabled(String provider) { }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public static double getLatitude() {
        return latitude;
    }

    public static double getLongitude() {
        return longitude;
    }

}

and from a simple Action I'm accessing these longitude and latitude values

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /** create a TextView and write Hello World! */
    TextView tv = new TextView(this);

    LocationManager mlocManager = 
                    (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new LocationManagerHelper();

    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            mlocListener);

    if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
                    + '\n');
            tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                    + '\n');
    } else {
        tv.setText("GPS is not turned on...");
    }

    /** set the content view to the TextView */
    setContentView(tv);

But it always returns 0.0 as the result.Couldn't figure out the problem.

Macias answered 5/2, 2011 at 5:55 Comment(1)
If you don't want to write that much code and have a simpler interface, use github.com/delight-im/Android-SimpleLocationGaven
S
3

Your location update callbacks can't be fired until after onCreate() returns. If you initialize your lat/long variables to dummy values you will probably see you are printing those values.

Put some logging in your onLocationChanged so that you can see it's being fired, then read up a bit on how android applications work with regard to callbacks and updating the UI.

Also make sure your application has appropriate permissions in its manifest.

Sienkiewicz answered 5/2, 2011 at 6:6 Comment(0)
A
19

Location updates are in fact asynchronous. This means the API does not make your calling thread wait until a new location is available ; instead you register an observer object with a specific method (callback) that gets called whenever a new location gets computed.

In the Android LocationManager API, the observer is a LocationListener object, and the main callback for location updates is onLocationChanged()

Here is a diagram trying to explain this point (hope this helps rather than confuse you!)

Sequence diagram

So from your current code :

  • Declare mlocListener as a member of your Activity subclass
  • Add log outputs (Logcat lines) in your LocationListener implementation
  • Keep the rest of the code as is.
  • Add the right permissions in the manifest (FINE_LOCATION is needed for GPS) if not done so yet.
  • Try to have the phone connected to Internet and near a window, in order to get a quite fast GPS fix (should be ~30s).

Then launch the app and watch what happens in the logcat. you will see that status changes and location updates are not immediate after the initial request, thus explaining why your textview always shows (0.0,0.0).

More: http://developer.android.com/guide/topics/location/obtaining-user-location.html

Avowal answered 5/2, 2011 at 9:24 Comment(2)
Thanks a lot for a super duper explanation.Macias
That worked.. the log just prints the lon/lat values in every 30 seconds. Now I have to get those values and update the UI.Macias
S
3

Your location update callbacks can't be fired until after onCreate() returns. If you initialize your lat/long variables to dummy values you will probably see you are printing those values.

Put some logging in your onLocationChanged so that you can see it's being fired, then read up a bit on how android applications work with regard to callbacks and updating the UI.

Also make sure your application has appropriate permissions in its manifest.

Sienkiewicz answered 5/2, 2011 at 6:6 Comment(0)
F
2

After you get mLocListener - set the Criteria as shown below

String mlocProvider;
Criteria hdCrit = new Criteria();
hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);
mlocProvider = mlocManager.getBestProvider(hdCrit, true);

and then use getLastKnownLocation

tv.append("\n\nLocations (starting with last known):");
Location currentLocation = mlocManager.getLastKnownLocation(mlocProvider);

Make sure you have these in your manifest
uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

If you are using Emulator - In DDMS Perspective, look for Location Controls in Emulator Control tab. Then use Manual tab to set the Longitude and Latitude and click send - do this when your program is running you see a call to onLocationchanged. It is good idea to have log in onLocationChanged.

BTW, the parameters in requestLocationUpdates are set to "... 0,0..." - it will drain your battery - I have seen the phone go dead in 6 - 8 hours - change it to "...30000, 100..." - the first parameter in millisec and the other is in meters.

Florella answered 5/2, 2011 at 6:55 Comment(1)
" If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request ONLY the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. (Permission for ACCESS_COARSE_LOCATION includes permission ONLY for NETWORK_PROVIDER.) " . You just need to add one permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) not both at same time.Eight
P
0

When you check it on emulator it will give 0.0. you have to pass the locations to emulator. you can pass this from C:\android-sdk_r06\android-sdk-windows\tools\ddms.bat file.

in ddms there is a tab named emulator controls. from there you can pass the locations to emulator. try this. hope it will work.

Plymouth answered 5/2, 2011 at 6:6 Comment(0)
S
-3

how to create app ?

Getting current location co-ordinates by action (get Location) Lat/long

Post the location to the webserver to be displayed on the map.(Submit) Clear button to clear the old location(Clear Location) or on (submit) it becomes clear (0.0.0.0)

Getting the current GPS location on Android http://developer.android.com/guide/topics/location/obtaining-user-location.html

Siskind answered 15/6, 2012 at 15:24 Comment(1)
Not really a constructive answer to the guys question.Fernandes

© 2022 - 2024 — McMap. All rights reserved.