1

I am trying to retrieve Location as follows:

LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);        

Criteria criteria = new Criteria();

// Getting the name of the provider that meets the criteria
String provider = locationManager.getBestProvider(criteria, false);

if(provider!=null && !provider.equals("")){
   // NOTE: the location below is null !!
   Location location = locationManager.getLastKnownLocation(provider);
   String lat = location.getLatitude();
   String lng = location.getLongitude();
}

The 'location' above is null. Why?

But when i open the (Google) Maps app - it shows location correctly, and even a notification icon (looks like a exclamation mark) shows up.

And there is a GPS Coordinates app - which also shows up blank.

I have turned on Settings > 'Location' on the phone. If it matters this is Android 4.4.4 Sony Experia phone.

Jasper
  • 8,440
  • 31
  • 92
  • 133

1 Answers1

2

Well, it seems that you're not checking properly if the GPS is working or not. The way you should do it:

final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

if (!manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) { 
    //GPS is not enabled !! 
} 

You can also create an AlertDialog so the user is aware that the GPS is not enabled and you can send him to the GPS settings by doing this:

startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

After this, I'd implement a location listener and get coordinates, here is an example, check it out

How do I get the current GPS location programmatically in Android?

UPDATE: They might be getting coordinates through other provider (usually the one which is working better at that moment). So if the GPS it not working, just try other provider, here is an example:

 Location lastKnownLocation = null;
 List<String> providers = null;
 if(locationManager != null) providers = locationManager.getAllProviders();

        if(providers != null)
        {
            for(int i=0; i<providers.size(); i++)
            {
                if(locationManager != null) lastKnownLocation = locationManager.getLastKnownLocation(providers.get(i));
                if(lastKnownLocation != null)
                {
                    position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                    break;
                }
            }
        }
Community
  • 1
  • 1
JaimeToca
  • 46
  • 1
  • 5
  • Well then...How is Google Maps and some other Location dependent apps working on the same mobile phone? – Jasper May 04 '15 at 16:53