Android My Location-Fix

Cuando se llama a mi actividad de mapa, hago una llamada en el onCreate para addUserMapPoint. Esta función contiene dos instancias en las que intento obtener la información de ubicación mediante myOverlay.getMyLocation. En la carga inicial de esta actividad el resultado del primer intento devuelve un GeoPoint nulo y después de que el subproceso principal de UI complete el segundo intento localizado en el subproceso de escucha de myOverlay.runOnFirstFix (new Runnable () … es llamada después de un segundo y contiene Un GeoPoint que contiene una lat y lon.La llamada dentro de esta función de escucha parece que poner el punto en el mapa y la línea mapController.animateTo (gp) se mueve el mapa a mi ubicación.Mi aplicación tiene un botón de actualización que cuando Clicked dispara de nuevo esta actividad .. Necesito lat y lon para obtener datos de ubicación de otro servicio.Después de la actualización, la segunda vez a través del código de actividad de mapa esperaba la primera llamada a myOverlay.getMyLocation () ahora sería Capaz de obtener el GeoPoint, pero sigue siendo nulo.

Si no soy capaz de obtener el GeoPoint por esta primera llamada a myOverlay.getMyLocation entonces cómo puedo pasar el lat y lon valor de la segunda llamada que se encuentra en el myOverlay.runOnFirstFix (nuevo Runnable () … hilo. He estado tratando de agregar el lat y lon a MyApp que es la clase de bean ayudante, pero el lat y lon en esta clase es nulo incluso después de la actualización.Si manualmente establecer un lat y lon manualmente en la función addUserMapPoint la primera vez que la actividad Se accede a estos valores se mantienen.Supongo que esto es porque se está estableciendo en el hilo principal de la interfaz de usuario.

public class MapActivity extends com.google.android.maps.MapActivity { private MapView mapView = null; private MapController mapController = null; private MyLocationOverlay myOverlay = null; public static MyApp app; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); app = (MyApp) getApplicationContext(); mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapController = mapView.getController(); List<Overlay> mapOverlays = mapView.getOverlays(); mapOverlays.clear(); addUserMapPoint(mapView); if (!app.isLocServOff()) { //map other points – service call to get items from our service near lat and lon addOtherMapPoints(mapOverlays); } else { Toast.makeText(app.getApplicationContext(),"Current location could not be found.",Toast.LENGTH_LONG).show(); } } private void addUserMapPoint(MapView mapView){ myOverlay = new MyLocationOverlay(app.getApplicationContext(), mapView); myOverlay.disableCompass(); myOverlay.enableMyLocation(); if(app.getMyLat()==null||app.getMyLon()==null){ GeoPoint gp = myOverlay.getMyLocation(); if(gp!=null){ app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6())); app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6())); app.setLocServOff(false); }else{ app.setLocServOff(true); } } myOverlay.runOnFirstFix(new Runnable() { public void run() { GeoPoint gp = myOverlay.getMyLocation(); if(gp!=null){ app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6())); app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6())); app.setLocServOff(false); mapController.animateTo(gp); }else{ app.setLocServOff(true); } } }); mapView.getOverlays().add(myOverlay); } } 

Su ayuda está siendo solicitada para la siguiente pregunta. ¿Cómo puedo obtener un GeoPoint que contiene un lat y lon en el hilo principal de la interfaz de usuario o cómo puedo pasar estos valores de GeoPoint Puedo obtener de la myOverlay.runOnFirstFix (nuevo Runnable () … hilo?

Si va a sugerir que utilizo Handler o runOnUiThread, por favor proporcione un ejemplo de código que pase el lat y lon de vuelta a algo que pueda ser usado por la vista principal de UI thread / map. He intentado cosas como el código siguiente que no produjo el resultado deseado. Pude conseguir el mensaje del pan tostado para aparecer, pero no podía conseguir el lat y el lon pasado de una manera que podría utilizar.

  final Handler handler = new Handler(); myOverlay.runOnFirstFix(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { GeoPoint gp = myOverlay.getMyLocation(); if(gp!=null){ app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6())); app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6())); app.setLocServOff(false); mapController.animateTo(gp); }else{ app.setLocServOff(true); } //Toast.makeText(getApplicationContext(),"wowoowowowoowoowowow",Toast.LENGTH_LONG).show(); } }); } }); 

También he utilizado código como el siguiente para obtener el lat y lon y funciona, pero porque la ubicación actual a veces sería un lat diferente y lon que whas se devuelve por ejemplo, no pude obtener una señal GPS, pero aún así El valor antiguo se devolvió. He añadido cheques para ver si los datos lat / lon eran mayores de 2 minutos, pero todavía no podía coincidir con el lat y lon más recientes con el que es devuelto por myOverlay.getMyLocation.

  LocationManager locMgr = (LocationManager)appcontext.getSystemService(Context.LOCATION_SERVICE); MyLocationListener locLstnr = new MyLocationListener(); //fetch current location for current location locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locLstnr, appcontext.getMainLooper()); 

 handler.post(new Runnable() { @Override public void run() { GeoPoint gp = myOverlay.getMyLocation(); if(gp!=null){ app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6())); app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6())); app.setLocServOff(false); // HERE WE HAVE VALID gp VALUE AND WE NEED TO SHARE IT mapController.animateTo(gp); }else{ app.setLocServOff(true); } } }); 

Creo que tu app.set / get | MyLat / Lon no funciona porque los llamas desde diferentes subprocesos. Para solucionarlo, sincronice los métodos set y get para MyLat / Long. (Crear objeto para sincronización y sincronización en él)

O si te gusta tu manera con el manejador esto debería funcionar:

 final Handler handler = new Handler(); // BE SURE TO RUN THIS LINE ON UI THREAD ... myOverlay.runOnFirstFix(new Runnable() { @Override public void run() { // THIS PART WORKS AS BEFORE final GeoPoint gp = myOverlay.getMyLocation(); mapController.animateTo(gp); ... // AND THIS RUNNABLE TO UPDATE MyLat/MyLong FROM UI THREAD handler.post(new Runnable() { @Override public void run() { app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6())); app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6())); }); } }); 

A continuación puede encontrar algunos ejemplos sobre cómo obtener la ubicación actual en el subproceso de interfaz de usuario, pero en primer lugar, una cierta información de fondo.

GPS puede tomar algún tiempo (15 segundos a 1 minuto) para obtener la primera corrección después de que se haga la solicitud de nueva ubicación. Esta es la razón por la que su primer intento de obtenerlo de myOverlay falla, y sólo después de la primera corrección puede obtener el valor.

Durante este período de blackout puedes usar getLastKnownLocation() para obtener la última ubicación GPS bien conocida si tienes prisa. Si no es availble devuelve null

El código:

Última ubicación conocida

 LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE); Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(loc != null){ //we have a valid location. Check location date } 

Solicitar una actualización de una sola ubicación

 LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE); locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, appcontext.getMainLooper); 

