我正在开发一个应用程序。其中,我需要获取用户的当前位置。我正在使用网络获取当前位置,但是当我启动 GPS 时,它没有显示当前位置。可能是什么问题?
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String bestProvider = locationManager.getBestProvider(criteria, true);
System.out.println("Best Provider:"+bestProvider);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
Toast.makeText(mContext, "GPS and Network not enabled!", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
//LocationManager.NETWORK_PROVIDER,
bestProvider,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
//.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
.getLastKnownLocation(bestProvider);
if (location != null) {
startLatitude = location.getLatitude();
startLongitude = location.getLongitude();
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
//LocationManager.GPS_PROVIDER,
bestProvider,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
//.getLastKnownLocation(LocationManager.GPS_PROVIDER);
.getLastKnownLocation(bestProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
我已添加权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
最佳答案
google 在他们最近的 Google IO 2013 Activity 中发布了一个不错的 API:
https://developers.google.com/events/io/sessions/324498944
您应该检查一下,看看如何最小化您的代码。
请注意,它需要设备具有 Play 商店应用程序才能运行。
与使用普通位置传感器相比,此方法具有许多优势(电池、速度、精度...)。
关于android - 无法使用 GPS 获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18207673/