在我的应用程序中,我每5分钟向服务器发送位置更新。为此,我使用gms
为此,我已经在我的服务中初始化了
LocationListener
。这很好用。我在服务内运行它。如果用户关闭了GPS,则它将无法工作。即使在打开GPS后仍在服务中运行,它也将等待完成5分钟的更新时间。因此,当用户打开GPS时,我希望它可以触发onLocationUpdate Listener。为此,我已经在我的服务中初始化了
GpsStatus.Listener
,并实现了onStatusChange()
函数,但是在我从打开到关闭/关闭到打开GPS状态之后,该函数没有触发。
代码:
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
}
}
我的问题如下:
1- 为什么改变GPS状态后,方法onGpsStatusChanged()
没有调用。
2- 如何在onLocationChanged()
方法中获取位置,以便我可以调用onLocationUpdate()
方法。
注意:请不要建议使用BroadcastReceiver
,因为它需要对我的当前代码进行大量修改。
LocationListener.isProviderEnabled()
。请参考这里的答案:https://dev59.com/hHXYa4cB1Zd3GeqP9rtP - panonski(Location location)
是你接收新位置的地方。然后你可以处理数据并执行像location.getLatitude()
等操作... - panonski