Mi ubicación actual siempre devuelve null. ¿Cómo puedo arreglar esto?

Estoy tratando de encontrar mi ubicación actual para un proyecto de Android. Cuando se carga la aplicación, mi ubicación actual siempre es nula. He configurado los permisos en el manifiesto, etc Cuando me encuentro la ubicación actual tengo la intención de utilizar las coordenadas para encontrar distancias a otras ubicaciones en el mapa. Mi fragmento de código está debajo. ¿Por qué siempre obtengo un valor nulo?

locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria crit = new Criteria(); towers = locMan.getBestProvider(crit, false); location = locMan.getLastKnownLocation(towers); if (location != null) { System.out.println("Location is not null!"); lat = (int) (location.getLatitude() *1E6); longi = (int) (location.getLongitude() * 1E6); GeoPoint ourLocation = new GeoPoint(lati, longi); OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String", "2nd String"); CustomPinpoint custom = new CustomPinpoint(d, MainMap.this); custom.insertPinpoint(overlayItem); overlayList.add(custom); overlayList.clear(); } else { System.out.println("Location is null! " + towers); Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT) .show(); } 

getLastKnownLocation() utiliza la ubicación (es) previamente encontrada por otras aplicaciones. Si ninguna aplicación ha hecho esto, entonces getLastKnownLocation() devolverá null.

Una cosa que usted puede hacer a su código para tener una mejor oportunidad de conseguir como última ubicación conocida iterar sobre todos los proveedores habilitados, no sólo el mejor proveedor. por ejemplo,

 private Location getLastKnownLocation() { List<String> providers = mLocationManager.getProviders(true); Location bestLocation = null; for (String provider : providers) { Location l = mLocationManager.getLastKnownLocation(provider); ALog.d("last known location, provider: %s, location: %s", provider, l); if (l == null) { continue; } if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { ALog.d("found best last known location: %s", l); bestLocation = l; } } if (bestLocation == null) { return null; } return bestLocation; } 

Si su aplicación no puede gestionar sin tener una ubicación y, si no hay una última ubicación conocida, tendrá que escuchar las actualizaciones de la ubicación. Usted puede echar un vistazo a esta clase para un ejemplo,

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

Vea el método onStartCommand() , donde verifica si el proveedor de red está habilitado. Si no, utiliza la última ubicación conocida. Si está habilitado, se registra para recibir actualizaciones de ubicación.

Si u encontrar la ubicación actual de los dispositivos el uso siguiente método en la clase principal

 public void find_Location(Context con) { Log.d("Find Location", "in find_location"); this.con = con; String location_context = Context.LOCATION_SERVICE; locationManager = (LocationManager) con.getSystemService(location_context); List<String> providers = locationManager.getProviders(true); for (String provider : providers) { locationManager.requestLocationUpdates(provider, 1000, 0, new LocationListener() { public void onLocationChanged(Location location) {} public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); addr = ConvertPointToLocation(latitude, longitude); String temp_c = SendToUrl(addr); } } } 

Y el método Add User Permission en su archivo de manifiesto

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

¿Ha intentado invertir el código? Por ejemplo, if (location == null) entonces imprime que la ubicación es null, y la ubicación de impresión no es null. Tengo ese problema una vez antes y que parecía haberlo arreglado (no sé por qué). Trata eso.

Si eso no funciona, tal vez la API de Google Maps devuelva el valor nulo, en cuyo caso es un problema con GM-API o con el método de llamada. Cualquiera de estos podría ser el problema.

Espero que esto ayude,

-JXP

Pruebe esto esto no le dará una ubicación actual nula

 class GetLastLocation extends TimerTask { LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener mlocListenerTmp = new CustomLocationListener(); private final Handler mLocHandler; public GetLastLocation(Handler mLocHandler) { this.mLocHandler = mLocHandler; } @Override public void run() { timer.cancel(); mlocManager.removeUpdates(mlocListenerTmp); Location location = mlocManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); { if (mlocListenerTmp != null) { mlocManager.removeUpdates(mlocListenerTmp); } currentLocation = location; } if (location != null) { String message = String.format( "Location \n Longitude: %1$s \n Latitude: %2$s", location.getLongitude(), location.getLatitude()); Log.d("loc", " :" + message); Bundle b = new Bundle(); { b.putBoolean("locationRetrieved", true); { Message msg = Message.obtain(); { msg.setData(b); mLocHandler.sendMessage(msg); } } } } else { Log.d( "loc", ":No GPS or network signal please fill the location manually!"); location = mlocManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { currentLocation = location; Bundle b = new Bundle(); { b.putBoolean("locationRetrieved", true); { Message msg = Message.obtain(); { msg.setData(b); mLocHandler.sendMessage(msg); } } } } else { Bundle b = new Bundle(); { b.putBoolean("locationRetrieved", false); { Message msg = Message.obtain(); { msg.setData(b); mLocHandler.sendMessage(msg); } } } } } } } 

Llámalo así

 timer.schedule(new GetLastLocation(mLocHandler), 3000); 

Y la clase customLocation es la siguiente

 public class CustomLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { loc.getLatitude(); loc.getLongitude(); currentLocation = loc; String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude(); Log.d("loc", "onLocationChanged" + Text); } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} } 

Si lo está probando en un dispositivo de malvavisco, pruebe a habilitar el permiso de ubicación para su aplicación manualmente.

  • Androide. Fragmento getActivity () a veces devuelve null
  • Touch Calculator en Android
  • Java.lang.NullPointerException en el paquete extras = data.getExtras ();
  • Argumento DialogFragment y excepción nullpointer
  • Nullpointer excepción en oncreateView () de fragmento
  • TextToSpeech muestra Null Pointer Exception?
  • Java Singleton + clase interna mal entendida
  • Class.getResource (className) que me da NullPointerException
  • NullPointerException Causado por getActionBar ()
  • ConnectivityManager puntero nulo
  • Llamando context.getResources () devuelve null
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.