Utility Class to Fetch Current Location through GPS in Android – Java

Following is the utility class to fetch current location through GPS in Android. It also gives you frequent updates through the listener, when the device location is changed. In this class, Runtime Permissions are also handled for API level 23 and above. In Android, we have many ways to fetch a user’s current location. But the most accurate & precise way is to fetch location using LocationManager service provided by Android which is used in the following class.

Following is the Java solution if you are looking for Kotlin solution you can read this article How to Fetch Current Location through GPS in Kotlin Android.

LocationHelper class

package com.handy.opinion.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import androidx.core.app.ActivityCompat; // you can change it to appsupport if you are not using androidx
import androidx.core.content.ContextCompat;

import static android.content.Context.LOCATION_SERVICE;

public class LocationHelper {

    final int LOCATION_REFRESH_TIME = 3000; // 3 seconds. The Minimum Time to get location update
    final int LOCATION_REFRESH_DISTANCE = 30; // 30 meters. The Minimum Distance to be changed to get location update
    final int MY_PERMISSIONS_REQUEST_LOCATION = 100;

    Context context;
    MyLocationListener myLocationListener;

    public interface MyLocationListener {
        public void onLocationChanged(Location location);
    }

    public LocationHelper (Context context) {
        this.context = context;
    }

    public void startListeningUserLocation(final MyLocationListener myListener) {
        myLocationListener = myListener;

        LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);

        final LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                //your code here
                myLocationListener.onLocationChanged(location);
            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onProviderDisabled(String provider) {
            }
        };

        if (ContextCompat.checkSelfPermission( context,android.Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED &&  ContextCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED)
        {
         mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
                    LOCATION_REFRESH_DISTANCE, mLocationListener);
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                // permission is denined by user, you can show your alert dialog here to send user to App settings to enable permission
            } else {
                ActivityCompat.requestPermissions((Activity) context,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
        }
    }
}

How to use LocationHelper Class

You can call it from your Activity or Fragment using the following code.

LocationHelper locationHelper = new LocationHelper(context);
        locationHelper.startListeningUserLocation(new LocationHelper.MyLocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // Here you got user location :)
            }
        });

Don’t forget to add the following permissions into your AndroidManifest.xml file.

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

That’s it. Enjoy!! 🙂

You can also find other related Java articles & helping materials here.

Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

3 thoughts on “Utility Class to Fetch Current Location through GPS in Android – Java

  1. This is the appropriate blog for anyone who wants to search out out about this topic. You understand a lot its virtually exhausting to argue with you (not that I really would need…HaHa). You positively put a new spin on a subject thats been written about for years. Nice stuff, just great!

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.