Here is the code for getting location and set the listener for gps to get current location on few minute and distance, also I have used runnable object to get the location on every few minutes.

Location gpslocation = null;

private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
private static final int GPS_DISTANCE= 1000; // set the distance value in meter

/*
   for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
*/

private void obtainLocation(){
if(locMan==null)
    locMan = (LocationManager) getSystemService(LOCATION_SERVICE);

    if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(isLocationListener){
             locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
                        GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
                }
            }
        }
}

Now use this method to get the current location and the listener was called on location change with every 1 min and 1000 meter of distance.

For getting every 5 min you can use this handler and runnable to get this location on well set period time:

private static final int HANDLER_DELAY = 1000*60*5;

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
        public void run() {
            myLocation = obtainLocation();
            handler.postDelayed(this, HANDLER_DELAY);
        }
    }, START_HANDLER_DELAY);

Here is GPS listener for location change event:

private LocationListener GPSListener = new LocationListener(){
    public void onLocationChanged(Location location) {
        // update location
        locMan.removeUpdates(GPSListener); // remove this listener
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

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

You can set interval time for listener and handler same for getting GPS location.

Answer from Pratik on Stack Overflow
Top answer
1 of 4
13

Here is the code for getting location and set the listener for gps to get current location on few minute and distance, also I have used runnable object to get the location on every few minutes.

Location gpslocation = null;

private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
private static final int GPS_DISTANCE= 1000; // set the distance value in meter

/*
   for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
*/

private void obtainLocation(){
if(locMan==null)
    locMan = (LocationManager) getSystemService(LOCATION_SERVICE);

    if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(isLocationListener){
             locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
                        GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
                }
            }
        }
}

Now use this method to get the current location and the listener was called on location change with every 1 min and 1000 meter of distance.

For getting every 5 min you can use this handler and runnable to get this location on well set period time:

private static final int HANDLER_DELAY = 1000*60*5;

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
        public void run() {
            myLocation = obtainLocation();
            handler.postDelayed(this, HANDLER_DELAY);
        }
    }, START_HANDLER_DELAY);

Here is GPS listener for location change event:

private LocationListener GPSListener = new LocationListener(){
    public void onLocationChanged(Location location) {
        // update location
        locMan.removeUpdates(GPSListener); // remove this listener
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

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

You can set interval time for listener and handler same for getting GPS location.

2 of 4
2

Hi Use the below timer code.

You can use the below options option 1 this will get the locations if mobile moved 100meters.

    captureFrequencey=3*60*1000;   
LocationMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, captureFrequencey, 100, this);

have a look at this link http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29

Option 2

   TimerTask refresher;
        // Initialization code in onCreate or similar:
        timer = new Timer();    
        refresher = new TimerTask() {
            public void run() {
              handler.sendEmptyMessage(0);
            };
        };
        // first event immediately,  following after 1 seconds each
        timer.scheduleAtFixedRate(refresher, 0,1000); 
        //=======================================================


final Handler handler = new Handler() {


        public void handleMessage(Message msg) {
              switch (msg.what) {
              case REFRESH: 
                  //your code here 

                  break;
              default:
                  break;
              }
          }
        };

Timer will call the handler for your time duration (change 1000 into your required time ).

Hope this will help you.

๐ŸŒ
YouTube
youtube.com โ€บ the code city
Android Get Current Location Every 5 Minutes - Tutorial & Source Code - YouTube
In this tutorial we'll learn how we can get location using GPS every 5 minutes. You can use it to get the location every 1 minute or any other interval as yo...
Published ย  January 6, 2022
Views ย  14K
Discussions

android - Checking the location every 10 minutes in the background - Stack Overflow
My requirement is to check the location of the device every 10 minutes using a background service. So the basic gist of what should happen every 10 minutes is this - Start the service. Wait a minu... More on stackoverflow.com
๐ŸŒ stackoverflow.com
android - Iam trying to get current location updates for every 5 minutes and send to server - Stack Overflow
Iam trying to get current location updates for every 5 minutes and send to server but I am getting it in the foreground but I am not getting it on the background I used Alarm Manager More on stackoverflow.com
๐ŸŒ stackoverflow.com
android - How to get location after every 5 minutes? - Stack Overflow
I am using this link for location service and it works Now I want to create BackgroundService that make calls to a function that gets location after every 5 minutes. I think I need to use Timer fo... More on stackoverflow.com
๐ŸŒ stackoverflow.com
android - Retrieving location every 5 seconds - Stack Overflow
Hi I am creating a project. It is about tracking a driver. The driver must send his location every 5 seconds to the Firebase. My problem is how do the passenger retrieve the location of the driver ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 3
4

Use a alarm service to trigger location service which will inturn save location in database table

Copypublic static void setAlarmTimely(Context context) {
    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(IntentConstants.ALARM_INTENT, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK);
    alarmIntent = PendingIntent
            .getBroadcast(context, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK, intent, 0);
    alarmMgr.cancel(alarmIntent);

    Calendar calendar = Calendar.getInstance();
    LOGD(TAG, time + " ");
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + locationCaptureTime * 60 * 1000,
            5 * 60 * 1000, alarmIntent);
}

