How to get current GPS information from Android programmatically

Asked 1 years ago, Updated 1 years ago, 151 views

I want to get my current location information programmed using GPS. What should I do?

android location geolocation gps

2022-09-22 21:28

1 Answers

Let me introduce an example app that sequentially explains how to get the current location as a GPS coordinate value.

Full source code can be found at Get Current Location coordinates, City name - in Android .

Operating method:

The first thing to do is register the permissions below in the manifest file :

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Next, create an instance of LocationManager:

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

Make sure GPS is enabled.

Implement LocationListener to receive coordinates:

LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

Below is the sample code for LocationListener.

/*---------- Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        editLocation.setText("");
        pb.setVisibility(View.INVISIBLE);
        Toast.makeText(
                getBaseContext(),
                "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                    + + loc.getLongitude(), Toast.LENGTH_SHORT).show();
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);

        /*------- /*------- To get city name from coordinates -------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
            if (addresses.size() > 0) {
                System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getLocality();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
            + + cityName;
        editLocation.setText(s);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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


2022-09-22 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.