参考了网上给的几种方法,都没成功通过,在线等!
我自己的代码:
- Java code
//....MapView,MapController的一些代码省略 mLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE); //设置监听 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll); Location mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); while(mLocation == null){ Log.e("current postion","get failure"); mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); } //获取纬度 String latitude = Double.toString(mLocation .getLatitude()); //获取经度 String longitude = Double.toString(mLocation .getLongitude()); Log.e("当前方位","" + latitude + ":" + longitude); } @Override protected void onResume() { super.onResume();mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 1, ll); } @Override protected void onPause() { super.onPause(); Log.e("onPause",""+(countY++)); mLocationManager.removeUpdates(ll); }
ll 为LocationListener对象,几个方法未做特殊处理
------解决方案--------------------
//监视地点变化
public final LocationListener mLocationListener01 = new LocationListener()
{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
processLocationUpDated(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
private void gpsdw()
{
try
{
mLocationManager01 = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mLocation01 = getLocationProvider(mLocationManager01);
if(mLocation01 != null)
{
processLocationUpDated(mLocation01);
}
//监视 时间为2秒距离为10米
mLocationManager01.requestLocationUpdates(strLocationProvider, 2000, 10, mLocationListener01);
}catch(Exception e)
{
e.printStackTrace();
}
}
private void processLocationUpDated(Location location)
{
if(location != null)
{
Consts.Latitude = String.valueOf(location.getLatitude());
Consts.Longitude = String.valueOf(location.getLongitude());
}
}
private Location getLocationProvider(LocationManager lm){
Location retLocation = null;
try
{
Criteria mCriteria01 = new Criteria();
mCriteria01.setAccuracy(mCriteria01.ACCURACY_COARSE);
mCriteria01.setAltitudeRequired(false);
mCriteria01.setBearingRequired(false);
mCriteria01.setCostAllowed(true);
mCriteria01.setSpeedRequired(false);
mCriteria01.setPowerRequirement(Criteria.POWER_LOW);
strLocationProvider = lm.getBestProvider(mCriteria01, true);
//List<String> matchingProviders = lm.getProviders(mCriteria01,false);
retLocation = lm.getLastKnownLocation(strLocationProvider);
}catch(Exception e)
{
e.printStackTrace();
}
return retLocation;
}
这是我的代码,测试通过,程序中调用gpsdw()即可