¿Cómo obtener Latitude y Longitud del dispositivo móvil en android?

¿Cómo obtengo la Latitude y la Longitud actuales del dispositivo móvil en android utilizando las herramientas de ubicación?

Utilice el LocationManager .

 LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); 

La llamada a getLastKnownLocation() no bloquea – lo que significa que devolverá null si no hay ninguna posición disponible actualmente – por lo que probablemente querrá echar un vistazo a pasar un LocationListener al método requestLocationUpdates() , que le dará actualizaciones asíncronas De su ubicación.

 private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); } } lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener); 

Deberá darle a su aplicación el permiso ACCESS_FINE_LOCATION si desea utilizar GPS.

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

También puede agregar el permiso ACCESS_COARSE_LOCATION para cuando GPS no esté disponible y seleccionar su proveedor de ubicación con el método getBestProvider() .

Aquí está la clase LocationFinder para encontrar la ubicación GPS. Esta clase llamará a MyLocation , que hará el negocio.

LocationFinder

 public class LocationFinder extends Activity { int increment = 4; MyLocation myLocation = new MyLocation(); // private ProgressDialog dialog; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intermediat); myLocation.getLocation(getApplicationContext(), locationResult); boolean r = myLocation.getLocation(getApplicationContext(), locationResult); startActivity(new Intent(LocationFinder.this, // Nearbyhotelfinder.class)); GPSMyListView.class)); finish(); } public LocationResult locationResult = new LocationResult() { @Override public void gotLocation(Location location) { // TODO Auto-generated method stub double Longitude = location.getLongitude(); double Latitude = location.getLatitude(); Toast.makeText(getApplicationContext(), "Got Location", Toast.LENGTH_LONG).show(); try { SharedPreferences locationpref = getApplication() .getSharedPreferences("location", MODE_WORLD_READABLE); SharedPreferences.Editor prefsEditor = locationpref.edit(); prefsEditor.putString("Longitude", Longitude + ""); prefsEditor.putString("Latitude", Latitude + ""); prefsEditor.commit(); System.out.println("SHARE PREFERENCE ME PUT KAR DIYA."); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; // handler for the background updating } 

Mi ubicacion

 public class MyLocation { Timer timer1; LocationManager lm; LocationResult locationResult; boolean gps_enabled=false; boolean network_enabled=false; public boolean getLocation(Context context, LocationResult result) { //I use LocationResult callback class to pass location value from MyLocation to user code. locationResult=result; if(lm==null) lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); //exceptions will be thrown if provider is not permitted. try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){} try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception 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) 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); // Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show(); 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); } } 

Con google cosas cambia muy a menudo: no de las respuestas anteriores trabajado para mí.

Abril 2016

Basado en este entrenamiento de google aquí es cómo lo haces usando

Proveedor de ubicación fusionado

Esto requiere configurar los servicios de Google Play

Clase de actividad

 public class GPSTrackerActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleApiClient mGoogleApiClient; Location mLastLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } protected void onStart() { mGoogleApiClient.connect(); super.onStart(); } protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override public void onConnected(Bundle bundle) { try { mLastLocation = LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient); if (mLastLocation != null) { Intent intent = new Intent(); intent.putExtra("Longitude", mLastLocation.getLongitude()); intent.putExtra("Latitude", mLastLocation.getLatitude()); setResult(1,intent); finish(); } } catch (SecurityException e) { } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } } 

uso

En tu actividad

  Intent intent = new Intent(context, GPSTrackerActivity.class); startActivityForResult(intent,1); 

Y este método

  protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 1){ Bundle extras = data.getExtras(); Double longitude = extras.getDouble("Longitude"); Double latitude = extras.getDouble("Latitude"); } } 

Usted puede conseguir latlng actual usando esto

  public class MainActivity extends ActionBarActivity { private LocationManager locationManager; private String provider; private MyLocationListener mylistener; private Criteria criteria; @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the location provider criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default // user defines the criteria criteria.setCostAllowed(false); // get the best provider depending on the criteria provider = locationManager.getBestProvider(criteria, false); // the last known location of this provider Location location = locationManager.getLastKnownLocation(provider); mylistener = new MyLocationListener(); if (location != null) { mylistener.onLocationChanged(location); } else { // leads to the settings because there is no last known location Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } // location updates: at least 1 meter and 200millsecs change locationManager.requestLocationUpdates(provider, 200, 1, mylistener); String a=""+location.getLatitude(); Toast.makeText(getApplicationContext(), a, 222).show(); } private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location location) { // Initialize the location fields Toast.makeText(MainActivity.this, ""+location.getLatitude()+location.getLongitude(), Toast.LENGTH_SHORT).show() } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!", Toast.LENGTH_SHORT).show(); } @Override public void onProviderEnabled(String provider) { Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!", Toast.LENGTH_SHORT).show(); } @Override public void onProviderDisabled(String provider) { Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!", Toast.LENGTH_SHORT).show(); } } 

Por encima de las soluciones también es correcto, pero algún tiempo si la ubicación es nula, entonces se bloquea la aplicación o no funciona correctamente. La mejor manera de obtener Latitude y Longitud de android es:

  Geocoder geocoder; String bestProvider; List<Address> user = null; double lat; double lng; LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); bestProvider = lm.getBestProvider(criteria, false); Location location = lm.getLastKnownLocation(bestProvider); if (location == null){ Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show(); }else{ geocoder = new Geocoder(activity); try { user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); lat=(double)user.get(0).getLatitude(); lng=(double)user.get(0).getLongitude(); System.out.println(" DDD lat: " +lat+", longitude: "+lng); }catch (Exception e) { e.printStackTrace(); } } 
  • Cómo comparar una cadena de Intent.getStringExtra ()?
  • OnPostExecute no se llama después de la finalización AsyncTask
  • Mostrar siempre el título del marcador de mapa en Android
  • Vista previa de la pantalla completa con una relación de aspecto correcta
  • Android Studio no ve la clase ArrayList
  • Lamentablemente, (nombre de la aplicación) se ha detenido. Eclipse / Android
  • Android no puede obtener matriz de bytes de la intención
  • Android: cómo programar ronda sólo esquinas superiores de un mapa de bits?
  • NDK vs JAVA rendimiento
  • Cómo configurar el tamaño de fuente para el texto de los botones de diálogo
  • Motor ligero ligero androide de la plantilla
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.