我正试图获得GPS经度&纬度。 在使用任何其他打开GPS的程序时,GPS正在打开时,一切正常。
但是当我尝试仅使用我的应用程序时,GPS无法启动。
这是我的代码:
m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = m_locationManager.getBestProvider(m_c, false);
Location location = m_locationManager.getLastKnownLocation(provider);
if (location != null)
{
double lng = location.getLongitude();
double lat = location.getLatitude();
gpsLocationLon.setText("" + lng);
gpsLocationLat.setText("" + lat);
}
else
{
gpsLocationLon.setText("No Provider");
gpsLocationLat.setText("No Provider");
}
public void onLocationChanged(Location location) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(null != gpsLocationLat && null != gpsLocationLon)
{
gpsLocationLon.setText("" + lng);
gpsLocationLon.setText("" + lat);
}
}
我错过了什么?
答案 0 :(得分:1)
您需要在找到最佳提供商后开始收听位置更新。
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider, 0, 0, this);
// ^^ This will start listening for location updates
// depending on your provider.
} else {
Log.d(LOGTAG, provider + " not enabled");
}
请记住,提供商有两种类型,即gps和网络。所以它取决于选择哪一个的标准(m_c
)。
如果您想确保要收听GPS以及网络更新,请删除Criteria变量并尝试以下操作:
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
} else {
Log.d(LOGTAG, "network provider not enabled");
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else {
Log.d(LOGTAG, gps provider not enabled");
}
编辑1:
m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (m_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
m_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location location = m_locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
else {
Log.d(LOGTAG, "network provider not enabled");
}
if (m_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
m_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else {
Log.d(LOGTAG, "gps provider not enabled");
}
if (location != null)
{
double lng = location.getLongitude();
double lat = location.getLatitude();
gpsLocationLon.setText("" + lng);
gpsLocationLat.setText("" + lat);
}
else
{
gpsLocationLon.setText("No Provider");
gpsLocationLat.setText("No Provider");
}
public void onLocationChanged(Location location) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(null != gpsLocationLat && null != gpsLocationLon)
{
gpsLocationLon.setText("" + lng);
gpsLocationLon.setText("" + lat);
}
}