Example usage for android.location LocationListener LocationListener

List of usage examples for android.location LocationListener LocationListener

Introduction

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

Prototype

LocationListener

Source Link

Usage

From source file:com.moodmap.HomeActivity.java

private void registerLocationListeners() {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (mLocationListener_Fine == null) {
        mLocationListener_Fine = new LocationListener() {
            // LocationListener
            @Override/*from w  ww .ja v  a2 s .co  m*/
            public void onLocationChanged(Location location) {

                float currentLocationAccuracy = location.getAccuracy();

                myLocationFixCnt_Fine++;
                if ((myLocationFixCnt_Fine >= Constants.kMaxGpsFixCnt)
                        || ((location.hasAccuracy()) && (currentLocationAccuracy <= 60.0))) // tighter,
                                                                                                                                                   // slower
                                                                                                                                                   // location
                {
                    // stop the fine location service
                    mLocationManager.removeUpdates(this);

                    // also stop the coarse location updates, if for some
                    // reason it has not resolved yet
                    if (mLocationListener_Coarse != null) {
                        mLocationManager.removeUpdates(mLocationListener_Coarse);
                    }
                }
                updateMyLocation(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.v(Constants.LOGTAG, "Fine Provider Disabled: " + provider);
            }

            @Override
            public void onProviderEnabled(String provider) {
                Log.v(Constants.LOGTAG, "Fine Provider Enabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                myStatusChangeCnt_Fine++;
                if ((status == LocationProvider.OUT_OF_SERVICE))
                // not sure if needed (myStatusChangeCnt_Fine >=
                // Constants.kMaxGpsFixCnt))
                {
                    // if cannot resolve the location, do not leave the gps
                    // running
                    mLocationManager.removeUpdates(mLocationListener_Fine);
                }
                Log.v(Constants.LOGTAG, "Fine Provider Status Change (OVER): " + provider + " status:" + status
                        + " myStatusChangeCnt_Fine:" + myStatusChangeCnt_Fine);

                // LocationProvider.OUT_OF_SERVICE
            }
        };
    }

    if (mLocationListener_Coarse == null) {
        mLocationListener_Coarse = new LocationListener() {
            // LocationListener
            @Override
            public void onLocationChanged(Location location) {

                float currentLocationAccuracy = location.getAccuracy();

                myLocationFixCnt_Coarse++;
                if ((myLocationFixCnt_Coarse >= Constants.kMaxGpsFixCnt)
                        || ((location.hasAccuracy()) && (currentLocationAccuracy <= 1000.0))) // quick,
                                                                                                                                                       // rough
                                                                                                                                                       // location
                {
                    // stop the coarse location service
                    mLocationManager.removeUpdates(this);
                }
                updateMyLocation(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.v(Constants.LOGTAG, "Provider Disabled: " + provider);
            }

            @Override
            public void onProviderEnabled(String provider) {
                Log.v(Constants.LOGTAG, "Provider Enabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.v(Constants.LOGTAG, "Provider Status Change: " + provider + " status:" + status);
                // LocationProvider.OUT_OF_SERVICE
            }
        };
    }

    // still in registerLocationListeners
    //
    String provider = null;
    Criteria crta = new Criteria();
    crta.setAccuracy(Criteria.ACCURACY_FINE);
    crta.setAltitudeRequired(false);
    crta.setBearingRequired(false);
    crta.setCostAllowed(false); // Indicates whether the provider is allowed
                                // to incur monetary cost.
                                // crta.setPowerRequirement(Criteria.POWER_MEDIUM); // POWER_LOW);
    provider = mLocationManager.getBestProvider(crta, true);
    // provider = LocationManager.NETWORK_PROVIDER;

    // get the last, possibly very wrong location
    currentLocation = mLocationManager.getLastKnownLocation(provider);
    // updateMyLocation(location);

    // minTime (2nd) the minimum time interval for notifications, in
    // milliseconds. This field is only used as a hint to conserve power,
    // and actual time between location updates may be greater or lesser
    // than this value.
    // minDistance (3rd)the minimum distance interval for notifications, in
    // meters
    // should be ~ 10000, 100
    // mLocationManager.requestLocationUpdates(provider, 3000, 50,
    // mLocationListener_Fine);
    mLocationManager.requestLocationUpdates(provider, 3000, 0, mLocationListener_Fine);

    // Add second quick location provider
    Criteria coarse = new Criteria();
    coarse.setAccuracy(Criteria.ACCURACY_COARSE);
    coarse.setAltitudeRequired(false);
    coarse.setBearingRequired(false);
    // coarse.setCostAllowed(false);
    // crta.setPowerRequirement(Criteria.POWER_MEDIUM); // POWER_LOW);
    String coarseProvider = mLocationManager.getBestProvider(coarse, true);
    if ((provider != null) && (!provider.contentEquals(coarseProvider))) {
        // only add coarse location resolution if DIFFERENT than the fine
        // location provider
        mLocationManager.requestLocationUpdates(coarseProvider, 1000, 1000, mLocationListener_Coarse);
    }
}

From source file:com.ohnemax.android.glass.doseview.CSDataSort.java

private void initializeLocationManager() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    for (String provider : providers) {
        if (locationManager.isProviderEnabled(provider)) {
            Log.d(TAG, "Location provider added: provider = " + provider);
        } else {//from w ww.  ja  v  a2  s . c  om
            Log.i(TAG, "Location provider not enabled: " + provider);
        }
        // TBD: Do this only for the currently enabled providers????
        try {
            locationManager.requestLocationUpdates(provider, 5000L, 5.0f, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.d(TAG, "locationChanged: location = " + location);
                    processLocationData(location);
                }

                @Override
                public void onProviderDisabled(String provider) {
                    Log.i(TAG, "providerDisabled: provider = " + provider);
                    // TBD
                }

                @Override
                public void onProviderEnabled(String provider) {
                    Log.i(TAG, "providerEnabled: provider = " + provider);
                    // TBD
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                    Log.i(TAG, "statusChanged: provider = " + provider + "; status = " + status + "; extras = "
                            + extras);
                    // TBD
                }
            });
        } catch (Exception e) {
            // ignore
            Log.w(TAG, "requestLocationUpdates() failed for provider = " + provider);
        }
    }
}

From source file:pandroid.agent.PandroidAgentListener.java

private void gpsLocation() {
    // Starts with GPS, if no GPS then gets network location
    //       /*from   w ww. j  ava 2 s  .  co m*/
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);
    Log.d("PANDROID providers count", "" + providers.size());

    /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
    Location loc = null;

    for (int i = providers.size() - 1; i >= 0; i--) {
        Log.d("PANDROID providers", providers.get(i));
        loc = lm.getLastKnownLocation(providers.get(i));
        if (loc != null)
            break;
    }

    if (loc != null) {
        Log.d("PANDROID", "loc != null");
        //if(latitude != loc.getLatitude() || longitude != loc.getLongitude()) {
        lastGpsContactDateTime = getHumanDateTime(-1);
        //`}
        Log.d("LATITUDE", Double.valueOf(loc.getLatitude()).toString());
        Log.d("LONGITUDE", Double.valueOf(loc.getLongitude()).toString());
        putSharedData("PANDROID_DATA", "latitude", Double.valueOf(loc.getLatitude()).toString(), "float");
        putSharedData("PANDROID_DATA", "longitude", Double.valueOf(loc.getLongitude()).toString(), "float");
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    String bestProvider = lm.getBestProvider(criteria, true);

    // If not provider found, abort GPS retrieving
    if (bestProvider == null) {
        Log.e("LOCATION", "No location provider found!");
        return;
    }

    lm.requestLocationUpdates(bestProvider, Core.interval, 15, new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.d("Best latitude", Double.valueOf(location.getLatitude()).toString());
            putSharedData("PANDROID_DATA", "latitude", Double.valueOf(location.getLatitude()).toString(),
                    "float");
            Log.d("Best longitude", Double.valueOf(location.getLongitude()).toString());
            putSharedData("PANDROID_DATA", "longitude", Double.valueOf(location.getLongitude()).toString(),
                    "float");
        }

        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        public void onProviderEnabled(String s) {
            // try switching to a different provider
        }

        public void onProviderDisabled(String s) {
            putSharedData("PANDROID_DATA", "enabled_location_provider", "disabled", "string");
        }
    });
    //}

}

