所以我希望我的应用程序能够跟踪手机的位置。我正在使用 FusedLocationProviderClient 来获取位置。一个人单击一个按钮,然后我的应用程序运行一个 trackLocation() 函数。然而,无论我在哪里,我的函数都会返回相同的经度和纬度。这是轨道位置:
private void trackLocation(){
button.setText("Tracking");
fusedLocationClient= LocationServices.getFusedLocationProviderClient(MainActivity.this);
if(ContextCompat.checkSelfPermission( MainActivity.this,android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(
MainActivity.this,
new String [] { Manifest.permission.ACCESS_COARSE_LOCATION,android.Manifest.permission.ACCESS_FINE_LOCATION },
1
);
}
fusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
TextView textView=findViewById(R.id.textView);
String latText=Double.toString(latitude);
String longText=Double.toString(longitude);
textView.setText(latText+" "+longText);
}
});
}
提前谢谢您。
最佳答案
尝试此操作来获取位置更新。您需要定期调用此函数来获取更新。根据您的喜好设置间隔。
private LocationRequest locationRequest;
private LocationCallback locationCallback;
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(20 * 1000);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
}
}
}
};
关于java - 无论我身在何处,我的应用程序都会返回相同的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59231210/