Solicitar una actualización de ubicación continua

 LocationManager locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); //use 0 for minDistance and minDistance between updates if you need the maximum update frequency. locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minDistance, minTime, locationListener); 

Oyente de ubicación para actualización de posición única y continua

Éste es el último pedazo de código, y es el lugar donde usted consigue los nuevos lugares frescos solicitados arriba.

Cuando una localización nueva que coincida con su petición critirea definida anteriormente sea recuperada por GPS, este oyente se llama inmediatamente, a menos que el dispositivo esté ocupado haciendo otra cosa que no puede ser interrumpida (es decir, la devolución de llamada está en un hilo pausado o que bloquea) .

Desde dentro de onLocationChanged() puede establecer cualquier nivel de clase archivado según corresponda. Si registró el listener desde el subproceso de UI, éste se ejecutará en ejecución en la interfaz de usuario.

 LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location fix) { fix.setTime(fix.getTime() + timeZoneOffset); //Add Timezone offset if needed //here you have a fresh new location in fix... //You can set the value of any class level field from here } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } }; 

Saludos.

Algunos de los puntos más importantes que debe tener en cuenta al buscar la ubicación del dispositivo son:

  1. La fijación GPS por satélite no está garantizada para ser recibida en la cantidad adecuada de tiempo. Por ejemplo, el dispositivo está dentro de un edificio / no bajo cielo abierto.
  2. Asegúrese de que los oyentes GPS por satélite no se mantengan activos durante mucho tiempo. Mantener el oyente activado implicará mantener la radio GPS en todo el tiempo lo que es la mayor razón de drenaje de la batería.

En el siguiente ejemplo de código, el método de encuesta en LinkedBlockingQueue no se devuelve hasta que haya transcurrido un intervalo de tiempo especificado o en el que se coloque una ubicación.

Utilice algo como el siguiente para obtener la ubicación actual:

  Location getCurrentLocation() { long startmillis = 0; LinkedBlockingQueue<Location> mQueue = new LinkedBlockingQueue<Location>(); try{ long millisSinceLastCollection = System.currentTimeMillis() - startmillis; startmillis = System.currentTimeMillis(); mQueue.clear(); // Register for Satellite GPS listener as well as Network GPS listener. registerGPSListeners(); // Wait for a maximum of one minutes for a fix Location firstfix = mQueue.poll(1, TimeUnit.MINUTES); if(firstfix != null && firstfix.getProvider().equals(LocationManager.GPS_PROVIDER)) { return firstfix; } long elapsedmillis = System.currentTimeMillis() - startmillis; long remainingmillis = ONE_MINUTE_IN_MS - elapsedmillis; if (remainingmillis <= 0){ return firstfix; } Location secondfix = mQueue.poll(remainingmillis, TimeUnit.MILLISECONDS); if(secondfix != null && secondfix.getProvider().equals(LocationManager.GPS_PROVIDER)) { return secondfix; } /* * In case we receive fix only from Network provider, return it. */ if(firstfix != null && firstfix.getProvider().equals(LocationManager.NETWORK_PROVIDER)) { return firstfix; } } catch(Exception e){ Logger.e("GPS: Exception while listening for the current location", e); } finally { Logger.i("GPS: Unsubscribing from any existing GPS listeners"); unregisterGPSListeners(); } } // GPS issue fix edit. private void registerGPSListeners() { LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE); if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, oneShotNetworkGPSLocationListener, MyAppApp.getAppContext().getMainLooper()); if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100, oneShotSatelliteGPSLocationListener, AirWatchApp.getAppContext().getMainLooper()); } } private void unregisterGPSListeners(){ final LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(oneShotSatelliteGPSLocationListener); locationManager.removeUpdates(oneShotNetworkGPSLocationListener); } //One shot location listener protected LocationListener oneShotSatelliteGPSLocationListener = new LocationListener() { public void onLocationChanged(Location location) { try { mQueue.put(location); } catch (InterruptedException e) { Logger.e("Exception in putting new Location to the queue", e); } Logger.d("GPS: Location received from Satellite GPS Provider"); unregisterGPSListeners(); } public void onProviderDisabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} }; //One shot location listener protected LocationListener oneShotNetworkGPSLocationListener = new LocationListener() { public void onLocationChanged(Location location) { try { mQueue.put(location); } catch (InterruptedException e) { Logger.e("Exception in putting new Location to the queue", e); } Logger.d("GPS: Location received from Network GPS Provider"); // Stop Listener for one-shot location fix from Network GPS provider. final LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(oneShotNetworkGPSLocationListener); Logger.d("GPS: Unsubscribed the network location listener."); } public void onProviderDisabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} }; 

Android modifica la interfaz de usuario y maneja los eventos de entrada desde un único hilo de la interfaz de usuario (subproceso principal).

Si el programador no utiliza construcciones de concurrencia, todo el código de una aplicación de Android se ejecutará en este subproceso.

GPS es la mejor manera de determinar la ubicación de un usuario, pero hacer ping a un satélite de posicionamiento global demasiado rápidamente drenará la batería de un dispositivo móvil, tardará mucho tiempo en obtener la ubicación del usuario y este método no siempre funciona en interiores. You are not getting your location in first attempt that's why you are getting null over there.

El Network Location Provider de Android calcula la ubicación de un usuario en función de las señales de torre celular y Wi-Fi. No sólo utiliza menos energía de la batería que el GPS, pero también es más rápido y funciona si el usuario está fuera o dentro.

Estoy dando mi código de trabajo a continuación que muestran progress dialog , escuchar la ubicación del usuario y después de obtener la ubicación mostrar la location overlay del usuario en Google-map

Supongo que tienes permisos de abajo en tu Menifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Mi clase principal

 public class MyLocationOnMap extends MapActivity { private MapView mapView; private MyLocationOverlay itemizedoverlay; private LocationManager locationManager; private String provider; private MyLocationListener locationListener; MyBroadCastreceiver myBroadCastreceiver; /** * My current Location <i>longitude</i>. */ static int longitude; /** * My current Location <i>latitude</i>. */ static int latitude; /** *My progress indicator. */ ProgressDialog loadingDialog; public static final String INTENT_FILTER_TAG="my location broadcast receiver"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_location_on_map); loadingDialog = new ProgressDialog(this); loadingDialog.setTitle("Hot Spots!"); loadingDialog.setMessage("Please wait ..."); loadingDialog.setIndeterminate(true); loadingDialog.setCancelable(false); loadingDialog.show(); // Configure the Map mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.setStreetView(true); /** * Get your location manager and Location Listener... */ locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener=new MyLocationListener(); myBroadCastreceiver = new MyBroadCastreceiver(); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.i("GPS_Enabled", "GPS enable! listening for gps location."); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener); registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG)); } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Log.i("Network_Enabled", "Network enable! listening for Network location."); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, locationListener); registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG)); } else { loadingDialog.dismiss(); Toast.makeText(this, "No Provider enable!", Toast.LENGTH_LONG).show(); } }//End of onCreate...... /** * My BroadCast Receiver, that is called when i get the location of user. * @author Rupesh Yadav. * */ class MyBroadCastreceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //Remove location update when you get user`s location very first time. locationManager.removeUpdates(locationListener); //Remove the broadcast listener that update my location on map. unregisterReceiver(myBroadCastreceiver); GeoPoint point = new GeoPoint(latitude, longitude); mapView.getController().animateTo(point); List<Overlay> mapOverlays = mapView.getOverlays(); Drawable drawable = MyLocationOnMap.this.getResources().getDrawable(R.drawable.hs_mapoverlay); itemizedoverlay = new MyLocationOverlay(drawable, MyLocationOnMap.this); OverlayItem overlayitem = new OverlayItem(point, "Hello!", "My Current Location :)"); itemizedoverlay.addOverlay(overlayitem); mapOverlays.add(itemizedoverlay); loadingDialog.dismiss(); } } /** * My Location listener... */ class MyLocationListener implements LocationListener{ @Override public void onLocationChanged(Location location) { latitude=(int) ((location.getLatitude())*1E6); longitude=(int) ((location.getLongitude())*1E6); //Send broadcast to update my location. Intent sendLocationIntent=new Intent(INTENT_FILTER_TAG); sendBroadcast(sendLocationIntent); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } } 

Clase MyLocationOverlay

 public class MyLocationOverlay extends ItemizedOverlay<OverlayItem> { Context mContext; private ArrayList<OverlayItem> hsOverlays = new ArrayList<OverlayItem>(); public MyLocationOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); // TODO Auto-generated constructor stub } public MyLocationOverlay(Drawable defaultMarker, Context context) { super(boundCenterBottom(defaultMarker)); mContext = context; } @Override protected OverlayItem createItem(int i) { // TODO Auto-generated method stub return hsOverlays.get(i); } @Override public int size() { // TODO Auto-generated method stub return hsOverlays.size(); } /** * add new OverlayItem objects to map OverlayItem ArrayList. * * @param overlay */ public void addOverlay(OverlayItem overlay) { hsOverlays.add(overlay); populate(); } /** * Called when user clicks on map overlay. */ @Override protected boolean onTap(int index) { // TODO Auto-generated method stub // return super.onTap(index); OverlayItem item = hsOverlays.get(index); AlertDialog.Builder dialog = new AlertDialog.Builder(mContext); dialog.setTitle(item.getTitle()); dialog.setMessage(item.getSnippet()); dialog.show(); return true; } 

Puede modificar el Broadcasr Receiver Location Listener y Broadcasr Receiver según su necesidad. Espero que esto solucione su problema.
¡Atentamente!

He utilizado esta clase para detectar mi lat & lon: Espero que esto sea útil para usted también.

Ejemplo de cómo usar: GPSUtility.getInstance (Context) .getLatitude (); GPSUtility.getInstance (CamPhotoModeAct.this) .getLongitude ()

 public class GPSUtility { public static final String TAG = "GPSUtility"; private Context ctx; Timer timer1; LocationManager lm; LocationResult locationResult; boolean gps_enabled=false; boolean network_enabled=false; private double latitude; private double longitude; private static SharedPreferences SHARED_PREF; private static SharedPreferences.Editor EDITOR_SHARED_PREF; private static GPSUtility this_instance; public GPSUtility(Context ctx){ this.ctx = ctx; SHARED_PREF = ctx.getSharedPreferences(ConstantsG.SHARED_PREF_FILE, Context.MODE_PRIVATE); EDITOR_SHARED_PREF = SHARED_PREF.edit(); this.getLocation(innerLocationResult); } public static GPSUtility getInstance(Context ctx){ if(this_instance == null) this_instance = new GPSUtility(ctx); return this_instance; } public static void updateLocation(Context ctx){ GPSUtility.getInstance(ctx);//this writes the latitude and longitude in sharable preference file } public double getLatitude(){ String latitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LATITUDE,null); if(latitudeStr == null){ latitude = 0.0; } else{ latitude = Double.parseDouble(latitudeStr); } return latitude; } public double getLongitude(){ String longitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LONGITUDE,null); if(longitudeStr == null){ longitude = 0.0; } else{ longitude = Double.parseDouble(longitudeStr); } return longitude; } private void updateWithNewLocation(Location location) { if (location != null) { latitude = location.getLatitude(); EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LATITUDE, String.valueOf(latitude) ); longitude = location.getLongitude(); EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LONGITUDE, String.valueOf(longitude)); EDITOR_SHARED_PREF.commit(); } } public boolean getLocation(LocationResult result) { //I use LocationResult callback class to pass location value from GPSUtility to user code. locationResult=result; if(lm==null) lm = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE); //exceptions will be thrown if provider is not permitted. try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex); } try { network_enabled = lm .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex); } //Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show(); //don't start listeners if no provider is enabled if(!gps_enabled && !network_enabled){ Toast.makeText(this.ctx, "You should enable gps or be connected to network.", Toast.LENGTH_LONG).show(); return false; } if(gps_enabled) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps); if(network_enabled) lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork); timer1=new Timer(); timer1.schedule(new GetLastLocation(), 10000); return true; } LocationListener locationListenerGps = new LocationListener() { public void onLocationChanged(Location location) { timer1.cancel(); locationResult.gotLocation(location); lm.removeUpdates(this); lm.removeUpdates(locationListenerNetwork); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; LocationListener locationListenerNetwork = new LocationListener() { public void onLocationChanged(Location location) { timer1.cancel(); locationResult.gotLocation(location); lm.removeUpdates(this); lm.removeUpdates(locationListenerGps); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; class GetLastLocation extends TimerTask { @Override public void run() { //Context context = getClass().getgetApplicationContext(); Location net_loc=null, gps_loc=null; if(gps_enabled) gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(network_enabled) net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); //if there are both values use the latest one if(gps_loc!=null && net_loc!=null){ if(gps_loc.getTime()>net_loc.getTime()) locationResult.gotLocation(gps_loc); else locationResult.gotLocation(net_loc); return; } if(gps_loc!=null){ locationResult.gotLocation(gps_loc); return; } if(net_loc!=null){ locationResult.gotLocation(net_loc); return; } locationResult.gotLocation(null); } } public static abstract class LocationResult{ public abstract void gotLocation(Location location); } LocationResult innerLocationResult = new LocationResult() { @Override public void gotLocation(Location location) { updateWithNewLocation(location); } }; } 
  • mapview.getoverlays () excepción de puntero nulo
  • Android - ¿Qué archivo debug.keystore es IntelliJ firmando mi aplicación?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.