连接地址: http://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9%A1%B5
https://ws1.sinaimg.cn/large/e25f3775ly1g8242lhl2dj20ux0hfjs5.jpg
上图是创建时候的一个展示,具体看看文档说明:
https://ws1.sinaimg.cn/large/e25f3775ly1g824a7ydedj20k9020t8j.jpg
可以看到对应的id和ak,等信息,后面再开放中会使用到.
http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/create-project/android-studio
我们先看看下载下来的libs包:
https://ws1.sinaimg.cn/large/e25f3775ly1g824ehitmqj21120dg3z0.jpg
导入对于项目下的libs;
第三步,配置build.gradle文件
配置build.gradle文件,注意设置sourceSets。
sourceSets{
main{
jniLibs.srcDir 'libs'
jni.srcDirs = [] //disable automatic ndk-build
}
}
dependencies {
compile fileTree(dir: 'libs' , include: ['*.jar'])
androidTestCompile ('com.android.support.test.espresso: espresso-core: 2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support: appcompat-v7:25.1.0'
testCompile 'junit: junit: 4.12'
}
第四步: 在清单文件中增加ak
具体在application节点下添加:
在Application标签中增加如下代码:
<!--配置百度的ak-->
<meta-data
android:name="io.xiaoduo.lbstest"
android:value="LBrSDFrOXpnNvWfmhfxXWdZOrYPYxLgV"></meta-data>
第五步:增加对应的权限
<!--联网的权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 这个权限用于进行网络定位-->
<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>
<!-- android 9.0上使用前台服务,需要添加权限-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!--服务定位的声明-->
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote"></service>
开始以前注意6.0的动态权限:
暂时使用的工具类: PermissionKits
代码: 主线程初始化:
private void initBaiDu() {
mLocationClient = new LocationClient(getApplicationContext());
// 注册listener
MyMainBdLocationListener myBdLocationListener = new MyMainBdLocationListener();
mLocationClient.registerLocationListener(myBdLocationListener);
// 初始化sdk的配置信息
LocationClientOption option = new LocationClientOption();
//可选,是否需要地址信息,默认为不需要,即参数为false
//如果开发者需要获得当前点的地址信息,此处必须为true
option.setIsNeedAddress(true);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置,请参照类参考中LocationClientOption类的详细说明
mLocationClient.setLocOption(option);
}
实现BDAbstractLocationListener接口
Android定位SDK自V7.2版本起,对外提供了Abstract类型的监听接口BDAbstractLocationListener,用于实现定位监听。原有BDLocationListener暂时保留,推荐开发者升级到Abstract类型的新监听接口使用,该接口会异步获取定位结果,核心代码如下:
在定位结果BDLocation类中,可通过getLocType方法来获取本次定位的错误返回码,成功码61
public class MyBdLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
String addr = location.getAddrStr(); //获取详细地址信息
String country = location.getCountry(); //获取国家
String province = location.getProvince(); //获取省份
String city = location.getCity(); //获取城市
String district = location.getDistrict(); //获取区县
String street = location.getStreet(); //获取街道信息
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mTv_show_location_address.setText(addr); // 展示地址
Log.d("main_addr", "onReceiveLocation: "+" addr "+addr
+" country "+ country+" province "+ province+ " city "
+city+" district "+ district+ " street "+street);
}
});
}
}
开启定位:
调用LocationClient的start()方法,发起请求,在BDAbstractLocationListener接口中,便可获得定位地址相关的信息。
2019-10-18 10:35:53.945 22644-22644/io.xiaoduo.lbstest D/main_addr: onReceiveLocation: addr 中国天津市西青区海泰发展六道7号 country 中国 province 天津市 city 天津市 district 西青区 street 海泰发展六道
public static void setOnLbsKitLocationListener(onLbsKitLocationListener onLbsKitLocationListener) {
mOnLbsKitLocationListner = onLbsKitLocationListener;
}
private static onLbsKitLocationListener mOnLbsKitLocationListner;
//回调
public interface onLbsKitLocationListener {
void onLbsKitLocationSuccess(BDLocation location);
void onLbsKitLocationFail(int type, String message);
}
直接调用就行了.
附件是: 完整的工具类和获取权限的工具类:
package io.xiaoduo.lbstest.utils;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.util.Log;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.ACCESS_WIFI_STATE;
/**
* PACKAGE_NAME: io.xiaoduo.lbstest.utils
* PROJECT_NAME:AllIsWell
* 创建日期 :2019/10/18
* 创建时间: 13/38
* author kunkun5love
* 说明: 定位的工具类,前提条件是,导入对应的jar包和so库,清单文件配置权限申明和ak以及定位服务
***/
public class LbsKit {
private static LocationClient mLocationClient;
//网络定位成功的返回码 161
private static final int TYPENETWORKLOCATIONSUCCESSCODE = BDLocation.TypeNetWorkLocation;
private static final String TYPENETWORKLOCATIONSUCCESSSTRING = "NetWork location successful!";
// GPS定位成功 61
private static final int TYPEGPSLOCATIONSUCCESSCODE = BDLocation.TypeGpsLocation;
private static final String TYPEGPSLOCATIONSUCCESSSTRING = "GPS location successful!";
// 失败码集合
//网络异常:没有成功向服务器发起请求,请确认当前测试手机网络是否通畅,尝试重新请求定位 63
private static final int TYPE_NETWORKLOCATION_FAIL = BDLocation.TypeNetWorkException;
private static final String TYPE_NETWORKLOCATION_STRING = "Offline location failed, please check the net (wifi/cell)!";
//不存在或者非法:请按照说明文档重新申请AK 505
private static final int TYPE_NOTAK_FAIL = BDLocation.TypeServerCheckKeyError;
private static final String TYPE_NOTAK_FAILSTRING = "NetWork location failed because baidu location service check the key is unlegal, please check the key in AndroidManifest.xml !";
// 定位失败: 无法获取有效定位依据,请检查运营商网络或者WiFi网络是否正常开启,尝试重新请求定位 62
private static final int TYPE_LOCATION_FAIL = BDLocation.TypeCriteriaException;
private static final String TYPE_LOCATION_FAILSTRING = "Location failed beacuse we can not get any loc information!";
/**
* 普通定位的初始化
*/
public static void initNinitNormalLoacl(Context applicationContext) {
mLocationClient = new LocationClient(applicationContext);
// 注册listener
LbsKitBdLocationListener lbsKitBdLocationListener = new LbsKitBdLocationListener();
mLocationClient.registerLocationListener(lbsKitBdLocationListener);
// 初始化sdk的配置信息
LocationClientOption option = new LocationClientOption();
//可选,是否需要地址信息,默认为不需要,即参数为false
//如果开发者需要获得当前点的地址信息,此处必须为true
option.setIsNeedAddress(true);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象,通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置,请参照类参考中LocationClientOption类的详细说明
mLocationClient.setLocOption(option);
}
/**
* 开启定位功能
*/
public static void startNormalLoacl(Activity mainActivity) {
//检查权限 网络定位:ACCESS_COARSE_LOCATION Gps定位:ACCESS_FINE_LOCATION wifi定位:ACCESS_WIFI_STATE
boolean checkAndRequestPremissions = PermissionKits.checkAndRequestPremissions(mainActivity, new PermissionKits.OnRequestPmListener() {
@Override
public void onRequestPermissionsResult(@NonNull String[] permissions, @NonNull int[] grantResults) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
return;
}
}
// 开启定位
mLocationClient.start();
}
}, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE);
if (checkAndRequestPremissions) {
// 开启定位
mLocationClient.start();
}
}
public static class LbsKitBdLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
int locType = location.getLocType();
if (locType == TYPENETWORKLOCATIONSUCCESSCODE | locType == TYPEGPSLOCATIONSUCCESSCODE) {
// 定位成功
mOnLbsKitLocationListner.onLbsKitLocationSuccess(location);
} else {
//定位失败
switch (locType) {
case TYPE_NETWORKLOCATION_FAIL:
case 67: //离线定位失败
mOnLbsKitLocationListner.onLbsKitLocationFail(locType, TYPE_NETWORKLOCATION_STRING);
break;
case TYPE_NOTAK_FAIL:
mOnLbsKitLocationListner.onLbsKitLocationFail(locType, TYPE_NOTAK_FAILSTRING);
break;
case TYPE_LOCATION_FAIL:
mOnLbsKitLocationListner.onLbsKitLocationFail(locType, TYPE_LOCATION_FAILSTRING);
break;
default:
mOnLbsKitLocationListner.onLbsKitLocationFail(locType, "其他错误码");
}
}
String addr = location.getAddrStr(); //获取详细地址信息
String country = location.getCountry(); //获取国家
String province = location.getProvince(); //获取省份
String city = location.getCity(); //获取城市
String district = location.getDistrict(); //获取区县
String street = location.getStreet(); //获取街道信息
Log.d("MyBdLocationListener", "onReceiveLocation: " + " addr " + addr
+ " country " + country + " province " + province + " city "
+ city + " district " + district + " street " + street + " 请求码 " + locType);
}
}
public static void setOnLbsKitLocationListener(onLbsKitLocationListener onLbsKitLocationListener) {
mOnLbsKitLocationListner = onLbsKitLocationListener;
}
private static onLbsKitLocationListener mOnLbsKitLocationListner;
//回调
public interface onLbsKitLocationListener {
void onLbsKitLocationSuccess(BDLocation location);
void onLbsKitLocationFail(int type, String message);
}
}
package io.xiaoduo.lbstest.utils;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
public class PermissionKits {
public interface OnRequestPmListener {
void onRequestPermissionsResult(@NonNull String[] permissions, @NonNull int[] grantResults);
}
static final int REQUEST_CODE = 0x1000;
static WeakHashMap phPool = new WeakHashMap<>();
static PermissionKits get(Activity activity) {
return phPool.get(activity);
}
public static void onRequestPermissionsResult(Activity activity, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
PermissionKits kits = get(activity);
if (kits != null) {
kits.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public static PermissionKits with(Activity activity) {
PermissionKits ret = get(activity);
if (ret == null) {
ret = new PermissionKits(activity);
}
phPool.put(activity, ret);
return ret;
}
public static boolean checkAndRequestPremissions(Activity activity, OnRequestPmListener listener, String... permissions){
return with(activity).checkAndRequestPremissions(listener, permissions);
}
WeakReference activity;
private int requestCode;
private Map listeners = new HashMap<>();
public PermissionKits(Activity activity) {
this.activity = new WeakReference<>(activity);
}
Activity getActivity() {
return activity.get();
}
/**
* 申请权限 {@linkplain Build.VERSION_CODES#M Android6.0}以上会调用{
* 需要在{@link Activity
*
* @param listener 权限状态监听
* @param permissions 需要申请权限
* @see ActivityCompat#
*/
public void requestPermissions(OnRequestPmListener listener, String... permissions) {
if (getActivity() != null) {
ActivityCompat.requestPermissions(getActivity(), permissions, REQUEST_CODE + requestCode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
listeners.put(REQUEST_CODE + requestCode, listener);
}
requestCode = (++requestCode) % 1000;
}
}
/**
* 校验权限 如果权限不足会申请该权限
*
* @param listener 权限状态监听
* @param permissions 需要申请权限
* @return 返回true已拥有所有权限,否则返回false
* @see #requestPermissions
*/
public boolean checkAndRequestPremissions(OnRequestPmListener listener, String... permissions) {
if (getActivity() == null) {
return false;
}
String[] noPermissions = checkPermission(getActivity(), permissions);
if (noPermissions == null) {
return true;
}
requestPermissions(listener, noPermissions);
return false;
}
/**
* 校验权限
*
* @param context
* @param permissions 需要校验的权限
* @return 未获得权限
*/
public static String[] checkPermission(Context context, String... permissions) {
if (context == null) {
return null;
}
List noPermisstions = new ArrayList<>();
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
noPermisstions.add(permission);
}
}
if (noPermisstions.isEmpty()) {
return null;
}
String[] ret = new String[noPermisstions.size()];
return noPermisstions.toArray(ret);
}
/**
* 在{@linkplain Build.VERSION_CODES#M Android6.0}以上版本运行时,可以申请运行时权限,该方法处理申请权限的回调
*
* @param requestCode
* @param permissions
* @param grantResults
* @see ActivityCompat#requestPermissions
* @see Activity#onRequestPermissionsResult
*/
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
OnRequestPmListener listener = listeners.remove(requestCode);
if (listener != null) {
listener.onRequestPermissionsResult(permissions, grantResults);
}
}
}
m requestCode
* @param permissions
* @param grantResults
* @see ActivityCompat#requestPermissions
* @see Activity#onRequestPermissionsResult
*/
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
OnRequestPmListener listener = listeners.remove(requestCode);
if (listener != null) {
listener.onRequestPermissionsResult(permissions, grantResults);
}
}
}