即使关闭后,我也希望跟踪与strava非常相似的用户位置。
我尝试过AlarmManager,但每隔一分钟就没有给我执行
答案 0 :(得分:3)
如果设备进入睡眠模式,仅使用服务作为BiGGZ解释将无法工作。该服务不会被杀死,但您的应用程序将不会获得任何CPU。因此,您必须获取部分Wakelock以防止设备进入睡眠模式。
Q
如果您需要较少的位置更新,您可以使用AlarmManager并设置重复警报,触发位置更新。警报应该触发BroadcastReceiver,因为在设备再次进入休眠状态之前无法保证服务成功启动。见这里:https://developer.android.com/reference/android/app/AlarmManager.html
答案 1 :(得分:2)
使用服务:
public class UpdateLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private final static int UPDATE_INTERVAL = 300000;//whatever you want
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public UpdateLocationService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(UpdateLocationService.this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
try{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, UpdateLocationService.this);
Toast.makeText(UpdateLocationService.this, "onConnected", Toast.LENGTH_SHORT).show();
}catch(SecurityException e){
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
Toast.makeText(UpdateLocationService.this, "onLocationChanged", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(UpdateLocationService.this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onDestroy() {
super.onDestroy();
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, UpdateLocationService.this);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, UpdateLocationService.this);
}
}