From source file:com.google.ytd.SubmitActivity.java

private void getVideoLocation() {
    this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);//  w  w w . j  ava 2  s.c o  m
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);

    String provider = locationManager.getBestProvider(criteria, true);

    this.locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                SubmitActivity.this.videoLocation = location;
                double lat = location.getLatitude();
                double lng = location.getLongitude();
                Log.d(LOG_TAG, "lat=" + lat);
                Log.d(LOG_TAG, "lng=" + lng);

                TextView locationText = (TextView) findViewById(R.id.locationLabel);
                locationText.setText("Geo Location: " + String.format("lat=%.2f lng=%.2f", lat, lng));
                locationManager.removeUpdates(this);
            } else {
                Log.d(LOG_TAG, "location is null");
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    };

    if (provider != null) {
        locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
    }
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

/**
 * Starts location services and timer to stop after specfied time.
 * //from   w  w w.j av a2 s.c om
 * @see http://d.hatena.ne.jp/orangesignal/20101223/1293079002
 */
private void startLocationService(boolean highaccuracy) {
    //
    this.stopLocationService();
    this.mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (this.mLocationManager == null) {
        // this device has no location service. DOES NOTHING.
        return;
    }

    // gets active location providers.
    // if requires high accuracy, creates filtered provider list.
    List<String> providerList = this.mLocationManager.getProviders(true);
    if (highaccuracy) {
        ArrayList<String> candidateList = new ArrayList<String>();
        if (providerList != null) {
            for (String providerName : providerList) {
                if (providerName != null) {
                    LocationProvider provider = this.mLocationManager.getProvider(providerName);
                    if (provider != null && provider.getAccuracy() == Criteria.ACCURACY_FINE) {
                        candidateList.add(providerName);
                    }
                }
            }
        }
        providerList = candidateList;
    }
    // checks whether at least one location provider is available.
    if (providerList == null || !(providerList.size() > 0)) {
        // Shows the dialog which let user to open system preference.
        AlertDialogHelper.showConfirmationDialog(this, Messages.getString("P_LOCATION_PROVIDER_ERROR"),
                Messages.getString("P_CONFIRM_OPEN_LOACTIONPROVIDER_SETTINGS"),
                android.R.drawable.ic_dialog_info, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        try {
                            startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
                        } catch (final ActivityNotFoundException e) {
                            // DOES NOTHING
                            e.printStackTrace();
                        }
                    }
                });
        this.stopLocationService();
        return;
    }
    // Starts timer. Checks whether timed out frequently,
    // and stops location services when specified time comes.
    final boolean onlyPassive = (providerList.size() == 1 && "passive".equals(providerList.get(0)));
    this.mLocationTimer = new Timer(true);
    this.mTimedOut = System.currentTimeMillis() + 30000L;
    final Handler handler = new Handler();
    this.mToast = Toast.makeText(this, Messages.getString("P_MYLOCATION_FINDING"), Toast.LENGTH_SHORT);
    this.mToast.show();
    this.mLocationTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Sends the procedure checks whether timed out.
            handler.post(new Runnable() {
                @Override
                public void run() {
                    long current = System.currentTimeMillis();
                    if (current >= MapActivityBase.this.mTimedOut) {
                        // timed out.
                        MapActivityBase.this.onLocationServiceTimedout(onlyPassive);
                    } else {
                        // NOT timed out. Shows the TOAST.
                        MapActivityBase.this.mToast.show();
                    }
                }
            });
        }
    }, 0L, 1000L);
    // starts
    this.mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            // New location got. Sends it to JS.
            setLocation(location, true);
        }

        @Override
        public void onProviderDisabled(final String provider) {
            // DOES NOTHING.
        }

        @Override
        public void onProviderEnabled(final String provider) {
            // DOES NOTHING.
        }

        @Override
        public void onStatusChanged(final String provider, final int status, final Bundle extras) {
            // DOES NOTHING.
        }
    };
    for (String provider : providerList) {
        this.mLocationManager.requestLocationUpdates(provider, 0, 0, this.mLocationListener);
    }
}

