要实现Android定期获取位置,即使应用实例已终止,可以使用后台服务和定时器来实现。下面是一个示例代码:
import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
public class LocationService extends Service {
private static final String TAG = "LocationService";
private static final long INTERVAL = 10 * 1000; // 10秒
private static final long FASTEST_INTERVAL = 5 * 1000; // 5秒
private FusedLocationProviderClient fusedLocationClient;
private LocationCallback locationCallback;
@Override
public void onCreate() {
super.onCreate();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
createLocationRequest();
startLocationUpdates();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY; // 在服务被杀死后自动重启
}
@Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createLocationRequest() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
Log.d(TAG, "onLocationResult: " + location.getLatitude() + ", " + location.getLongitude());
// 在此处处理获取到的位置信息
}
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
}
private void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
}
private void stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(this, LocationService.class);
startService(serviceIntent);
}
这样,即使应用实例已终止,服务仍然可以在后台定期获取位置信息。请确保在AndroidManifest.xml文件中申请了获取位置的权限(ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION)。