In my application I am sending location update to server in each 5 minutes. For that I am using gms LocationListener
. This is working fine. I am running this inside a service. It won't work if the user turned off the GPS. since it is running it in service even after turning on the GPS it will wait for completing the 5 minutes of update time. So what I want is when the user turned on the GPS it should trigger the onLocationUpdate Listener.
For that I have did as follows I have initialised GpsStatus.Listener
in my service, and implemented it onStatusChange()
function, but after I change the GPS status from on to off/ off to on, the function is not triggering .
Code
public class LocationUpdateService extends Service implements GpsStatus.Listener, com.google.android.gms.location.LocationListener{
onCreate(Bundle b){
super.onCreate();
registerGpsStatusListener();
}
private void registerGpsStatusListener() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.addGpsStatusListener(this);
}
@Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_STARTED:
Log.e(TAG, "onGpsStatusChanged started");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.e(TAG, "onGpsStatusChanged stopped");
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.e(TAG, "onGpsStatusChanged first fix");
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.e(TAG, "onGpsStatusChanged status");
break;
}
}
@Override
public void onLocationChanged(Location location) {
//opertations
}
}
My queries are :
1- Why the method onGpsStatusChanged()
is not calling after changing the GPS status.
2- How do I get location inside onLocationChanged()
method, so that I can call onLocationUpdate()
method.
NOTE: Please do not recommend to use BroadcastReceiver
since it requires huge code modification of my current code.
I think you are trying to know when the user switches the GPS on or off from his device. In that case you can have a look at this answer.This is the only correct and reliable way to detect GPS on/off switch (at least it is the only one that worked for me).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With