android关于LocationManager的gps定位

LocationManager提供了两种定位当前位置的方法 GPS和NETWORK 其中gps的误差大概50m左右 network大概500m

起初当gps打开后 我使用Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);来获取location 可是一直为null不知道是什么原因 网上搜了很久终于找到了解决方案


android有一个Criteria类可以直接判断当前适合用gps或者network 并且设置LocationListener监听器实时更新location 直接上代码


private void getLocalAddress() {

LocationManager locationManager;

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_FINE);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false);

criteria.setCostAllowed(true);

criteria.setPowerRequirement(Criteria.POWER_LOW);

String provider = locationManager.getBestProvider(criteria, true);

Location location = locationManager.getLastKnownLocation(provider);

//updateWithNewLocation(location);

locationManager.requestLocationUpdates(provider, 2000, 10,

locationListener);

updateWithNewLocation(location);

}



private final LocationListener locationListener = new LocationListener() {

public void onLocationChanged(Location location) {

updateWithNewLocation(location);

}


public void onProviderDisabled(String provider) {

updateWithNewLocation(null);

}


public void onProviderEnabled(String provider) {

}


public void onStatusChanged(String provider, int status, Bundle extras) {

}

};



private void updateWithNewLocation(Location location) {

String latLongString;

TextView myLocationText;

if (location != null) {

double lat = location.getLatitude();

double lng = location.getLongitude();

latLongString = "纬度:" + lat + "\n经度:" + lng;

} else {

latLongString = "无法获取地理信息";

}

Toast.makeText(SearchXiaoQuActivity.this, latLongString,

Toast.LENGTH_LONG).show();

}


更多相关文章

  1. android 项目中规范使用SharedPreferences
  2. Android(安卓)打开相机、相册获取图片文件,支持Android(安卓)9.0
  3. android 项目中规范使用SharedPreferences
  4. Android调用getSimSerialNumber获取iccid不完整
  5. android低功耗蓝牙APP开发问题记录
  6. [Android]googleMap的简单使用,地图定位,图标绘制。
  7. 获取Android设备的方向
  8. Android获取屏幕的宽和高
  9. 命令获取 Eclipse Android(安卓)证书指纹 MD5、SHA1

随机推荐

  1. Delphi Android USB Interface with the
  2. android点滴(11) -- Android常用命令
  3. android 权限介绍(一)
  4. android NDK/JNI-实例开发流程
  5. android Toolbar的使用结合状态栏与返回
  6. 【Android Audio】Android Audio System
  7. Android SDK目录结构和工具介绍
  8. Android recyclerview更新item位置移动
  9. 【荐货】Android主流技术知多少?
  10. Android音频系统之四AudioPolicy