martes, 31 de marzo de 2015

Android: Geo location


public class LocationHelper {

    private LocationManager locationManager;
    private MyLocationListener locationListener;


    public void listenToLocationUpdates(Context context) {

        if (getLocationManager(context) != null) {

            try {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 5000, 0,
                        getLocationListener(context));

            } catch (IllegalArgumentException e) {

                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 5000, 0,
                        getLocationListener(context));
            }
        }
    }

    private LocationManager getLocationManager(Context context) {

        if (locationManager == null) {
            locationManager = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);
        }
        return locationManager;
    }

    private MyLocationListener getLocationListener(Context context) {
        if (locationListener == null) {
            locationListener = new MyLocationListener(context);
        }
        return locationListener;
    }

    public class MyLocationListener implements LocationListener {

        private Context context;

        public MyLocationListener(Context context) {
            this.context = context;
        }

        @Override
        public void onLocationChanged(Location location) {

            if (location != null) {
                // TODO - New location available

                locationManager.removeUpdates(this);
            }
        }

        public void onProviderDisabled(String provider) {
            // TODO
            locationManager.removeUpdates(this);
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

    }
}  

No hay comentarios:

Publicar un comentario