Java tutorial
//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 latitude. 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 getLastKnownLocationLatitude() { loadLocationManager(); double latitude = 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) { latitude = gpsLocation.getLatitude(); } } else if (isNetworkEnabled()) { Location networkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (networkLocation != null) { latitude = networkLocation.getLatitude(); } } return latitude; } /** Instantiates the mLocationManager variable if needed. */ private static final void loadLocationManager() { if (mLocationManager == null) { mLocationManager = (LocationManager) (new Activity().getApplicationContext()) .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; } } }