配置SDK
- 申请网址http://lbsyun.baidu.com/apiconsole/key/create
- 获取SHA1http://lbsyun.baidu.com/index.php?title=androidsdk/guide/key
- 按照操作创建完了之后拿到了访问应用(AK)
- 下载SDKhttp://lbsyun.baidu.com/index.php?title=sdk/download&action#selected=location_all,只需要基础定位
- 配置SDK http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/create-project/android-studio
编写代码
- show类实现接口BDLocationListener
public class Show extends Fragment implements CompoundButton.OnCheckedChangeListener, BDLocationListener {
- 定义相关变量
private TextView _locationTextView;
private LocationClient _locationClient;
private static final int BAIDU_READ_PHONE_STATE =100;
- 配置client并申请权限
_locationClient=new LocationClient(getContext());
_locationClient.registerLocationListener(this);
LocationClientOption option=new LocationClientOption();
option.setIsNeedAddress(true);
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置高精度定位定位模式
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
_locationClient.setLocOption(option);
if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
// 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义)
requestPermissions( new String[]{ Manifest.permission.READ_PHONE_STATE },BAIDU_READ_PHONE_STATE );
}else{
_locationClient.start();
}
- 重写权限结果函数
@Override
public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
//requestCode即所声明的权限获取码,在checkSelfPermission时传入
case 1:
BAIDU_READ_PHONE_STATE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
_locationClient.start();
} else {
Log.i("tag", "onRequestPermissionsResult: " + "没有获取到权限");
}
break;
default:
break;
}
}
- 重写定位结果函数
@Override
public void onReceiveLocation(BDLocation bdLocation) {
String addr = bdLocation.getAddrStr(); //获取详细地址信息
String country = bdLocation.getCountry(); //获取国家
String province = bdLocation.getProvince(); //获取省份
String city = bdLocation.getCity(); //获取城市
String district = bdLocation.getDistrict(); //获取区县
String street = bdLocation.getStreet(); //获取街道信息
_locationTextView.setText(city+district);
_locationClient.stop(); //获得结果之后停止,否则会一直定位
}
效果图
image.png
网友评论