MainActivity.java
32.3 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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
package com.metroapp;
import android.Manifest;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
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.support.annotation.RequiresApi;
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.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.ResultBean;
import com.metroapp.constant.Constant;
import com.metroapp.nativemodules.BluetoothModule;
import com.metroapp.utils.WifiAdmin;
import com.metroapp.utils.XNVersionService;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import java.util.ArrayList;
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(22)
public class MainActivity extends ReactActivity implements EasyPermissions.PermissionCallbacks {
// 用于蓝牙扫描
private static final int REQUEST_COARSE_LOCATION = 0;
/**
* 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";
}
//定义接收广播的action字符串
public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";
//声明AMapLocationClient类对象
private AMapLocationClient mLocationClient = null;
private GeoFenceClient mGeoFenceClient = null;
private LatLng oldLatLng = null;
// 本地蓝牙适配器
// final BluetoothManager bluetoothManager =
// (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
private BluetoothAdapter mBluetoothAdapter;
public String mobilePhone =null;
public String isFromOtherApp = "0";
public boolean isCameraDenied;
//wifi相关
private WifiManager wifiManager;
//wifi扫描结果
private List<ScanResult> mWifiResult ;
//花生地铁wifi扫描结果
private List<ScanResult> sameResult ;
private WifiAdmin mWifiAdmin;
//需要传给接口的数据
private ResultBean apibean = new ResultBean();
private List<BluetoothBean> bluetoothBeanList = new ArrayList<>();
public static MainActivity _this;
// 设备是否支持蓝牙扫描
private boolean canBlueToothScan = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this, getReactInstanceManager());
super.onCreate(savedInstanceState);
_this = this;
PushAgent.getInstance(this).onAppStart();
//获取从别的应用跳转过来时传的手机号码
{
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";
}
}
//获得系统wifi服务
wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
//忽略电池优化
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:com.metroapp"));
startActivity(intent);
}catch (Exception e){
}
//所要申请的权限
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);
acquireWakeLock(this);
//检测版本更新
VersionParams.Builder builder = new VersionParams.Builder()
.setRequestUrl(Constant.GET_APP_VERSION_URL)
.setService(XNVersionService.class);
AllenChecker.startVersionCheck(MainActivity.this, builder.build());
mWifiAdmin = new WifiAdmin(this);
initBluetooth();//初始化蓝牙
// 高德地图定位
initMapLocation();
registerReceiver(mReceiver, makeFilter()); //注册蓝牙开关咋状态变化与高德定位的广播
startMapLocation();
}
@TargetApi(22)
public void initBluetooth(){
if(canBlueToothScan == false){
stopBlueToothTimer();
return;
}
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);//这里与标准蓝牙略有不同
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null){
canBlueToothScan = false;
Toast.makeText(MainActivity.this,"该手机暂无蓝牙设备",Toast.LENGTH_SHORT).show();
return;
}
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();
finish();
}
if (mayRequestLocation()){
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
// 7.0后需要使用新方法
if (Build.VERSION.SDK_INT >= 23){
BluetoothLeScanner bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
// if(bleScanner != null){
// bleScanner.startScan(scanCallback);
// }else{
mBluetoothAdapter.startLeScan(mLeScanCallback);
// }
}else{
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
}
ScanCallback scanCallback = new ScanCallback() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onScanResult(int callbackType, android.bluetooth.le.ScanResult result) {
super.onScanResult(callbackType,result);
BluetoothDevice device = result.getDevice();
int rssi = result.getRssi();//获取rssi
onLeScanParse(device,rssi,result.getScanRecord().getBytes());
}
};
private int lastRSS =-9999;//上一个rss值
private String UUID="FDA50693-A4E2-4FB1-AFCF-C6EB07647825";
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
onLeScanParse(device,rssi,scanRecord);
}
};
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
/**
* 扫描结果处理
*/
public void onLeScanParse(final BluetoothDevice device, final int rssi,
final byte[] scanRecord){
// System.out.println("========onLeScanParse=======" + rssi);
String scanRecordHex=bytesToHex(scanRecord);
String hexString = scanRecordHex.substring(18,50);
// ibeacon的UUID值
String uuid = hexString.substring(0, 8) + "-"
+ hexString.substring(8, 12) + "-"
+ hexString.substring(12, 16) + "-"
+ hexString.substring(16, 20) + "-"
+ hexString.substring(20, 32);
int major = Integer.valueOf(scanRecordHex.substring(50,54),16);
int minor = Integer.valueOf(scanRecordHex.substring(54,58),16);
String ibeaconName = device.getName() == null ? "null" : device.getName();
//扫描到了
// System.out.println("========onLeScanParse=======" + UUID + " "+rssi+ " " + (uuid.equalsIgnoreCase(UUID) && rssi != 0));
if (uuid.equalsIgnoreCase(UUID) && rssi != 0 ){
// 扫描到就先关闭扫描,持续扫描三五分钟后就没反应了,可能是耗电的关系被系统禁了
stopBlueToothScan();
Log.i("!!!!!!!","扫描到蓝牙设备");
BluetoothBean bluetoothBean = new BluetoothBean();
bluetoothBean.setDeviceCode(uuid+"|"+major+"|"+minor);
bluetoothBean.setRss(rssi+"");
bluetoothBeanList.add(bluetoothBean);
// Toast.makeText(getApplicationContext(),"扫描到蓝牙设备",Toast.LENGTH_SHORT).show();
lastRSS = rssi;
// 通过定时器轮询方式开启蓝牙扫描
startBlueToothTimer();
}
}
static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
// 用于蓝牙扫描轮询的定时器
private Timer blueToothScanTimer = null;
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);
if (msg.what == 1){
et = Arguments.createMap();
WritableArray writableArray = new WritableNativeArray();
List<BluetoothBean> temp = new ArrayList<>();
// System.arraycopy(bluetoothBeanList, 0, temp, 0, bluetoothBeanList.size());
System.out.println("===========1111======" +bluetoothBeanList.size());
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);
}
System.out.println("============"+currentResult !=null);
BluetoothModule.sendEvent("BlueToolData",et);
bluetoothBeanList.clear();
resetData();
}
if (msg.what == 2) {
// 触发蓝牙扫描
startBlueToothScan();
}
}
};
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;
lastRSS =-9999;
}
stopBlueToothTimer();
isFromOtherApp = "0";
releaseWakeLock();
if (mReceiver !=null){
unregisterReceiver(mReceiver);
mReceiver =null;
}
}
public void resetData(){
lastRSS =-9999;
}
// 开启蓝牙扫描轮询Timer
private void startBlueToothTimer(){
if(blueToothScanTimer == null){
blueToothScanTimer = new Timer();
try {//防止重复开定时器时报错
blueToothScanTimer.schedule(new blueToothScanTask(), 0, 10*1000);
}catch (Exception e){
e.printStackTrace();
}
}
}
// 关闭蓝牙扫描轮询Timer
private void stopBlueToothTimer(){
if (blueToothScanTimer !=null){
blueToothScanTimer.cancel();
blueToothScanTimer.purge();
blueToothScanTimer = 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);
}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);
}
}
// 蓝牙扫描轮询定时器定时任务
class blueToothScanTask extends TimerTask {
public void run() {
Message message = new Message();
message.what = 2;
handler.sendMessage(message);
}
}
/**
* 监听蓝牙开关状态
* @return
*/
private IntentFilter makeFilter() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);// 蓝牙开关
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(GEOFENCE_BROADCAST_ACTION);// 高德地图
return filter;
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
switch (blueState) {
case BluetoothAdapter.STATE_ON:
//当蓝牙重新开启式必须重新设置mLeScanCallback,要不然不会重新扫描
if (mBluetoothAdapter.isEnabled()){
mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
onLeScanParse(bluetoothDevice,i,bytes);
}
};
// 7.0后需要使用新方法
if (Build.VERSION.SDK_INT >= 23){
BluetoothLeScanner bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (bleScanner != null){
bleScanner.startScan(scanCallback);
}else{
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}else{
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
break;
case BluetoothAdapter.STATE_OFF:
// 7.0后需要使用新方法
if (Build.VERSION.SDK_INT >= 23){
BluetoothLeScanner bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (bleScanner != null){
bleScanner.stopScan(scanCallback);
}else{
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}else{
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
mLeScanCallback =null;
stopBlueToothTimer();
break;
default:
break;
}
break;
// 高德定位
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 startBlueToothScan(){
initBluetooth();
}
private void stopBlueToothScan(){
if (Build.VERSION.SDK_INT >= 23){
BluetoothLeScanner bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (bleScanner != null){
bleScanner.stopScan(scanCallback);
}else{
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}else{
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
mLeScanCallback =null;
}
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;
}
}
}