0

I get location as:

    LocationManager locationManager;
                GeoPoint p; 
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


                boolean gps_enabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (gps_enabled) {
                    Location location = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                }

However, gps_enabled=true but location =null. Why can't get my location? Can you help me? If i get by NETWORK_PROVIDER is ok.

Seshu Vinay
  • 13,560
  • 9
  • 60
  • 109
mum
  • 1,637
  • 11
  • 34
  • 58

5 Answers5

2

Well there are a number of things. The GPS could be coming from what's known as a "cold start" where it doesn't have any knowledge of where it is. In these cases the last known location is null. You could also be in a location where there is no signal to get a location fix. It could also be a crappy GPS or a crappy GPS driver (cough samsung cough). These things aren't exact.

First I would start with this documentation. Location Acquisition Strategies

Next, let's evaluate the logic here. Yes the GPS is enabled. However in this context, enabled means that it is enabled for use by applications with the fine location permission. Enabled does not mean it is currently active and acquiring locations. But there is good news! You can make a listener or subscribe to location updates.

So as others have mentioned, make sure you have the permissions setup in your manifest. I assume you do, or else your app probably crashed and burned with a permission issue on the getLastKnownLocation() call.

Then for receiving location updates, take a look at the LocationListener class. By implementing this interface you can use locationManager.requestLocationUpdates() to register for location updates from the GPS.

Using your code (I assume some things, like it's within an activity and the method being described is invoked on the UI Thread):

public class MyActivity extends Activity implements LocationListener {
  // The rest of the interface is not really relevant for the example
  public void onProviderDisabled(String provider) { }
  public void onProviderEnabled(String provider) { }
  public void onStatusChanged(String provider, int status, Bundle extras) { }

  // When a new location is available from the Location Provider,
  // this method will be called.
  public void onLocationChanged(Location location) {
        // You should do whatever it was that required the location
        doStuffWithLocation(location);
        // AND for the sake of your users' battery stop listening for updates
        (LocationManager) getSystemService(LOCATION_SERVICE).removeUpdates(this);
        // and cleanup any UI views that were informing of the delay
        dismissLoadingSpinner();
  }

  // Then in whatever code you have
  public void methodA() {
    LocationManager locationManager;
    GeoPoint p; 
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (gps_enabled) {
      Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
      if (location == null) {
            // When it is null, register for update notifications.
            // run this on the UI Thread if need be
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            // Since this might take some time you should give the user a sense
            // that progress is being made, i.e. an indeterminate ProgressBar 
            showLoadingSpinner();
      } else {
            // Otherwise just use the location as you were about to
            doStuffWithLocation(location);
      }
    }
    ...

This should run your code as you would expect, and then in the case where the GPS does not have a location, you spin it up and wait until you get a location. Once that occurs you shut it off and use it as you were planning to. This is sort of a naive approach, but you should be able to use it as a simple basis. A real solution should take into account the cases where there is no chance of getting a location, handling the cases when the location provider is not available or becomes unavailable while you are waiting for a location, and validate the sanity of the location.

Greg Giacovelli
  • 10,164
  • 2
  • 47
  • 64
  • I am not sure what is being asked. When you request location updates with a listener you won't block. This is an asynchronous callback for when a new location is found. So there is no need for a new thread. Just as long as the call to request updates happens from the UI Thread. If you wish to register within another thread, the call to register should be wrapped inside of a `Runnable` that's invoked on the UI Thread via: a Handler's `post()` where the Handler started on the UI Thread, the `runOnUIThread()` method or a `View`s `post()` method. This will guaranteed a successful register – Greg Giacovelli Oct 16 '12 at 14:27
1

Did you add these permissions in the manifest:

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

Edit:

go through this link. It gives different strategies to find the location.

Seshu Vinay
  • 13,560
  • 9
  • 60
  • 109
1

in manifest did u give the permissions..

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
mainu
  • 448
  • 2
  • 11
1

The method getLastKnownLocation() just returns the last location acquired by GPS withour turning it on. If for example, you reobot your phone, cache will be cleaned and GPS wouldn't have any cached location to return, until you start it and let it acquire at leat one location.

Luis
  • 11,978
  • 3
  • 27
  • 35
1

use code:

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

    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
    System.out.println("Provider " + provider + " has been selected.");
    double lat = (double) (location.getLatitude());
    double lng = (double) (location.getLongitude());

    Log.i(TAG, "Lattitude:" +lat);
    Log.i(TAG, "Longitude:" +lng);

    } else {
      System.out.println("Location not avilable");
    }
  }
SubbaReddy PolamReddy
  • 2,083
  • 2
  • 17
  • 23
  • running in emulator or real device? – SubbaReddy PolamReddy Oct 16 '12 at 09:50
  • i run on real device. Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); It's ok . But device hasn't got network . it doesn't working. – mum Oct 16 '12 at 09:51
  • next it doesn't show location null.. then it will automatically shows the google co-ordinates... just use that code... simple... – SubbaReddy PolamReddy Oct 16 '12 at 09:53