0

I am trying to get current location using LocationManager class, but I am not getting any result in onLocationChanged method.

I am doing this in a fragment

 LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
 LocationListener locationListener = new myLocationListener();
 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0, locationListener);



private class myLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {

        Log.d(TAG, "Location Changed");
        Toast.makeText(getActivity(), location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_SHORT).show();

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}
Hirak Chhatbar
  • 3,159
  • 1
  • 27
  • 36
  • Are you receiving any errors? And do you have the permissions set? Also a link that may be helpful if you havent seen it yet. https://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android – Kalel Wade Mar 06 '15 at 18:13

2 Answers2

0

create a new class in your project, name it GPSTracker.java and copy content below in this:

Sorry unable to put its content here, so you have to search this class, you will get it from here then where you want current latitude and longitude, just use this code:

GPSTracker mTracker = new GPSTracker(MyActivity.this);

double lat=mTracker.getLatitude(); double lng=mTracker.getLongitude();

Rahul Sharma
  • 5,949
  • 5
  • 36
  • 46
0

First of all you have to add the android.permission.ACCESS_FINE_LOCATION permission in your AndroidManifest.xml file.

After that you can get last known location using next code:

Criteria criteria = new Criteria();
String provider = mLocationManager.getBestProvider(criteria, true);
Location location = mLocationManager.getLastKnownLocation(provider);

You can setup power and accuracy requirements in the Criteria. e.g:

criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);

If last known location was not enabled, or if you need continues updates of location you should setup location listener.

But code that you show in question should setup it correctly. So, probably you do not turn location on on the device, or you don't have permissions.

It is better to use instead of LocationManager.GPS_PROVIDER, Criteria with requirements, because sometimes GPS provider is disables, but you can obtain location using network.