在Android上实现后台服务
问题描述:
我正在构建Android应用程序以跟踪用户在乘坐GPS期间的GPS定位(通过向服务器发送带有定位信息的事件),但到目前为止我有两个问题。由于用户可以暂停应用程序以在乘车过程中使用其他应用程序,因此应用程序将停止发送事件。为了解决这个问题,我实现了一个后台服务,即使在用户切换到另一个应用程序时也能继续运行,并因此不断向服务器发送事件。但是,无论何时手机关闭其屏幕(进入睡眠模式?),该服务似乎都会暂停。第二个问题是关于从手机获取GPS定位数据。我已经为应用程序提供了必要的权限,以便从GPS接收器获取数据,实际上,有时候,位置数据可以正确检索(同时还有其他应用程序使用GPS)。当没有其他应用程序使用GPS时,检索的定位是经度和纬度的元组(0.0,0.0)。我不清楚为什么这两个问题正在发生。为什么后台服务在屏幕关闭时会暂停,以及为什么只有当其他应用程序要求使用GPS时,GPS才会返回正确的定位?在Android上实现后台服务
答
我面临同样的问题(第一个问题)。我通过在服务中使用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);
}
}
}
}