建议使用Android Studio3.0版本,最初我使用书中的2.0版本,导入BaiduLBS_Android.jar库之后报出各种错误,改一个就会出现另一个错误。于是下了一个AS3.5.0版本,并按照百度开发者文档中所要求的步骤成功移植库。
一、注册和获取密匙&&AS的配置
参考百度Android定位的SDK网址,配置的结果如下:
工程文件结构为:
AndroidManifest.xml文件为:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lbstest">
<!-- 这个权限用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<!-- 这个权限用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<!-- 访问网络,网络定位需要上网-->
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="XkgsMYYtBgIblZ0NLD3DUnF35cf3oFFV" >
</meta-data>
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote">
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle文件为:
apply plugin: 'com.android.application'
android {
compileSdkVersion 31
buildToolsVersion "31.0.0"
defaultConfig {
applicationId "com.example.lbstest"
minSdkVersion 15
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets{
main{
jniLibs.srcDir 'libs'
jni.srcDirs = [] //disable automatic ndk-build
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation ('androidx.test.espresso:espresso-core:3.1.1',{
exclude group: 'com.android.support', module: 'support-annotations'
})
}
二、定位的实现部分
参考官方文档:Android定位SDK - 获取经纬度 | 百度地图API SDK
1.前端的界面就一个TextView,activity_main.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/position_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
2.代码逻辑实现以及结果显示在MainActivity.java文件中,代码如下:
public class MainActivity extends AppCompatActivity {
public LocationClient mLocationClient = null;
private TextView positionText;
private MyLocationListener myListener = new MyLocationListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient(getApplicationContext());
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationMode.Hight_Accuracy);
option.setCoorType("bd09ll");
option.setScanSpan(1000);
option.setOpenGps(false);
option.setLocationNotify(false);
option.setIgnoreKillProcess(false);
option.SetIgnoreCacheException(false);
option.setWifiCacheTimeOut(1000);
option.setEnableSimulateGps(false);
option.setIsNeedAddress(true);
option.setNeedNewVersionRgc(true);
mLocationClient.setLocOption(option);
mLocationClient.registerLocationListener(myListener);
setContentView(R.layout.activity_main);
positionText = (TextView)findViewById(R.id.position_text_view);
List<String>permissionList = new ArrayList<>();
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_WIFI_STATE)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.ACCESS_WIFI_STATE);
}
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.ACCESS_NETWORK_STATE);
}
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CHANGE_WIFI_STATE)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.CHANGE_WIFI_STATE);
}
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.INTERNET);
}
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
//如果非空
if(!permissionList.isEmpty()){
String[] permissions = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this,permissions,1);
}else{
requestLocation();
}
}
private void requestLocation(){
mLocationClient.start();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
if(grantResults.length > 0){
for(int result: grantResults){
if(result != PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"必须同意所有权限才可以使用应用",Toast.LENGTH_SHORT).show();
finish();
return;
}
}
//同意了才会执行到这里
requestLocation();
}else{
Toast.makeText(this,"发生未知错误",Toast.LENGTH_SHORT).show();
finish();
}
}
}
public class MyLocationListener extends BDAbstractLocationListener{
@Override
public void onReceiveLocation(BDLocation location){
//此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果
//以下只列举部分获取经纬度相关(常用)的结果信息
//更多结果信息获取说明,请参照类参考中BDLocation类中的说明
final double latitude = location.getLatitude(); //获取纬度信息
final double longitude = location.getLongitude(); //获取经度信息
final float radius = location.getRadius(); //获取定位精度,默认值为0.0f
//获取经纬度坐标类型,以LocationClientOption中设置过的坐标类型为准
final String coorType = location.getCoorType();
//获取定位类型、定位错误返回码,具体信息可参照类参考中BDLocation类中的说明
final int errorCode = location.getLocType();
final String addr = location.getAddrStr(); //获取详细地址信息
final String country = location.getCountry(); //获取国家
final String province = location.getProvince(); //获取省份
final String city = location.getCity(); //获取城市
final String district = location.getDistrict(); //获取区县
final String street = location.getStreet(); //获取街道信息
final String adcode = location.getAdCode(); //获取adcode
final String town = location.getTown(); //获取乡镇信息
//回到主线程中更新UI
runOnUiThread(new Runnable() {
@Override
public void run() {
StringBuilder currentPosition = new StringBuilder();
currentPosition.append("纬度:").append(latitude).append("\n");
currentPosition.append("经度:").append(longitude).append("\n");
currentPosition.append("定位精度:").append(radius).append("\n");
currentPosition.append("经纬度坐标类型:").append(coorType).append("\n");
currentPosition.append("定位类型、定位错误返回码:").append(errorCode).append(":");
if(errorCode == 161){
currentPosition.append("网络定位成功").append("\n");
}else if(errorCode == 505){
currentPosition.append("server校验KEY失败,请确认KEY合法").append("\n");
}
currentPosition.append("地址:").append(addr).append("\n");
positionText.setText(currentPosition);
}
});
}
}
}
三、效果展示