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 OverflowHere 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.
android - Checking the location every 10 minutes in the background - Stack Overflow
android - Iam trying to get current location updates for every 5 minutes and send to server - Stack Overflow
android - How to get location after every 5 minutes? - Stack Overflow
android - Retrieving location every 5 seconds - Stack Overflow
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);
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
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);
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)
{
}
}
There is no any guarantee how often the location changes will come. And you can make it in two ways.
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
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
}
});
}
}
}
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.
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
To save power you can use/implement a function to detect when the user is stationary. You can for example define a user in stationary state when the location has not changed in more than 2 minutes (set this parameter so it does not fire too often, as when the user stops at a red light). When stationary states are detected, stop listen for location updates from the GPS and start listen for SIGNIFICANT_MOTION_SENSOR to detect active states. Be aware that not all models have this software sensor so you have to support situations when this is the case.
One good approach is to request location updates in batch like this. so you will be less frequently requesting for location updates:
LocationRequest request = new LocationRequest(); request.setInterval(10 * 60 * 1000); request.setMaxWaitTime(60 * 60 * 1000);In this case, location is computed roughly every ten minutes, and approximately six location data points are delivered in a batch approximately every hour. While you still get location updates every ten minutes or so, you conserve battery because your device is woken up only every hour or so. reference
Hi guys, I would like to play a kind of city-wide hide and seek or city-wide tag. For that it would be useful if my friends knew my location, but not all the time, only every few minutes they get my current location. Is there an app that does something like that? Thank you very much!