我正在开发一个位置应用程序,当用户按下Button
时,它应该开始基于经度和纬度来跟踪一些统计数据。所有这些东西都运行良好但是当涉及到锁定屏幕或将应用程序放在后台时,服务不再起作用了!
我已经阅读了很多关于后台服务和广播接收器的内容,但我不知道如何在服务中实现Google API位置监听器以及在MainActivity
中实现此类的位置。任何人都可以告诉我一个简短的代码示例如何实现这样的服务或链接解释这个?
答案 0 :(得分:3)
每次使用保险丝位置服务并保存更新的位置
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
进行操作答案 1 :(得分:0)
这是应用程序,可以执行您想要的操作:
https://github.com/sergstetsuk/CosyDVR/blob/master/src/es/esy/CosyDVR/CosyDVR.java
主要活动在BackgroundVideoRecorder服务上开始。
Intent intent = new Intent(/*CosyDVR.this*/getApplicationContext(), BackgroundVideoRecorder.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
查看mConnection onServiceConnected,onServiceDisconnected。
这是BackgroundVideoRecorder类:
https://github.com/sergstetsuk/CosyDVR/blob/master/src/es/esy/CosyDVR/BackgroundVideoRecorder.java
它实现了LocationListener。那么onLocationChanged,onProviderDisabled,onProviderEnabled,onStatusChanged。