最近在搞Android的手机定位,结果location一直返回null,上网查了查很多人也遇到了这个问题,有的人直接写了一个循环,不断的获取location,这样显然是不太合理的,因为经过我的测试,获得一个location大概需要10-15s左右,循环相当于location为null时就重新通过LocationManager 获取location,根本等不了10s。所以后来研究到了用一个LocationListener,当获得location或者location发生变化后就会回调LocationListener中的onLoCationChange方法。利用这种定位代理模式很好地解决了这个问题。
附上代码:
判断GPS是否启用的函数
private void openGPSSettings2() {
LocationManager alm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
if (alm
.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT)
.show();
doWork();
return;
}
Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCALE_SETTINGS);
startActivityForResult(intent,0); //此为设置完成后返回到获取界面
}
若没有启动会跳掉GPS设置界面,设置完成后,调用此方法
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) { //resultCode为回传的标记,我在B中回传的是RESULT_OK
case 0:
doWork();
break;
case RESULT_FIRST_USER:
break;
default:
break;
}
}
调用dowork()开始定位
private void doWork() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// 获得最好的定位效果
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
// 使用省电模式
criteria.setPowerRequirement(Criteria.POWER_LOW);
// 获得当前的位置提供者
String provider = locationManager.getBestProvider(criteria, true);
// 获得当前的位置
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates("gps", 60000, 1, locationListener);
}
定位成功后系统自动回调调用LocationListener中的onLocationChanged函数(currentCity是xml中显示当前城市的控件)
LocationListener locationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
AnArrivalCityActivity.this.location=location;
Geocoder gc = new Geocoder(AnArrivalCityActivity.this);
String msg = "";
List<Address> addresses = null;
try {
addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} if (addresses.size() > 0) {
msg += "AddressLine:" + addresses.get(0).getAddressLine(0)+ "\n";
msg += "CountryName:" + addresses.get(0).getCountryName()+ "\n";
msg += "Locality:" + addresses.get(0).getLocality() + "\n";
msg += "FeatureName:" + addresses.get(0).getFeatureName();
}
currentCity.setText(addresses.get(0).getLocality());
Logger.d("-----------currentCity----------------" + currentCity.getText());
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
};