直接上代码:
重要的 是 获取位置权限,否则 是获取不到的!!!
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setCostAllowed(false);
//设置位置服务免费
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //设置水平位置精度
//getBestProvider 只有允许访问调用活动的位置供应商将被返回
String providerName = lm.getBestProvider(criteria, true);
if (providerName != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
return;
}
Location location = lm.getLastKnownLocation(providerName);
//获取维度信息
double latitude = location.getLatitude();
//获取经度信息
double longitude = location.getLongitude();
Log.i("获取经纬度", "定位方式: " + providerName + " 维度:" + latitude + " 经度:" + longitude);
} else {
Toast.makeText(this, "1.请检查网络连接 \n2.请打开我的位置", Toast.LENGTH_SHORT).show();
}