帮我写一个Android百度定位的工具类 实用性强的
时间: 2024-04-30 16:18:30 浏览: 99
好的,以下是一个简单的Android百度定位的工具类。
前提条件:
1. 需要在AndroidManifest.xml文件中添加定位权限:ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION
2. 需要在百度开发者平台创建应用并获取到ak
```
public class BaiduLocationUtils {
private static final String TAG = "BaiduLocationUtils";
private static final int LOCATION_CODE = 1001;
private Context mContext;
private LocationClient mLocationClient;
private LocationCallback mLocationCallback;
public BaiduLocationUtils(Context context) {
mContext = context;
mLocationClient = new LocationClient(mContext);
mLocationCallback = new LocationCallback();
mLocationClient.registerLocationListener(mLocationCallback);
}
public void startLocation() {
if (!checkPermission()) {
return;
}
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
option.setCoorType("bd09ll");
option.setScanSpan(1000);
option.setOpenGps(true);
option.setIsNeedAddress(true);
mLocationClient.setLocOption(option);
mLocationClient.start();
}
public void stopLocation() {
mLocationClient.stop();
}
private boolean checkPermission() {
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_CODE);
return false;
}
return true;
}
private class LocationCallback extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
if (bdLocation == null) {
return;
}
int locType = bdLocation.getLocType();
if (locType == BDLocation.TypeGpsLocation
|| locType == BDLocation.TypeNetWorkLocation
|| locType == BDLocation.TypeOffLineLocation) {
stopLocation();
double latitude = bdLocation.getLatitude();
double longitude = bdLocation.getLongitude();
String address = bdLocation.getAddrStr();
String city = bdLocation.getCity();
if (TextUtils.isEmpty(address)) {
address = "定位失败";
}
Log.i(TAG, "latitude: " + latitude + ", longitude: " + longitude + ", address: " + address + ", city: " + city);
// TODO: 定位成功后的操作
}
}
}
}
```
使用时,在需要定位的地方调用startLocation()方法即可开始定位,调用stopLocation()方法结束定位。当定位成功时,会回调LocationCallback中的onReceiveLocation()方法,其中包含了定位的经纬度、地址和城市信息。在这个方法中可以根据需要进行相应的处理。
阅读全文