Android Location Listener call very often - android

I am using Network Location provider.
I need to call onLocationChanged method from my LocationListener only once per 1 hour.
Here is my code:
MyLocationListener locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3600000, 0,locationListener);
But it doesn't work. My onLocationChanged calling very often.
What parameters must I use?

From the LocationManager#requestLocationUpdates() documentation:
Prior to Jellybean, the minTime parameter was only a hint, and some location provider implementations ignored it. From Jellybean and onwards it is mandatory for Android compatible devices to observe both the minTime and minDistance parameters.
However you can use requestSingleUpdate() with a Looper and Handler to run the updates once an hour.
Addition
To start you can read more about Loopers and Handlers here.
You are using API 8 which is a good choice, but this limits which LocationManager methods we can call since most were introduced in API 9. API 8 only have these three methods:
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)
Let's use the first method, it is the simplest.
First, create your LocationManager and LocationListener as you normally would, but in onLocationChanged() stop requesting more updates:
#Override
public void onLocationChanged(Location location) {
mLocationManager.removeUpdates(mLocationListener);
// Use this one location however you please
}
Second, create a couple new class variables:
private Handler mHandler = new Handler();
private Runnable onRequestLocation = new Runnable() {
#Override
public void run() {
// Ask for a location
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
// Run this again in an hour
mHandler.postDelayed(onRequestLocation, DateUtils.HOUR_IN_MILLIS);
}
};
Of course, you ought to disable all of your callbacks in onPause() and enable them again in onResume() to prevent the LocationManager from wasting resources by acquiring unused updates in the background.
A more technical point:
If you are concerned about blocking the UI thread with the LocationManager, then you can use the second requestLocationUpdates() method to supply a specific Looper from a new Thread (say a HandlerThread).

Related

Android location update every minute

I am currently writing an application that receives location data every minute (or other specified amount of time) and thes send it to server.
The problem that I have noticed is:
When I use my application connected to power source it works perfectly - sends updates with defined interval.
When I use it on battery it sends updates randomly.
For my application I use timer to specify interval of update. This timer runs in Background service. I request updates in timer and remove updates when I receive location.
Fragment of my code:
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
date = date.getInstance(); //used to set time of update.
if(!GPSupdating)
{
locationManager.requestLocationUpdates("gps", 0, 0, locationListenerGPS);
GPSupdating = true;
}
}
};
My location listener:
LocationListener locationListenerGPS = new LocationListener()
{
public void onLocationChanged(Location updatedLocation)
{
myGPSLocation = updatedLocation;
haveLocationGPS = true;
locationManager.removeUpdates(locationListenerGPS);
GPSupdating = false;
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
Do you have any idea why this is not working correctly?
It's not good solution - enable/disable listener on each minute.
Better to try following things:
1) Set minimal update time (in requestLocationUpdates ) to one minute and send data to server in update listener:
locationManager.requestLocationUpdates("gps", 60*1000, 0, locationListenerGPS);
If you need more accurate update intervals, than:
2) Start separate thread and enable GPS updates on it. Store last location in thread or service variable. Also start timer and on timer tick send location to the server.
Try using Criteria to manage the power. Set power requirement to POWER_LOW. You will loose some accuracy though.
LocationManager locationManager= (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
You will not save energy by enabling and disabling GPS once per minute. Either choose a greater intervall (5 minute) or get the location evry second.
Then store the location in a lastValidLocation filed, start your own Timer, and once a minute read out lastValidLocation. and send to server if changed.

Android- same GPS location repeating without updating

I have tried to do my research about GPS issues before posting here. When I tested my code It repeats the same output over and over. The method gpsStart() is called on a timer. Fine and Coarse location permissions have been added to the manifest. The method appendLog() stores the output in a file.
public void gpsStart() {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Toast.makeText(getApplicationContext(), "location changed",
// Toast.LENGTH_SHORT).show();
// Called when a new location is found by the network location
// provider.
appendLog("Lat: " + location.getLatitude() + "\nLng: "
+ location.getLongitude()+"\n");
text3.setText("Lat: " + location.getLatitude() + "\nLng: "
+ location.getLongitude());
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location
// updates
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
You must not call gpsStart() method in the timer. I am going to say how Location Listener works
What is Location Listener?
Location Listener is the class which notify you when your current location will be change. For receive the location updates you will have to register LocationListener class using LocationManager class.
When to register Location Listener?
It depends on the requirement of your application. For example if you want location listener for display current location on map then you should register Location Listener in onCreate() or onResume() method of the activity and unregister receiver in onPause() or onStop() method. If you want to receive the location even if your application is not running then you can use a service to receive location.
How to Register/Unregister Location Listener?
To register the LocationListener you first need the instance of the LocationManager class which you can get using the context like
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
After then you will have to set the location provider. There are 2 types of providers which are often used.
GPS provider
Network Provider
Now to register the location receiver with this location provider there is a method requestLocationUpdates of LocationManager. In this method first argument is the provider name second argument is the minimum time for request location update. Third argument is the minimum distance to request for the location change.Last argument is for locationListener.
Here how you can use the method
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, minTime, minDistance, locationListener);
To unRegister location updates you can use the below method
locationManager.removeUpdates(locationListener)
Note: You are calling a method gpsStart in the timer as you have mentioned in your question so it is adding location listener each time when this method calls.So all the listeners are triggering you the new location so probably you are getting same location multiple times. Instead of it, you should call this method once when your activity starts and unRegister this locationListener when your activity finish.
Hopes you are getting. :D
Enjoy!!!
Better you create a 2 listeners.1 for Gps and other for network.
the following are code samples
public class MyLocationListener extends LocationListener
{
public void onLocationChanged(Location location)
{
// Toast.makeText(getApplicationContext(), "location changed",
// Toast.LENGTH_SHORT).show();
// Called when a new location is found by the network location
// provider.
appendLog("Lat: " + location.getLatitude() + "\nLng: "
+ location.getLongitude()+"\n");
text3.setText("Lat: " + location.getLatitude() + "\nLng: "
+ location.getLongitude());
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
}
MyLocationListener gpsListener=new MyLocationListener();
MyLocationListener networkListener=new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpslocationListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networklocationListener);
Thank you very much for your answers. Dharmendra you are correct, I did need to close the LocationListeners, however the answer to my question was much simpler. I needed to change the minimum time (the time the listener waits to get an answer) to a value above zero. The value I needed to change is shown in bold below (MINTIME).
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINTIME, 0, gpslocationListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINTIME, 0, networklocationListener);

used requestLocationUpdates() but not getting consistent updates

I am trying to get a periodic update on location at a fixed interval. Right now, I am testing with a 2 minute interval just to make sure things are working. Then I will push it to a much longer interval.
Here is the relevant code:
public final int LOCATION_TIMER_RATE=120000;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d("BLAH", "Recorded home location as: (" + location.getLatitude() + "," + location.getLongitude() + ")");
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_TIMER_RATE, 0, locationListener);
If I request a single update, as follows, I always get a response back within 20 seconds or so. But, after that, I still do not get my periodic updates:
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, null);
If you request a single update, do you need to reschedule your periodic updates?
If you request a single update, then yes, you'd have to reschedule it for future updates. As for the requesting period updates not being consistent, it says so in the documentation. The updates can take longer (or possibly even shorter) than the time period you select.