on button click cancel the alarm

CopyAlarmManager alarmMgr;
    PendingIntent alarmIntent;
    LOGD(TAG, "cancelling location update");
    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(IntentConstants.ALARM_INTENT, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK);
    alarmIntent = PendingIntent
            .getBroadcast(context, IntentConstants.INTENT_REQUEST_CODE_LOCATION_TRACK, intent, 0);
    alarmMgr.cancel(alarmIntent);
2 of 3
0

You can do that with LocationManager, you need to set time interval.

example

CopyLocationManager = new LocationManager();
 locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Parameters

provider String: the name of the provider with which to register

minTime long: minimum time interval between location updates, in milliseconds

minDistance float: minimum distance between location updates, in meters

listener LocationListener: a LocationListener whose

onLocationChanged(Location) method will be called for each location update

you can read more on this page LocationManager

Top answer
1 of 3
2

Instead of alarm manager which is scheduling each 10 min, use the FusedLocationAPI and location request in order to get accurate location.

            LocationRequest mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);//Change to PRIORITY_HIGH_ACCURACY for more accurate.
            mLocationRequest.setInterval(600000); // Update location every 10 minute
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);

Call this method whenever you need the location

/**
 * Get the Location Detail from Fused Location API.
 * @param mContext
 * @return
 */
private Location getLocationDetails(Context mContext) {
    Location location = null;
    if (mGoogleApiClient != null) {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG,"Location Permission Denied");
            return null;
        }else {
            location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
    }
    return location;
}
2 of 3
0

try with this

// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10; // 10 minute

for more info example try with this

Try with this link click here

๐ŸŒ
YouTube
youtube.com โ€บ watch
Android Get Current Location Continuously | Location Service | Fused Location Provider API - YouTube
Android Get Current Location Continuously | Location Service | Fused Location Provider APIIn this tutorial, we will implement a foreground location service w...
Published ย  May 20, 2020
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70708329 โ€บ iam-trying-to-get-current-location-updates-for-every-5-minutes-and-send-to-serve
android - Iam trying to get current location updates for every 5 minutes and send to server - Stack Overflow
mLocationRequest = LocationRequest.create(); mLocationRequest.setInterval(60*1000); mLocationRequest.setFastestInterval(10*1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); if (mLocationCallback == null) mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult == null) { return; } for (Location location : locationResult.getLocations()) { if (location != null) { if(BuildConfig.DEBUG) mLastLocation = location; } } } }; fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MasterApplica tion.getInstance().getApplicationContext()); fusedLocationProviderClient.requestLocationUpdates(mLocationR equest, mLocationCallback, Looper.getMainLooper());
Top answer
1 of 2
1
public class LocationService extends Service {      
    private Timer timer; 
    private  long UPDATE_INTERVAL ;
    public static final String Stub = null;
    LocationManager mlocmag;
    LocationListener mlocList ;
    private double lat,longn;

    @Override
    public void onCreate() {
        super.onCreate();
        webService = new WebService();
         mlocmag = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         mlocList = new MyLocationList();

        Location loc = mlocmag.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (loc == null) {
            loc = mlocmag.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        timer  = new Timer();       // location.
        UpdateWithNewLocation(loc); // This method is used to get updated
        mlocmag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocList);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        mlocmag.removeUpdates(mlocList);
    }

    @Override
    public boolean stopService(Intent name) {
        return super.stopService(name);
    }

