【发布时间】:2016-06-19 09:20:17
【问题描述】:
我有一个程序可以获取用户的纬度和经度。
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.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.
}
Location myLocation = locationManager.getLastKnownLocation(provider);
Location myLocation = locationManager.getLastKnownLocation(provider);
boolean netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (netEnabled) {
if (isGPSEnabled) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude()
} else if (!isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
// displayPromptForEnablingGPS(MapsActivity.this);
}
}
} else if (!netEnabled) {
if (isGPSEnabled) {
latitude = myLocation.getLatitude();
// Get longitude of the current location
longitude = myLocation.getLongitude();
} else {
// displayPromptForEnablingGPS(MapsActivity.this);
}
}
(displayPromptForEnablingGPS 用于 ACTION_LOCATION_SOURCE_SETTINGS)
在程序中,如果 GPS 和网络提供商已关闭,则会打开一个窗口以打开它们。当我第一次打开 GPS 时,它在第一个 if(GPSEnabled) 方法中出现错误(latitude=myLocation.getLatitude() 上的错误)。我无法获得纬度和经度。当我只打开网络提供商时也是一样的。它使“位置”变量为空。但是如果我打开谷歌地图,它会开始获取纬度和经度。
问题可能是什么?是手机的问题还是我必须通过编写任何代码来使 GPS 运行?
感谢您的帮助。
【问题讨论】:
标签: android google-maps android-studio gps