我正在嘗試在移動設備上獲取GPS經緯度。我的下面的代碼工作 - 即它以所需的方式提供所有信息 - 當選擇設備的「使用無線網絡」設置時,而不是選擇「使用GPS衛星」時,在這種情況下,我沒有得到任何信息。通過GPS獲取緯度和經度
下面的代碼:
void getLatitudeAndLongitude() {
boolean gpsEnabled = false;
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.e("mLocation#####", "" + mLocMan);
try {
gpsEnabled = mLocMan
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
boolean networkEnabled = false;
try {
networkEnabled = mLocMan
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
Location mCurrentLocation = null;
// network*****************
if (networkEnabled)
mCurrentLocation = mLocMan
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// gps********************
if (gpsEnabled)
mCurrentLocation = mLocMan
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("current location", "" + mCurrentLocation);
LocationProvider mGpsProv = null;
if (mGpsProv == null && mLocMan != null) {
mGpsProv = mLocMan.getProvider(LocationManager.GPS_PROVIDER);
}
if (mLocMan != null) {
mylocationlistener mGpsLocListener = new mylocationlistener();
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0 /* minTime ms */, 0 /* minDistance in meters */,
mGpsLocListener);
Log.d("Provoider1", "NETWORK_PROVIDER");
}
if (mLocMan != null && mGpsProv != null) {
mylocationlistener mGpsLocListener = new mylocationlistener();
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0 /* minTime ms /, 0/minDistance in meters */, 0,
mGpsLocListener);
Log.d("Provoider2", "GPS_PROVIDER");
}
}
class mylocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
Log.e("location==", "" + location);
Log.e("getLatitude", location.getLatitude() + "");
Log.e("getLongitude", location.getLongitude() + "");
if (GlobalConfig.DEBUG)
Log.d("setUpIndividualWork", "location==" + location);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 1000);
onGPSUpdate(location);
Geocoder gcd = new Geocoder(setUpIndividualWorkOut.this,
Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
userCurrentLocation = addresses.get(0).getLocality();
Log.e("current location by GPS ", ""
+ addresses.get(0).getLocality());
}
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
我將是你的反應非常感謝。
當你嘗試這個時,你是否清楚地看到了天空? GPS通常不起作用 – Craigy 2012-07-31 11:20:49
拋出一些'else's:如果'networkEnabled'和'gpsEnabled'都是'true',那麼你得到了兩次LastKnownLocation。此外,如果mLocMan和mGpsProv都爲空,則您正在請求更新兩次。 – 2012-07-31 11:26:59