我正在开发一个 Location-App,当用户按下 Button
时,它应该开始根据经度和纬度跟踪一些统计数据。所有这些东西都很好用,但是当涉及到锁定屏幕或将应用程序置于后台时,该服务不再工作了!
我已经阅读了很多关于后台服务和广播接收器的内容,但我不知道如何在服务中实现 Google API 位置监听器以及在 MainActivity
中的何处实现此类。任何人都可以用一个简短的代码示例告诉我如何实现这样的服务或解释这个的链接吗?
最佳答案
使用 fuse 定位服务并每次保存更新的位置
public class LocationNotifyService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public static Location mCurrentLocation;
.............................
@Override
public void onCreate() {
//show error dialog if GoolglePlayServices not available
if (isGooglePlayServicesAvailable()) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(BACKGROUND_INTERVAL);
mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//mLocationRequest.setSmallestDisplacement(10.0f); /* min dist for location change, here it is 10 meter */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
//Check Google play is available or not
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
return ConnectionResult.SUCCESS == status;
}
@Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
try {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} catch (IllegalStateException e) {}
}
@Override
public void onLocationChanged(Location location) {
//Save your location
}
............................
}
你可以获取当前位置 onLocationChanged()
更多详情请查看http://javapapers.com/android/android-location-fused-provider/或按照官方指南https://developer.android.com/training/location/index.html
关于Android 定位服务无法在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34918675/