我正在尝试使用GPS获取设备的位置信息,但由于某种原因,有时会丢失其中一个坐标。
这是代码:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
有时我会得到两个坐标,但并非总是如此,这让我想到某处的某种延迟。当发生这种情况时,有没有办法找出为什么缺少GPS坐标?
答案 0 :(得分:1)
因为GPS不会一直亮着。 getLastKnownLocation将返回一个位置,如果它知道一个并且它不是太陈旧。由于没有其他任何东西使用GPS,它不知道一个。如果您需要一个位置,请求requestLocationUpdates或requestSingleUpdate,这将打开GPS并获得一个新位置。
答案 1 :(得分:0)
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
//
}
在onLocationChanged方法中,您可以使用 location.getLatitude& location.getLongitude