From source file:com.esri.android.mapsapp.MapFragment.java

/**
 * Starts tracking GPS location.//from  w w  w. jav a 2s  .c o m
 */
void startLocationTracking() {
    LocationDisplayManager locDispMgr = mMapView.getLocationDisplayManager();
    mCompass.start();
    locDispMgr.setAutoPanMode(AutoPanMode.LOCATION);
    locDispMgr.setAllowNetworkLocation(true);

    locDispMgr.setLocationListener(new LocationListener() {

        boolean locationChanged = false;

        // Zooms to the current location when first GPS fix arrives
        @Override
        public void onLocationChanged(Location loc) {
            double locy = loc.getLatitude();
            double locx = loc.getLongitude();
            Point wgspoint = new Point(locx, locy);
            mLocation = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
                    mMapView.getSpatialReference());
            if (!locationChanged) {
                locationChanged = true;
                Unit mapUnit = mMapView.getSpatialReference().getUnit();
                double zoomWidth = Unit.convertUnits(SEARCH_RADIUS, Unit.create(LinearUnit.Code.MILE_US),
                        mapUnit);
                Envelope zoomExtent = new Envelope(mLocation, zoomWidth / 10, zoomWidth / 10);
                mMapView.setExtent(zoomExtent);
            }
        }

        @Override
        public void onProviderDisabled(String arg0) {
        }

        @Override
        public void onProviderEnabled(String arg0) {
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }
    });
    locDispMgr.start();
    mIsLocationTracking = true;
}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

