Code example for LocationManager: Finding current location

Methods: getLastKnownLocationgetProvidersrequestLocationUpdates

0
 
            // We're running on the main thread. The C++ side is responsible to 
            // bounce notifications to the Geolocation thread as they arrive in the mainLooper. 
            try { 
                Criteria criteria = new Criteria();
                mLocationManager.requestLocationUpdates(0, 0, criteria, this,
                        Looper.getMainLooper());
                if (mIsGpsEnabled) {
                    criteria.setAccuracy(Criteria.ACCURACY_FINE);
                    mLocationManager.requestLocationUpdates(0, 0, criteria, this,
                            Looper.getMainLooper());
                } 
            } catch(SecurityException e) {
                Log.e(TAG, "Caught security exception registering for location updates from " +
                    "system. This should only happen in DumpRenderTree."); 
            } catch(IllegalArgumentException e) {
                Log.e(TAG, "Caught IllegalArgumentException registering for location updates.");
            } 
        } 
 
        /** 
         * Unregisters this object from the location service. 
         */ 
        private void unregisterFromLocationUpdates() { 
            if (mIsRunning) {
                mIsRunning = false;
                mLocationManager.removeUpdates(this);
            } 
        } 
 
        private boolean usePassiveOneShotLocation() { 
            if (!isOnlyPassiveLocationProviderEnabled()) return false; 
 
            // Do not request a location update if the only available location provider is 
            // the passive one. Make use of the last known location and call 
            // onLocationChanged directly. 
            final Location location = mLocationManager.getLastKnownLocation(
                    LocationManager.PASSIVE_PROVIDER);
            if (location != null) {
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override 
                    public void run() { 
                        updateNewLocation(location);
                    } 
                }); 
            } 
            return true; 
        } 
 
        /* 
         * Checks if the passive location provider is the only provider available 
         * in the system. 
         */ 
        private boolean isOnlyPassiveLocationProviderEnabled() { 
            List<String> providers = mLocationManager.getProviders(true);
            return providers != null && providers.size() == 1
                    && providers.get(0).equals(LocationManager.PASSIVE_PROVIDER);
        } 
    }