MainActivity.java
30.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
package com.metroapp;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
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.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.douwan.peacemetro.BuildConfig;
import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.mehcode.reactnative.splashscreen.SplashScreen;
import com.metroapp.bean.BluetoothBean;
import com.metroapp.bean.UserRssi;
import com.metroapp.nativemodules.BluetoothModule;
import com.metroapp.utils.WifiAdmin;
import com.metroapp.utils.XNVersionService;
import com.minew.beacon.BeaconValueIndex;
import com.minew.beacon.BluetoothState;
import com.minew.beacon.MinewBeacon;
import com.minew.beacon.MinewBeaconManager;
import com.minew.beacon.MinewBeaconManagerListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import pub.devrel.easypermissions.EasyPermissions;
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;
@TargetApi(21)
public class MainActivity extends ReactActivity implements EasyPermissions.PermissionCallbacks {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "metroApp";
}
private static final String TAG = "MainActivity";
public static MainActivity _this;
/**
* 蓝牙 uuid 标识
*/
private final String UUID="FDA50693-A4E2-4FB1-AFCF-C6EB07647825";
/**
* 定义接收广播的action字符串
*/
public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";
/**
* 蓝牙相关
*/
private MinewBeaconManager mMinewBeaconManager;
private static final int REQUEST_ENABLE_BT = 2;
private boolean isScanning;
private UserRssi comp = new UserRssi();
/**
* 定位相关
*/
private AMapLocationClient mLocationClient = null;
private GeoFenceClient mGeoFenceClient = null;
private LatLng oldLatLng = null;
/**
* wifi相关
*/
private WifiManager wifiManager;
private WifiAdmin mWifiAdmin;
//wifi扫描结果
private List<ScanResult> mWifiResult ;
//花生地铁wifi扫描结果
private List<ScanResult> sameResult ;
/**
* 从其他应用启动时的信息
*/
public String mobilePhone =null;
public String isFromOtherApp = "0";
public boolean isCameraDenied;
/**
* 数据处理
*/
private List<BluetoothBean> bluetoothBeanList = new ArrayList<>();
//上次存储的结果
private List<BluetoothBean> lastBluetoothBeanList = new ArrayList<>();
// 设备是否支持蓝牙扫描
private boolean canBlueToothScan = true;
//因蓝牙扫描不稳定,所以给3次扫描机会,3此都扫不到,就认为真的没有扫到
public static int RETRY_COUNT = 0;
//重试的上限次数
public final int RETRY_COUNT_LIMIT = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
//闪屏页配置
SplashScreen.show(this, getReactInstanceManager());
super.onCreate(savedInstanceState);
_this = this;
//友盟统计
PushAgent.getInstance(this).onAppStart();
//获取从别的应用跳转过来时传的手机号码
dealDataFromOther();
//电池优化添加白名单
addToWhiteList();
//权限申请
easyPermission();
//初始化wifi
initWifi();
initBluetooth();//初始化蓝牙
//初始化定位
initLocation();
//版本更新检查
versionCheck();
}
private void versionCheck() {
//检测版本更新
VersionParams.Builder builder = new VersionParams.Builder()
.setRequestUrl(BuildConfig.APP_VERSION_URL)
.setService(XNVersionService.class);
AllenChecker.startVersionCheck(MainActivity.this, builder.build());
}
private void initLocation() {
// 高德地图定位
initMapLocation();
//注册蓝牙开关咋状态变化与高德定位的广播
registerReceiver(mReceiver, makeFilter());
startMapLocation();
}
/**
* 监听位置变化
* @return
*/
private IntentFilter makeFilter() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// 高德地图
filter.addAction(GEOFENCE_BROADCAST_ACTION);
return filter;
}
private void easyPermission() {
//所要申请的权限
String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.BLUETOOTH,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.CHANGE_WIFI_STATE
};
easyPermission(perms);
}
private void addToWhiteList() {
//忽略电池优化
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:com.metroapp"));
startActivity(intent);
}catch (Exception e){
}
acquireWakeLock(this);
}
private void dealDataFromOther(){
Intent intent = getIntent();
String scheme = intent.getScheme();
Uri uri = intent.getData();
if (uri != null && scheme.equals("subwayEscort")) {
//获得参数值
isFromOtherApp = "1";
mobilePhone = uri.getQueryParameter("mobilePhone");
}else {
isFromOtherApp = "0";
}
}
private void initWifi(){
//获得系统wifi服务
wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
mWifiAdmin = new WifiAdmin(this);
}
public void initBluetooth(){
if ( !canBlueToothScan){
return;
}
mMinewBeaconManager = MinewBeaconManager.getInstance(this);
BluetoothState bluetoothState = mMinewBeaconManager.checkBluetoothState();
switch (bluetoothState){
case BluetoothStatePowerOn:
Log.d(TAG, "initBluetooth: 蓝牙已开启");
break;
case BluetoothStatePowerOff:
canBlueToothScan = false;
Log.d(TAG, "initBluetooth: 蓝牙已关闭");
break;
case BluetoothStateNotSupported:
canBlueToothScan = false;
Toast.makeText(MainActivity.this,"该手机暂无蓝牙设备",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {//小于18
canBlueToothScan = false;
Toast.makeText(MainActivity.this,"该手机暂不支持蓝牙4.0",Toast.LENGTH_SHORT).show();
return;
}
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
canBlueToothScan = false;
Toast.makeText(this, "该手机暂不支持蓝牙4.0", Toast.LENGTH_SHORT).show();
}
if (mayRequestLocation()){
startBleScan();
}
}
/**
* 蓝牙设备管理类回调接口
*/
private void startBleScan() {
if (isScanning) {
isScanning = false;
if (mMinewBeaconManager != null) {
mMinewBeaconManager.stopScan();
}
} else {
isScanning = true;
try {
mMinewBeaconManager.startScan();
} catch (Exception e) {
e.printStackTrace();
}
}
mMinewBeaconManager.setDeviceManagerDelegateListener(new MinewBeaconManagerListener() {
/**
* if the manager find some new beacon, it will call back this method.
* 发现了新的设备,该函数每3秒回调一次
* @param minewBeacons new beacons the manager scanned
*/
@Override
public void onAppearBeacons(List<MinewBeacon> minewBeacons) {
Log.d(TAG, "onAppearBeacons: "+minewBeacons.size());
}
/**
* if a beacon didn't update data in 10 seconds, we think this beacon is out of rang, the manager will call back this method.
* 设备消失的情况下,每秒钟回调一次。
* @param minewBeacons beacons out of range
*/
@Override
public void onDisappearBeacons(List<MinewBeacon> minewBeacons) {
/*for (MinewBeacon minewBeacon : minewBeacons) {
String deviceName = minewBeacon.getBeaconValue(BeaconValueIndex.MinewBeaconValueIndex_Name).getStringValue();
Toast.makeText(getApplicationContext(), deviceName + " out range", Toast.LENGTH_SHORT).show();
}*/
Log.d(TAG, "onDisappearBeacons: "+minewBeacons.size());
}
/**
* the manager calls back this method every 1 seconds, you can get all scanned beacons.
* 定期回调数据更新函数,每秒钟回调一次
* @param minewBeacons all scanned beacons
*/
@Override
public void onRangeBeacons(List<MinewBeacon> minewBeacons) {
Log.d(TAG, "onRangeBeacons: " + minewBeacons.size());
Collections.sort(minewBeacons, comp);
onBleScanParse(minewBeacons);
}
/**
* the manager calls back this method when BluetoothStateChanged.
*
* @param state BluetoothState
*/
@Override
public void onUpdateState(BluetoothState state) {
switch (state) {
case BluetoothStatePowerOn:
Log.d(TAG, "onUpdateState: 蓝牙已打开");
break;
case BluetoothStatePowerOff:
Log.d(TAG, "onUpdateState: 蓝牙已关闭");
break;
default:
break;
}
}
});
}
/**
* 扫描结果处理
*/
public void onBleScanParse(List<MinewBeacon> minewBeacons){
//没有扫描到任何蓝牙信号
if (minewBeacons ==null || minewBeacons.size() ==0){
return;
}
for (MinewBeacon beacon: minewBeacons) {
String uuid = beacon.getBeaconValue(BeaconValueIndex.MinewBeaconValueIndex_UUID).getStringValue();
//扫描到了地铁蓝牙信号
if (uuid !=null && uuid.equalsIgnoreCase(UUID) ){
Log.d(TAG, "onBleScanParse: 扫描到地铁蓝牙设备!!!");
String major = beacon.getBeaconValue(BeaconValueIndex.MinewBeaconValueIndex_Major).getStringValue();
String minor = beacon.getBeaconValue(BeaconValueIndex.MinewBeaconValueIndex_Minor).getStringValue();
String rssi = beacon.getBeaconValue(BeaconValueIndex.MinewBeaconValueIndex_RSSI).getStringValue();
BluetoothBean bluetoothBean = new BluetoothBean();
bluetoothBean.setDeviceCode(uuid+"|"+major+"|"+minor);
bluetoothBean.setRss(rssi);
bluetoothBeanList.add(bluetoothBean);
}
}
}
private Timer timer = new Timer();
private WritableMap et;
private WifiInfo wifiInfo;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 要做的事情
super.handleMessage(msg);
dealHandleMessage();
}
};
/**
* 处理 handle message
*/
private void dealHandleMessage(){
et = Arguments.createMap();
WritableArray writableArray = new WritableNativeArray();
Log.d(TAG, "dealHandleMessage: " +bluetoothBeanList.size() +" try " + RETRY_COUNT);
if (bluetoothBeanList.size() ==0){
//本次没扫描到,给重试次数,进行传值
if (RETRY_COUNT >= RETRY_COUNT_LIMIT){
//已经重试3此还没有,直接返回空
et.putArray("requestData",writableArray);
}else {
//重试机会不超过3次,取上次的结果,并更新重试次数
for (BluetoothBean bean: lastBluetoothBeanList) {
WritableMap map = new WritableNativeMap();
map.putString("deviceCode",bean.getDeviceCode());
map.putString("RSS",bean.getRss());
map.putString("deviceType","2");
map.putString("deviceMac","");
writableArray.pushMap(map);
}
RETRY_COUNT ++;
}
}else {
//本此扫描到结果,清空上次的值,并重新赋值,以及重新计算重试数
lastBluetoothBeanList.clear();
lastBluetoothBeanList.addAll(bluetoothBeanList);
RETRY_COUNT = 0;
for (BluetoothBean bean: bluetoothBeanList) {
WritableMap map = new WritableNativeMap();
map.putString("deviceCode",bean.getDeviceCode());
map.putString("RSS",bean.getRss());
map.putString("deviceType","2");
map.putString("deviceMac","");
writableArray.pushMap(map);
}
et.putArray("requestData",writableArray);
}
//连接的wifi
wifiInfo = wifiManager.getConnectionInfo();
int ip = 0;
if (wifiInfo !=null){
ip = wifiInfo.getIpAddress();
}
//扫描wifi
mWifiResult = mWifiAdmin.getScanResult();
sameResult = new ArrayList<>();
ScanResult currentResult = null;
if (mWifiResult !=null && mWifiResult.size() >0){
for (int i = 0; i < mWifiResult.size() ; i++) {
//花生地铁WiFi
if (mWifiResult.get(i).SSID.equals("\""+"花生地铁WiFi" +"\"") || mWifiResult.get(i).SSID.equals("花生地铁WiFi")){
sameResult.add(mWifiResult.get(i));
}
}
}
if (sameResult !=null && sameResult.size() >0){
//进行强度比较,那个强度强,取哪个
currentResult = sameResult.get(0);
for (int i = 0; i < sameResult.size(); i++) {
int currentRssi = currentResult.level;
int sameRssi = sameResult.get(i).level;
if (currentRssi < sameRssi){
currentResult = sameResult.get(i);
}
}
}
//当前有wifi信号
if (currentResult !=null){
WritableMap map = new WritableNativeMap();
map.putString("wRSS",currentResult.level+"");
map.putString("wBSSID",currentResult.BSSID+"");
map.putString("wIP",getWifiIP(ip));
et.putMap("wifiData",map);
}
BluetoothModule.sendEvent("BlueToolData",et);
bluetoothBeanList.clear();
}
public static String getWifiIP (int i){
String ip;
ip = (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + (i >> 24 & 0xFF);
return ip;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (timer !=null){
timer.cancel();
timer = null;
}
if (isScanning) {
mMinewBeaconManager.stopScan();
}
isFromOtherApp = "0";
releaseWakeLock();
if (mReceiver !=null){
unregisterReceiver(mReceiver);
mReceiver =null;
}
}
/**
* 开启定时器
* @param s 秒
*/
public void startTimer(String s){
if (s == null || s.equals("")){
return;
}
if (timer ==null) {
timer = new Timer();
}
try {//防止重复开定时器时报错
timer.schedule(new task(), 0, Integer.parseInt(s)*1000);
Log.d("!!!!",Integer.parseInt(s)*1000+"");
}catch (Exception e){
e.printStackTrace();
}
// }
}
/**
* 关闭定时器
*/
public void stopTimer(){
if (timer !=null){
timer.cancel();
timer.purge();
timer = null;
}
}
class task extends TimerTask {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
// 高德定位
case GEOFENCE_BROADCAST_ACTION:
//解析广播内容
//获取Bundle
Bundle bundle = intent.getExtras();
//获取自定义的围栏标识:
String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
String poiName = "";
////获取自定义的围栏标识:
// 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);
if (null != fence && null != fence.getPoiItem()){
poiName = fence.getPoiItem().getPoiName();
}
WritableMap map = new WritableNativeMap();
if(poiName.length() > 0){
map.putString("requestData",poiName);
}
int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
switch (status){
case GEOFENCE_IN:
Log.d(LOG_TAG_LOCATION,"进地铁站");
if(null != map && map.hasKey("requestData")){
BluetoothModule.sendEvent("locationData",map);
}
break;
case GEOFENCE_OUT:
Log.d(LOG_TAG_LOCATION,"出地铁站");
// if(null != map && map.hasKey("requestData")){
// BluetoothModule.sendEvent("locationData",map);
// }
break;
case GEOFENCE_STAYED:
Log.d(LOG_TAG_LOCATION,"在地铁站");
if(null != map && map.hasKey("requestData")){
BluetoothModule.sendEvent("locationData",map);
}
BluetoothModule.sendEvent("locationData",map);
break;
default:
break;
}
break;
default:
break;
}
}
};
//android 电源管理
private PowerManager.WakeLock wakeLock;
private void acquireWakeLock(Context context) {
if (wakeLock == null) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, context.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
}
}
/**
* android6.0运行时权限处理
*/
public static void easyPermission( String[] perms){
if (EasyPermissions.hasPermissions(_this, perms)) {//检查是否获取该权限
} else {
//第二个参数是被拒绝后再次申请该权限的解释
//第三个参数是请求码
//第四个参数是要申请的权限
EasyPermissions.requestPermissions(_this, "平安地铁需要获取必要的权限才能正常使用哦", 0, perms);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//把申请权限的回调交由EasyPermissions处理
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
//下面两个方法是实现EasyPermissions的EasyPermissions.PermissionCallbacks接口
//分别返回授权成功和失败的权限
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
if (perms.contains(Manifest.permission.CAMERA) && perms.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
isCameraDenied = false;
}
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
if (perms.contains(Manifest.permission.CAMERA) || perms.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
isCameraDenied = true;
}
}
static final String LOG_TAG_LOCATION = "locationLog";
private void initMapLocation(){
if (null == mLocationClient) {
//初始化client
mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位参数
mLocationClient.setLocationOption(getDefaultOption());
// 设置定位监听
mLocationClient.setLocationListener(new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation loc) {
Log.d(LOG_TAG_LOCATION, "onLocationChanged: ");
try {
if (null != loc) {
//可在其中解析amapLocation获取相应内容。
if (loc.getErrorCode() == 0) {
LatLng newLatLng = new LatLng(loc.getLatitude(),loc.getLongitude());
if (null == oldLatLng){
Log.d(LOG_TAG_LOCATION,"定位成功-初次定位");
oldLatLng = newLatLng;
//创建一个中心点坐标
DPoint centerPoint = new DPoint();
centerPoint.setLatitude(loc.getLatitude());
centerPoint.setLongitude(loc.getLongitude());
addGeoFence(centerPoint);
}else{
float distance = AMapUtils.calculateLineDistance(newLatLng,oldLatLng);
distance = Math.round(distance);// 四舍五入
if (distance > 50){
Log.d(LOG_TAG_LOCATION,"定位成功-累计位移超过50米,重新取得地理围栏");
oldLatLng = newLatLng;
//创建一个中心点坐标
DPoint centerPoint = new DPoint();
centerPoint.setLatitude(loc.getLatitude());
centerPoint.setLongitude(loc.getLongitude());
addGeoFence(centerPoint);
}else{
Log.d(LOG_TAG_LOCATION,"定位成功-但位移在50米内,不更新地理围栏");
}
}
//创建一个中心点坐标
// DPoint centerPoint = new DPoint();
// centerPoint.setLatitude(loc.getLatitude());
// centerPoint.setLongitude(loc.getLongitude());
// addGeoFence(centerPoint);
} else {
// 定位返回的loc包含失败信息
Log.d(LOG_TAG_LOCATION,"定位返回的loc包含失败信息");
}
}else{
// 定位返回的loc为空
Log.d(LOG_TAG_LOCATION,"定位返回的loc为空");
}
} catch (Exception ex) {
Log.d(LOG_TAG_LOCATION,"定位捕捉到异常");
ex.printStackTrace();
}
}
});
}
}
/**
* 默认的定位参数
*/
private AMapLocationClientOption getDefaultOption() {
AMapLocationClientOption mOption = new AMapLocationClientOption();
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
mOption.setGpsFirst(true);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
mOption.setInterval(5000);//可选,设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(false);//可选,设置是否单次定位。默认是false
mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
mOption.setMockEnable(true);//如果您希望位置被模拟,请通过setMockEnable(true);方法开启允许位置模拟
mOption.setLocationCacheEnable(false);//关闭缓存机制
return mOption;
}
private void addGeoFence(DPoint point){
if(null == mGeoFenceClient){
mGeoFenceClient = new GeoFenceClient(getApplicationContext());
//设置希望侦测的围栏触发行为,默认只侦测用户进入围栏的行为
mGeoFenceClient.setActivateAction(GEOFENCE_IN|GEOFENCE_OUT|GEOFENCE_STAYED);
mGeoFenceClient.setGeoFenceListener(new GeoFenceListener() {
@Override
public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
if(i == GeoFence.ADDGEOFENCE_SUCCESS){
//添加围栏成功!!
//geoFenceList是已经添加的围栏列表,可据此查看创建的围栏
Log.d(LOG_TAG_LOCATION,"添加围栏成功!!");
} else {
//添加围栏失败!!
Log.d(LOG_TAG_LOCATION,"添加围栏失败!!");
}
}
});
// 创建并设置PendingIntent
mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
}else{
//清除所有围栏
// mGeoFenceClient.removeGeoFence();
}
mGeoFenceClient.addGeoFence("地铁站","150500",point,150F,1,"poi_1");
}
public void startMapLocation(){
// 启动定位
if(mLocationClient.isStarted() == false){
mLocationClient.startLocation();
}
}
private boolean mayRequestLocation() {
if (Build.VERSION.SDK_INT >= 23) {
String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION};
if (EasyPermissions.hasPermissions(this, perms)) {
return true;
} else {
EasyPermissions.requestPermissions(this, "动态请求权限", 0, perms);
return false;
}
}else{
return true;
}
}
}