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 OverflowUse 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);
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
Videos
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.
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.
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;
}
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
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) {
}
}
}
use This:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//your code to get lat long
}
}, 0, 500000);