    private void UpdateWithNewLocation(final Location loc) {
        final SharedPreferences prefs = getSharedPreferences(Const.COMMON_SHARED, Context.MODE_PRIVATE);
        userId = prefs.getString(Const.COMMON_USERID, null);
        gps = prefs.getInt(Const.COMMON_GPS, 0);

        UPDATE_INTERVAL = 500000;

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
        if (loc != null) {
            final double latitude = loc.getLatitude(); // Updated lat
            final double longitude = loc.getLongitude(); // Updated long

            String response = null ;
                if (lat != latitude || longn != longitude ) {

                    response = webService.updateLatandLong(userId, latitude, longitude);
                    lat = latitude;
                    longn = longitude;

                }
        }

        else {
            String latLongStr = "No lat and longitude found";
        }

    }
        }, 0, UPDATE_INTERVAL);
    }


    public class MyLocationList implements LocationListener {

        public void onLocationChanged(Location arg0) {
            UpdateWithNewLocation(arg0);
        }

        public void onProviderDisabled(String provider) {
            Toast.makeText(getApplicationContext(), "GPS Disable ",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String provider) {
            Toast.makeText(getApplicationContext(), "GPS enabled",
                    Toast.LENGTH_LONG).show();
        }

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

        }

    }
}
2 of 2
0

use This:

Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
//your code to get lat long

                    }
                }, 0, 500000);
Find elsewhere
๐ŸŒ
Comexplus
comexplus.com โ€บ unraid-c0284001-blackhawk โ€บ android-get-current-location-every-5-minutes.html
Android get current location every 5 minutes
If a user is a driver, their current ... practices for retrieving location updates. So if you want to get a new location every 1 minute, just ask it on a repeating basis....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 39014217 โ€บ get-current-location-every-n-minutes-in-android
java - Get current location every n minutes in android - Stack Overflow
August 18, 2016 - Timer timer = new Timer (); TimerTask hourlyTask = new TimerTask () { @Override public void run () { // check if GPS enabled GPSTracker gpsTracker = new GPSTracker(this); if (gpsTracker.getIsGPSTrackingEnabled()){ String stringLatitude = String.valueOf(gpsTracker.latitude); String stringLongitude = String.valueOf(gpsTracker.longitude); } } }; // schedule the task to RUN every hour timer.schedule (hourlyTask, 0l, 1000*60*60); // 1000*10*60 every 10 minut
Top answer
1 of 2
3

First of all see this link which says to use a Handler to request one update with requestSingleUpdate() every 5 minutes.

Here is an example for the onLocationChanged()...

inside onCreate()

mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();                             
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

MyLocationListener class

public class MyLocationListener implements LocationListener
{

    @Override
    public void onLocationChanged(Location location)
    {                         

          //Set marker here
          LatLng pos=new LatLng(location.getLatitude(), location.getLongitude());
           map.addMarker(new MarkerOptions().position(pos).icon(BitmapDescriptorFactory.fromResource(markericon)));

    }

    @Override
    public void onProviderDisabled(String provider)
    {

    }

    @Override
    public void onProviderEnabled(String provider)
    {

    }

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

    }                
}
2 of 2
0

There is no any guarantee how often the location changes will come. And you can make it in two ways.

  1. You do not need to read the location every X seconds. Just save the last location from onLocationChanged() and use it on your timer ticks. You can also check if this location is different from the last used, if this matters

  2. The other way is to use LocationClient and its method getLastLocation(). You can use getLastLocation() in any time (after proper initialization), like every 5 sec.

Something like this:

timer.scheduleAtFixedRate( new UpdateLocationTask(), 1000, 5000 );

class UpdateLocationTask extends TimerTask
{
   public void run()
      {
      final Location location = mLocationClient.getLastLocation();
      if ( location != null )
         {
         runOnUiThread( new Runnable()
            {
            public void run()
               {
               // do whatever you want here
               }
            });
         }
      }
}
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 32521286 โ€บ optimize-the-operation-of-retrieving-users-location-periodically-android
Optimize the operation of retrieving user's location periodically android - Stack Overflow
If your user stays on app and you ... is outside the app and you need to get the location, just use a Service and keep fetching location by making it wait 5 minutes....
Top answer
1 of 2
5

Start your app service in background to get timely location updates.

public class MYService extends Service implements LocationListener {

}

and do async task on timely to get periodic location updates.

TimerTask doAsynchronousTask = new TimerTask() {
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {

            }
        });
    }
};

