package com.dpf.daohangttt.dpfdaohang;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_IN;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED;
public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {
private TextView mTvwodeweizhi, mTvjutiweizhi, mTvshijian;
MapView mMapView;
AMap aMap;
OnLocationChangedListener mListener;
AMapLocationClient mlocationClient;
AMapLocationClientOption mLocationOption;
boolean isFisrt = true;
long time;
//定义接收广播的action字符串
public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.map);//获取地图控件引用
mMapView.onCreate(savedInstanceState);//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),创建地图
initView();
}
private void initView() {
mTvwodeweizhi = findViewById(R.id.wodeweizhi);
mTvjutiweizhi = findViewById(R.id.jutiweizhi);
mTvshijian = findViewById(R.id.shijian);
//初始化地图控制器对象
aMap = mMapView.getMap();
// 设置定位监听
aMap.setLocationSource(this);
// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
aMap.setMyLocationEnabled(true);
// 设置定位的类型为定位模式,有定位、跟随或地图根据面向方向旋转几种
aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
//实例化地理围栏客户端
GeoFenceClient mGeoFenceClient = new GeoFenceClient(getApplicationContext());
//设置希望侦测的围栏触发行为,默认只侦测用户进入围栏的行为
//public static final int GEOFENCE_IN 进入地理围栏
//public static final int GEOFENCE_OUT 退出地理围栏
//public static final int GEOFENCE_STAYED 停留在地理围栏内10分钟
mGeoFenceClient.setActivateAction(GEOFENCE_IN | GEOFENCE_OUT | GEOFENCE_STAYED);
//创建一个中心点坐标
DPoint centerPoint = new DPoint();
//设置中心点纬度
centerPoint.setLatitude(34.749011);
//设置中心点经度
centerPoint.setLongitude(113.602946);
mGeoFenceClient.addGeoFence(centerPoint, 10F, "自有业务Id");
LatLng latLng = new LatLng(34.749011, 113.602946);
aMap.addCircle(new CircleOptions().
center(latLng).
radius(10F).
fillColor(Color.argb(50, 1, 1, 1)).
strokeColor(Color.argb(50, 1, 1, 1)).
strokeWidth(1));
//创建回调监听
GeoFenceListener fenceListenter = new GeoFenceListener() {
@Override
public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
if (i == GeoFence.ADDGEOFENCE_SUCCESS) {//判断围栏是否创建成功
Log.d("dpf", "添加围栏成功!!");
// Toast.makeText(MainActivity.this, "添加围栏成功!!", Toast.LENGTH_SHORT).show();
//geoFenceList是已经添加的围栏列表,可据此查看创建的围栏
IntentFilter filter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(GEOFENCE_BROADCAST_ACTION);
registerReceiver(mGeoFenceReceiver, filter);
} else {
Log.d("dpf", "添加围栏失败!!");
// Toast.makeText(MainActivity.this, "添加围栏失败!!", Toast.LENGTH_SHORT).show();
}
}
};
mGeoFenceClient.setGeoFenceListener(fenceListenter);//设置回调监听
//创建并设置PendingIntent
mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图
mMapView.onResume();
isFisrt = true;
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制
mMapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
mMapView.onSaveInstanceState(outState);
}
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mListener = onLocationChangedListener;
if (mlocationClient == null) {
//初始化定位
mlocationClient = new AMapLocationClient(this);
//初始化定位参数
mLocationOption = new AMapLocationClientOption();
//设置定位回调监听
mlocationClient.setLocationListener(this);
//设置定位模式为AMapLocationMode.Hight_Accuracy,高精度模式。
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms,最低1000ms。
mLocationOption.setInterval(1000);
//设置是否返回地址信息(默认返回地址信息)
mLocationOption.setNeedAddress(true);
//单位是毫秒,默认30000毫秒,建议超时时间不要低于8000毫秒。
mLocationOption.setHttpTimeOut(20000);
//关闭缓存机制
mLocationOption.setLocationCacheEnable(false);
//设置定位参数
mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
// 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后,在合适的生命周期调用onDestroy()方法
// 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
mlocationClient.startLocation();//启动定位
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mListener = null;
if (mlocationClient != null) {
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
}
/**
* 定位成功后回调函数
*/
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (mListener != null && aMapLocation != null) {
if (aMapLocation != null
&& aMapLocation.getErrorCode() == 0) {
mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
int locationType = aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表
double latitude = aMapLocation.getLatitude();//获取纬度
double longitude = aMapLocation.getLongitude();//获取经度
float accuracy = aMapLocation.getAccuracy();//获取精度信息
String address = aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。
String country = aMapLocation.getCountry();//国家信息
String province = aMapLocation.getProvince();//省信息
String city = aMapLocation.getCity();//城市信息
String district = aMapLocation.getDistrict();//城区信息
String street = aMapLocation.getStreet();//街道信息
String streetNum = aMapLocation.getStreetNum();//街道门牌号信息
String cityCode = aMapLocation.getCityCode();//城市编码
String adCode = aMapLocation.getAdCode();//地区编码
String aoiName = aMapLocation.getAoiName();//获取当前定位点的AOI信息
String buildingId = aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
String floor = aMapLocation.getFloor();//获取当前室内定位的楼层
int gpsAccuracyStatus = aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//获取定位时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(aMapLocation.getTime());
df.format(date);
mTvjutiweizhi.setText(province + city + district + street + streetNum + ":\n" + latitude + "," + longitude);
// Log.d("dpf", "时间:" + date.toString());
// Log.d("dpf", "定位:" + latitude + "," + longitude);
if (isFisrt) {
isFisrt = false;
time = aMapLocation.getTime();
new TimeThread().start();//启动线程
}
} else {
String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
Log.e("AmapErr", errText);
}
}
}
//写一个新的线程每隔一秒发送一次消息,这样做会和系统时间相差1秒
public class TimeThread extends Thread {
@Override
public void run() {
super.run();
do {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
}
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
Date d = new Date(time);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.SECOND, 1);
time = c.getTimeInMillis();
mTvshijian.setText(new SimpleDateFormat("HH:mm:ss").format(time));
break;
}
return false;
}
});
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();
//获取围栏行为:
int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
//获取自定义的围栏标识:
String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
//获取围栏ID:
String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
//获取当前有触发的围栏对象:
GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
String zhuangtai = null;
switch (status) {
case GEOFENCE_IN:
zhuangtai = "进入地理围栏";
break;
case GEOFENCE_OUT:
zhuangtai = "退出地理围栏";
break;
case GEOFENCE_STAYED:
zhuangtai = "停留在地理围栏内10分钟";
break;
default:
break;
}
Log.d("yyh", "围栏状态:" + zhuangtai);
mTvwodeweizhi.setText("我的位置:" + zhuangtai);
}
}
};
}
网友评论