/**
 * Start listening and recording locations
 *//*from  w w w  .  j av  a 2  s.c o  m*/
public void startRecording() {
    gpsTimer.cancel();
    gpsTimer = new Timer();
    long checkInterval = 60 * 1000;
    long minDistance = 1000;
    // receive updates
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    for (String s : locationManager.getAllProviders()) {
        locationManager.requestLocationUpdates(s, checkInterval, minDistance, new LocationListener() {

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

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onLocationChanged(Location location) {
                // if this is a gps location, we can use it
                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    doLocationUpdate(location, true);
                }
            }
        });
    }
    // start the gps receiver thread
    gpsTimer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Location location = getBestLocation();
            doLocationUpdate(location, false);
        }
    }, 0, checkInterval);
}

From source file:com.BeatYourRecord.SubmitActivity.java

private void getVideoLocation() {
    this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);/*w  ww .  jav a2s.  c o m*/
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);

    String provider = locationManager.getBestProvider(criteria, true);

    this.locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                SubmitActivity.this.videoLocation = location;
                lat = location.getLatitude();
                lng = location.getLongitude();
                Log.d(LOG_TAG, "lat=" + lat);
                Log.d(LOG_TAG, "lng=" + lng);

                TextView locationText = (TextView) findViewById(R.id.locationLabel);
                locationText.setText("Geo Location: " + String.format("lat=%.2f lng=%.2f", lat, lng));
                locationManager.removeUpdates(this);
            } else {
                Log.d(LOG_TAG, "location is null");
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    };

    if (provider != null) {
        locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
    }
}

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   w  w w .j a  v  a  2s . c om
    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;
}