Search code examples
androidlocation

How to get current location in android?


I am using the following code to get my current location, without GPS, but i want to show the co-ordinates in a toast. i have tried this code, but it shows my package name instead of co-ordinates!

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
          //makeUseOfNewLocation(location);
        }

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

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}

    };

    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    Toast.makeText(getBaseContext(), "location is:"+locationListener, Toast.LENGTH_LONG).show();
}

Solution

  • You only have the location in your onLocationChanged() callback.

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
    
         public void onLocationChanged(Location location) {
    
            // Called when a new location is found by the network location provider.
            Toast.makeText(getBaseContext(), "location is:"+location, Toast.LENGTH_LONG).show();
        }
    
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    
        public void onProviderEnabled(String provider) {}
    
        public void onProviderDisabled(String provider) {}
    };
    
    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);