disable GPS signal during location update

I am making location tracker application in android so I call a function
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
30000,
0,
listener);
So in this example i set 5minute interval.
Now my question is why GPS signal is constantly activate, though my interval time is 5minute..
Can't is deactivate till 5 minute and after 5 minute can't it automatically activate??
I thing device require more battery power though it constant active...
What I have to do to deactivate GPS for particular interval defined in function.
No you can't but you can always run a service that asks for a single shot fix every five minutes.
For e/g use requestSingleUpdate (String provider, PendingIntent intent)
To broadcast an intent when a single shot fix is obtained.
I had exactly the same problem with my app. I used a timer initialized on startup:
serviceHandler = new Handler();
serviceHandler.postDelayed( new RunTask(),1000L );
This runs locupdate and adds one to counter every second.
class RunTask implements Runnable {
public void run() {
++counter;
locupdate(0,0);
serviceHandler.postDelayed( this, 1000L );
}
}
this is the locupdate function used above. Note, mlocManager is defined globaly as a LocationManager.
public void locupdate(int minTime, float minDistance) {
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
if (mlocListener != null && mlocManager != null) {
mlocManager.removeUpdates(mlocListener);
}
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
minTime, minDistance, mlocListener);
}
One last thing. At the end of the onLocationChanged method in LocationListener I remove updates after 5 locations fixes:
mlocManager.removeUpdates(mlocListener);
This is similar to requestSingleUpdate() but i find it more flexible. Hope this helps!
Basically this function takes time interval as follows,
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, listener);
the meaning over here is that give me GPS update if you found within the given time with no
other priority tasks.
so this is you method
public void requestLocationUpdates (long minTime, float minDistance, Criteria criteria, PendingIntent intent)
& these are the parameters, please read it carefully you can understand it
Parameters
minTime = the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
minDistance = the minimum distance interval for notifications, in meters criteria contains parameters for the location manager to choose the appropriate provider and parameters to compute the location
intent = a {#link PendingIntent} to be sent for each location update
That is all about
Best Regards,
~Anup

Android: How to keep GPS active until more accurate location is provided?

I am using the location manager's requestLocationUpdates() method to receive an intent to my broadcast receiver periodically. The system is correctly firing the intent to my receiver, and I have been able to use it correctly. The only problem is that the GPS location provider only stays active for a few seconds after the initial location acquisition, and I need it to stay on a little longer so that the location estimates are more accurate.
My question is how to make the GPS location provider stay active for each periodic request that comes from the LocationManager requestLocationUpdates. Does anyone know how to do this?
Try something like this. I think it is the right approach
private void createGpsListner()
{
gpsListener = new LocationListener(){
public void onLocationChanged(Location location)
{
curLocation = location;
// check if locations has accuracy data
if(curLocation.hasAccuracy())
{
// Accuracy is in rage of 20 meters, stop listening we have a fix
if(curLocation.getAccuracy() < 20)
{
stopGpsListner();
}
}
}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status, Bundle extras){}
};
}
private void startGpsListener()
{
if(myLocationManager != null)
// hit location update in intervals of 5sec and after 10meters offset
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, gpsListener);
}
private void stopGpsListner()
{
if(myLocationManager != null)
myLocationManager.removeUpdates(gpsListener);
}
if you keep your LocationListener active, it should continue to receive updates to onLocationChanged() if the fix accuracy narrows. and indeed location.getAccuracy() will tell you the current accuracy
maybe set minTime and minDistance both to 0 to receive updates with greater frequency? will use more battery, but is more preise.
There is a example about get GPS location with timeout.
http://sikazi.blogspot.com/2010/09/android-gps-timeout.html#more
To get GPS location periodically, get the location from onLocationChanged method of locationListener and in onResume method specify the timing in milliseconds for getting periodic updates
onResume
location_manager.requestLocationUpdates(provider, 1000, 1, MainActivity.this);

Categories

Resources