现在很多应用都有定位的需求,我现在的项目也用到了。
如果只用到定位我们会想到的方案一是:用Android自带的定位拿到经纬度,然后调用Google提供的API获取详细的信息。这方案如果不是在我们国内的话绝对的可行,但是我们很多国产手机都把Google这一块阉割掉了,它的功能自然就有问题了(拿不到经纬度、定位不了)。不过我还是贴一下代码吧。
private LocationManager locationManager;
private String locationProvider;
private void getLocation() {
//获取地理位置管理器
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
List<String> providers = locationManager.getProviders(true);
if (providers.contains(LocationManager.GPS_PROVIDER)) {
//如果是GPS
locationProvider = LocationManager.GPS_PROVIDER;
} else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//如果是Network
locationProvider = LocationManager.NETWORK_PROVIDER;
} else {
Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
return;
}
//获取Location
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
Toast.makeText(MainActivity.this, "miss Permisson", Toast.LENGTH_LONG).show();
return;
}
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null) {
//不为空,显示地理位置经纬度
String locationStr = "维度:" + location.getLatitude() + "\n"
+ "经度:" + location.getLongitude();
Log.i("定位", locationStr);
return;
}
//监视地理位置变化
locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
}
/**
* LocationListern监听器
* 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
*/
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle arg2) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
//如果位置发生变化,重新显示
String locationStr = "维度:" + location.getLatitude() + "\n"
+ "经度:" + location.getLongitude();
Log.i("定位", locationStr);
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "miss Permisson", Toast.LENGTH_LONG).show();
return;
}
locationManager.removeUpdates(locationListener);
}
};
那我们还有什么其他的解决方案吗?答案是肯定的,方案二:百度定位,百度已经把地图和定位分开来了,我们只需要定位的话就只下定位的sdk就可以了。
怎么没贴代码??你傻啊,肯定是去百度官网去找啊,毕竟官网可靠一点。
连地址都给你们贴了,够义气吧。http://lbsyun.baidu.com/index.php?title=android-locsdk