//Starts after 20 sec and will repeat on every 20 sec of time interval.
timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer

it will give location updates on every 20 SEC.

2 of 2
3

Try this code. make an interface GetLocation

public interface GetLocation {
    public void onLocationChanged(Location location);
    public void onStatusChanged(String s, int i, Bundle bundle);
    public void onProviderEnabled(String s);
    public void onProviderDisabled(String s);
}

then make a class CurrentLocation and implements LocationListener

public class CurrentLocation implements LocationListener {

    Context context;
    LocationManager locationManager;
    String provider;

    GetLocation getLocation;

    public CurrentLocation(Context context) {

        this.context = context;
        getLocation = (GetLocation) context;
        location();
    }

    public void location() {
        // Getting LocationManager object
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        // anruag getting last location
      //  Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        // Creating an empty criteria object
        Criteria criteria = new Criteria();

        // Getting the name of the provider that meets the criteria
        provider = locationManager.getBestProvider(criteria, false);

        if (provider != null && !provider.equals(" ")) {

            // Get the location from the given provider
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            Location location = locationManager.getLastKnownLocation(provider);

            locationManager.requestLocationUpdates(provider, 20000, 1, this);

            if (location != null)
                onLocationChanged(location);
            else {

            }
                // Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(context, "No Provider Found", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        // Log.e("Location", location.getProvider() + "==" + location.getAccuracy() + "==" + location.getAltitude() + "==" + location.getLatitude() + "==" + location.getLongitude());
        getLocation.onLocationChanged(location);
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude());

        ConstantValues.UPlat = String.valueOf(location.getLatitude());
        ConstantValues.UPlng = String.valueOf(location.getLongitude());

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        Log.e("onStatusChanged", "==" + s);
        getLocation.onStatusChanged(s, i, bundle);
    }

    @Override
    public void onProviderEnabled(String s) {
        Log.e("onProviderEnabled", "==" + s);
        getLocation.onProviderEnabled(s);
    }

    @Override
    public void onProviderDisabled(String s) {
        Log.e("onProviderDisabled", "==" + s);
        getLocation.onProviderDisabled(s);
        // alertbox("GPS STATUS", "Your GPS is: OFF");
        // Toast.makeText(context, "Please turn on the GPS to get current location.", Toast.LENGTH_SHORT).show();

        try {

            ConstantValues.showDialogOK("Please turn on the GPS to get current location.", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    switch (i) {
                        case DialogInterface.BUTTON_POSITIVE:
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            context.startActivity(myIntent);
                            dialogInterface.dismiss();
                            break;
                        case DialogInterface.BUTTON_NEGATIVE:
                            dialogInterface.dismiss();
                            break;
                    }
                }
            }, context);
        } catch (Exception e) {
            Log.e("exception", e.toString()+"==");
        }

    }

}

call this class in any Activity where you want to get the current location

CurrentLocation currentLocation;

declare these two global variables for minimum distance change and time interval

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
    // Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; 

make its object in onCreate

currentLocation = new CurrentLocation(this);

make a method

public void locationWithPermission() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (checkAndRequestPermissions()) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    MINIMUM_TIME_BETWEEN_UPDATES,
                    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new CurrentLocation(this));

        }
    }

and call this method in your Activity on any event you want to get Location

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 47998844 โ€บ is-there-a-way-to-get-the-location-every-x-minutes-even-when-there-are-no-chang
android - Is there a way to get the location every x minutes, even when there are no changes? - Stack Overflow
I am using Android Studio. I use locationManager.requestLocationUpdates(...) to get the location. ... //print location every 5 minutes 12:10am lat=10.23652 long=21.25441 12:15am lat=10.23652 long=21.25441 12:20am lat=15.21456 long=58.21452 12:25am ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 39093866 โ€บ get-current-position-of-a-mobile-every-2-minutes-android
Get current position of a mobile every 2 minutes android - Stack Overflow
August 23, 2016 - This sample might use the necessity for this but fused location provider use three modes gps,wifi and network provider so you get location in regular interval.you can get the location without it but for better results you must use gps. โ€“ Mohit Dixit Aug 23 '16 at 7:04 ยท Thank you I will try and get back โ€“ Philomath Aug 23 '16 at 7:05 ... public void StartAlaramServiceforDataService(){ Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 1); Intent intentToQB = new Intent(SendLatlong.this, LocationFetchService.class