如何找出Android中GPS坐标缺失的原因?
问题描述:
我想使用GPS获取设备的位置信息,但由于某种原因,有时会丢失两个坐标中的一个。如何找出Android中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坐标缺少这种情况?
答
因为GPS并不总是打开。如果getLastKnownLocation知道一个并且它不是过时的,它将返回一个位置。由于没有其他人使用GPS,它不知道。如果你需要一个位置,requestLocationUpdates或requestSingleUpdate,这将打开GPS并获得一个新的位置。
答
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
谢谢,是有道理的。不过,我仍然应该在'requestSingleUpdate'后面调用'getLastKnownLocation',对吗? – user1301428
你不需要。 requestSingleUpdate有一个回调参数,当它有结果时(它需要一段时间才能启动GPS,它需要与卫星对话)。您可以致电GLKL,看看它是否恰好有一个存储位置,以便您可以更快地显示它,但您不能指望它。 –
完美,谢谢! – user1301428