LocationUtils.java
3.15 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
package com.chudiangameplay.android.util;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2019/3/5.
*/
public class LocationUtils {
private static Context mContext;
private static LocationUtils mInstance;
public static final String TAG = "LocationUtils";
private LocationUtils(Context mContext) {
this.mContext = mContext;
}
public static LocationUtils getInstance(Context context){
if (mInstance == null){
synchronized (LocationUtils.class){
if (mInstance == null){
mInstance = new LocationUtils(context);
mContext = context;
}
}
initLocation();
}
return mInstance;
}
static LocationManager locationManager;
static Location location;
static String provider;
public static void initLocation() {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
// 获取所有可用的位置提供器
List<String> providerList = locationManager.getProviders(true);
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
} else {
// 当没有可用的位置提供器时,弹出Toast提示用户
return;
}
location = locationManager.getLastKnownLocation(provider);
/*if (location != null) {
// 显示当前设备的位置信息
showLocation(location);
}*/
locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
}
/**
* 获取位置信息
* @return
*/
public static Map<String, String> getLocation() {
return showLocation(location);
}
public static Map<String, String> showLocation(Location location) {
if(location == null)return null;
Map<String, String> map = new HashMap<>();
map.put("longitude", String.valueOf(location.getLongitude()));
map.put("latitude", String.valueOf(location.getLatitude()));
return map;
}
public static LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 更新当前设备的位置信息
showLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
public void remove() {
if (locationManager != null) {
// 关闭程序时将监听器移除
locationManager.removeUpdates(locationListener);
}
}
}