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);
Answer from Tushar Saha on Stack Overflow
🌐
GitHub
github.com › topics › current-location
current-location · GitHub Topics · GitHub
Location services using FusedLocation Api and handle location updates as a LiveData using Android architecture components and Jetpack libraries.
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

🌐
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
🌐
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 - Don't use Async task like this for getting location in every 2 minutes there is perfect solution that is "Fused Location Provider". it gives us device location on a regular interval you can set it for 2 minutes tale a look on this https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates
🌐
GitHub
github.com › TommyR22 › Android-getcurrentlocation
GitHub - TommyR22/Android-getcurrentlocation: Example to get current location in Android with google maps api v2 and GPS
Example to get current location in Android with google maps api v2 and GPS - TommyR22/Android-getcurrentlocation
Starred by 3 users
Forked by 5 users
Languages   Java 100.0% | Java 100.0%
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.

🌐
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
🌐
GitHub
gist.github.com › quynguyen3490 › 854d09996522d8e629d3
Get Current Location Android · GitHub
Get Current Location Android. GitHub Gist: instantly share code, notes, and snippets.
Find elsewhere
🌐
GitHub
github.com › Akashmathwani › Get-Current-Location-Android
GitHub - Akashmathwani/Get-Current-Location-Android: get Current latitude and Longitude in android studio code.
get Current latitude and Longitude in android studio code. - Akashmathwani/Get-Current-Location-Android
Starred by 5 users
Forked by 3 users
Languages   Java 100.0% | Java 100.0%
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

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);
🌐
GitHub
github.com › dinkar1708-zz › LocationTrackerAndroid
GitHub - dinkar1708-zz/LocationTrackerAndroid: Get current location in background service using location service in android
Get current location in background service using location service in android - dinkar1708-zz/LocationTrackerAndroid
Starred by 45 users
Forked by 23 users
Languages   Java 99.0% | Kotlin 1.0% | Java 99.0% | Kotlin 1.0%
🌐
GitHub
github.com › prabhat1707 › EasyWayLocation
GitHub - prabhat1707/EasyWayLocation: This library contain all utils related to google location. like, getting lat or long, Address and Location Setting dialog, many more...
@Override public void locationOn() { Toast.makeText(this, "Location ON", Toast.LENGTH_SHORT).show(); } @Override public void currentLocation(Location location){ // give lat and long at every interval } @Override public void locationCancelled() ...
Starred by 166 users
Forked by 51 users
Languages   Java 51.5% | Kotlin 48.5% | Java 51.5% | Kotlin 48.5%
🌐
GitHub
github.com › farooqkhan003 › android-current-location
GitHub - farooqkhan003/android-current-location: Android App getting current Location using Google Fused Api.
Android App for getting current Location using Google Fused Api. And if no previous data for location is available, it gets the current location. Here you can see the Demo Video.
Starred by 13 users
Forked by 11 users
Languages   Java 100.0% | Java 100.0%
🌐
GitHub
github.com › hmkcode › Android › tree › master › android-get-current-location
Android/android-get-current-location at master · hmkcode/Android
Android related examples. Contribute to hmkcode/Android development by creating an account on GitHub.
Author   hmkcode
🌐
GitHub
gist.github.com › yudikarma › fff2ea8aa0e6c2946f56b8e44c6f610b
how to get current location android gps and network provider · GitHub
how to get current location android gps and network provider - get location android GPS and Network Provider
🌐
GitHub
github.com › codepath › android_guides › issues › 220
A good example of background service getting location updates · Issue #220 · codepath/android_guides
September 29, 2016 - I'm facing a problem here. It is impossible to find A GOOD EXAMPLE of how create a service that must run in background and receive location updates. Also, all examples on developer.android.com are terrible, any one of them really works.
Author   codepath
🌐
GitHub
github.com › topics › location-tracker
location-tracker · GitHub Topics · GitHub
Application developed for the University course "Embedded Systems Programming". The app retrieves the location of the device in real time and shows it to the user. Furthermore, the app shows the path of the user in the last 5 minutes.
🌐
GitHub
github.com › yayaa › LocationManager
GitHub - yayaa/LocationManager: Simplify getting user's location for Android · GitHub
But till now, all depends on GooglePlayServices what happens if user's device doesn't have GooglePlayServices, or user didn't want to handle GooglePlayServices issue or user did everything and waited long enough but somehow GooglePlayServices weren't able to return any location. What now? Surely we still have good old times GPS and Network Providers, right? Let's switch to them and see what we need to do! ... All of these steps, just to retrieve user's current location.
Starred by 805 users
Forked by 186 users
Languages   Java