我正在为Android开发一个应用程序来跟踪用户在乘车过程中的GPS定位(通过将带有定位信息的事件发送到服务器),但是到目前为止,我遇到了两个问题。由于用户可以挂起该应用程序以便在乘车期间使用其他应用程序,因此该应用程序将停止发送事件。为了解决这个问题,我实现了一个后台服务,即使用户切换到另一个应用程序,该后台服务也可以继续运行,并因此始终将事件发送到服务器。但是,无论何时手机关闭屏幕(进入睡眠模式?),该服务似乎都以某种方式被挂起。第二个问题是关于从手机获取GPS定位数据。我已经为应用程序设置了必要的权限,以便从GPS接收器获取数据,实际上,有时,正确检索了位置g(同时还有其他应用程序也在使用GPS)。如果没有其他应用程序使用GPS,则检索到的位置是经度和纬度的元组(0.0,0.0)。我不清楚这两个问题为什么会发生。为什么每当屏幕关闭时后台服务就会暂停,为什么GPS仅在有其他要求GPS使用的应用程序时才返回正确的位置?
我遇到了同样的问题(第一个问题)。我通过在服务内部使用Looper来解决它。对于第二个问题,我们必须看到一些代码来帮助您。另外,我将显示我的搜索位置代码,可能会有所帮助。我为此使用了GoogleApiClient https://developer.android.com/training/location/retrieve-current.html
public class LocationService extends Service implements com.google.android.gms.location.LocationListener {
private Thread mTriggerService;
private Handler mLooperHandler;
...
private void addLocationListener(){
// Start thread which listen location
mTriggerService = new Thread(new Runnable(){
public void run(){
try{
Looper.prepare();//Initialise the current thread as a looper.
mLooperHandler = new Handler();
initLocationManager();
Looper.loop();
}catch(Exception ex){
ex.printStackTrace();
}
}
}, "LocationThread");
mTriggerService.start();
}
/**
* Strart listening location
*/
public void initLocationManager(Context context) {
...
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(mInterval);
//This controls the fastest rate at which your application will receive location
//updates, which might be faster than setInterval(long) in some situations
//(for example, if other applications are triggering location updates).(from doc)
mLocationRequest.setFastestInterval(mFastestInterval);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended");
}
})
.addOnConnectionFailedListener(mOnConnectionFailedListener)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
//stop listening location
private void stopLocationListener() {
if(mLocationHelper != null){
mLooperHandler.getLooper().quit();
if(mGoogleApiClient != null && mLocationListener != null
&& mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句