Example usage for android.location LocationManager requestLocationUpdates

List of usage examples for android.location LocationManager requestLocationUpdates

Introduction

In this page you can find the example usage for android.location LocationManager requestLocationUpdates.

Prototype

@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria,
        LocationListener listener, Looper looper) 

Source Link

Document

Register for location updates using a Criteria, and a callback on the specified looper thread.

Usage

From source file:com.thomasokken.free42.Free42Activity.java

public int shell_get_location(DoubleHolder lat, DoubleHolder lon, DoubleHolder lat_lon_acc, DoubleHolder elev,
        DoubleHolder elev_acc) {//from   ww  w  . j  a v a  2 s  . c o m
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locat_inited = false;
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        return 0;
    }
    if (!locat_inited) {
        locat_inited = true;
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria cr = new Criteria();
        cr.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(cr, true);
        if (provider == null) {
            locat_exists = false;
            return 0;
        }
        LocationListener ll = new LocationListener() {
            public void onLocationChanged(Location location) {
                // TODO: Verify units etc.
                locat_lat = location.getLatitude();
                locat_lon = location.getLongitude();
                locat_lat_lon_acc = location.getAccuracy();
                locat_elev = location.getAltitude();
                locat_elev_acc = location.hasAltitude() ? locat_lat_lon_acc : -1;
            }

            public void onProviderDisabled(String provider) {
                // Ignore
            }

            public void onProviderEnabled(String provider) {
                // Ignore
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
                // Ignore
            }
        };
        try {
            lm.requestLocationUpdates(provider, 60000, 1, ll, Looper.getMainLooper());
        } catch (IllegalArgumentException e) {
            return 0;
        } catch (SecurityException e) {
            return 0;
        }
        locat_exists = true;
    }

    if (locat_exists) {
        lat.value = locat_lat;
        lon.value = locat_lon;
        lat_lon_acc.value = locat_lat_lon_acc;
        elev.value = locat_elev;
        elev_acc.value = locat_elev_acc;
        return 1;
    } else
        return 0;
}