Android examples for Map:Last Location
Returns the last known location longitude.
//package com.java2s; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationManager; public class Main { /** A reference to the system Location Manager. */ private static LocationManager mLocationManager; /** Returns the last known location longitude. Use this if you know that the location listener * doesn't need to turn on. This first tries GPS, then network, and returns 0.0 if GPS nor Network is enabled. */ public static final double getLastKnownLocationLongitude() { loadLocationManager();/*from w ww . ja va2 s.c o m*/ double longitude = 0.0; // Load last known location coordinate, if available, so that user doesn't have to wait as long for a location. if (isGpsEnabled()) { Location gpsLocation = mLocationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (gpsLocation != null) { longitude = gpsLocation.getLongitude(); } } else if (isNetworkEnabled()) { Location networkLocation = mLocationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (networkLocation != null) { longitude = networkLocation.getLongitude(); } } return longitude; } /** Instantiates the mLocationManager variable if needed. */ private static final void loadLocationManager() { // TODO: Don't get Application context this way. Either pass in a static way of getting app context like in second line, or create a constructor to accept the context. if (mLocationManager == null) { mLocationManager = (LocationManager) (new Activity() .getApplicationContext()) .getSystemService(Context.LOCATION_SERVICE); } // if (mLocationManager == null) { mLocationManager = (LocationManager) MyApp.getContext().getSystemService(Context.LOCATION_SERVICE); } } /** Returns true if GPS provider is enabled, otherwise false. */ public static final boolean isGpsEnabled() { loadLocationManager(); try { return mLocationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception e) { // If exception occurs, then there is no GPS provider available. return false; } } /** Returns true if network provider is enabled, otherwise false. */ public static final boolean isNetworkEnabled() { loadLocationManager(); try { return mLocationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception e) { // If exception occurs, then there is no network provider available. return false; } } }