1.引入定位依赖库
implementation 'com.amap.api:3dmap:9.3.1'
导入对应so库
2.使用
private GeoFenceClient mGeoFenceClient;
//定义接收广播的action字符串
public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";
private void initAreaFence() {
mGeoFenceClient = new GeoFenceClient(getApplicationContext());
//创建回调监听
GeoFenceListener fenceListenter = new GeoFenceListener() {
@Override
public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
if (i == GeoFence.ADDGEOFENCE_SUCCESS) {
Log.e("fenceListenter", "onGeoFenceCreateFinished " + i);
}
}
};
mGeoFenceClient.setGeoFenceListener(fenceListenter);//设置回调监听
//创建并设置PendingIntent
mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
polygonFence();
administrationFence();
createCircleFence();
}
private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
//解析广播内容
//获取Bundle
Bundle bundle = intent.getExtras();
//获取围栏行为:
//public static final int GEOFENCE_IN 1 进入地理围栏
//public static final int GEOFENCE_OUT 2 退出地理围栏
//public static final int GEOFENCE_STAYED 4 停留在地理围栏内10分钟
int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
Log.e("status", "status " + status);
//获取自定义的围栏标识:
String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
String msg = customId;
if (status == 1) {
msg = "进入敏感区域【" + msg + "】";
} else {
msg = "离开敏感区域【" + msg + "】";
}
XuiToastUtils.info(msg);
//获取围栏ID:
String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
//获取当前有触发的围栏对象:
GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
Log.e("customId", "customId " + customId);
Log.e("fenceId", "fenceId " + fenceId);
}
}
};
/**
* 行政区划 围栏
* keyword
* 行政区划关键字 例如:朝阳区
* customId
* 与围栏关联的自有业务Id
*/
private void administrationFence() {
mGeoFenceClient.addGeoFence("河南省郑州市中原区", "行政-北京围栏");
}
/**
* point 围栏中心点
* radius 要创建的围栏半径 ,半径无限制,单位米
* customId 与围栏关联的自有业务Id
*/
private void createCircleFence() {
//创建一个中心点坐标
DPoint centerPoint = new DPoint();
//设置中心点纬度
centerPoint.setLatitude(34.831179); // 113.549834,34.831179
//设置中心点经度
centerPoint.setLongitude(113.549834);
mGeoFenceClient.addGeoFence(centerPoint, 1000F, "圆形围栏");
}
/**
* 多边形 围栏
* points
* 多边形的边界坐标点,最少传3个
* customId
* 与围栏关联的自有业务Id
*/
private void polygonFence() {
List<DPoint> points = new ArrayList<DPoint>();
points.add(new DPoint(34.82549, 113.562237));
points.add(new DPoint(34.824019, 113.561185));
points.add(new DPoint(34.822557, 113.56273));
points.add(new DPoint(34.823218, 113.563932));
points.add(new DPoint(34.824636, 113.565133));
mGeoFenceClient.addGeoFence(points, "多边形围栏");
}
3.退出时关闭对应广播围栏监听
//会清除所有围栏标签:DPoint,mGeoFenceClient,高德,围栏,points,new,Android,customId From: https://blog.51cto.com/u_15948835/6042572
mGeoFenceClient.removeGeoFence();
// 广播注销
unregisterReceiver(mGeoFenceReceiver);