简体   繁体   中英

Android: GPS Location not working

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.

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;
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM