1 import android.content.Context;
2 import android.location.Criteria;
3 import android.location.Location;
4 import android.location.LocationListener;
5 import android.location.LocationManager;
6 import android.util.Log;
7
8 import java.util.List;
9
10 public class LocationUtils {
11
12 /**
13 * 火星坐标
14 */
15 public static LocationManager getLocationManager(Context context) {
16
17 return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
18 }
19
20 /**
21 * GPS定位更精确,缺点是只能在户外使用,耗电严重,并且返回用户位置信息的速度远不能满足用户需求
22 */
23 public static String getGPSProvider() {
24
25 return LocationManager.GPS_PROVIDER;
26 }
27
28 /**
29 * 通过基站和Wi-Fi信号来获取位置信息,室内室外均可用,速度更快,耗电更少
30 */
31 public static String getNETWORKProvider() {
32
33 return LocationManager.NETWORK_PROVIDER;
34 }
35
36 /**
37 * 无源定位 (综合所有的定位方式,得出最准确的结果)
38 */
39 public static String getPassvieProvider() {
40
41 return LocationManager.PASSIVE_PROVIDER;
42 }
43
44 /**
45 * 获取当前环境下最好的Provider
46 */
47 public static String getBestProvider(Context context) {
48
49 Criteria criteria = new Criteria();
50 criteria.setAccuracy(Criteria.ACCURACY_FINE); // 定位的精准度
51 criteria.setAltitudeRequired(false); // 海拔信息是否关注
52 criteria.setBearingRequired(false); // 对周围的事物是否关心
53 criteria.setCostAllowed(false); // 是否支持收费查询
54 criteria.setPowerRequirement(Criteria.POWER_LOW); // 是否耗电
55 criteria.setSpeedRequired(false); // 对速度是否关注
56 // true 代表从打开的设备中查找
57 return getLocationManager(context).getBestProvider(criteria, true);
58 }
59
60 /**
61 * 获取所有的Provider
62 */
63 public static List<String> getAllProviders(Context context) {
64
65 return getLocationManager(context).getAllProviders();
66 }
67
68 /**
69 * 记住转为火星坐标
70 */
71 public static void openUpdate(Context context, String provider, LocationListener mLocationListener) {
72 try {
73 //第二个参数minTime:两次定位用户位置的最小间隔时间(毫秒)
74 //第三个参数minDistance: 两次定位用户位置的最小距离(米)
75 getLocationManager(context).requestLocationUpdates(provider, 0, 0, mLocationListener);
76
77 } catch (SecurityException e) {
78 e.printStackTrace();
79 Log.e("LocationUtils", "openUpdate--->权限拒绝");
80 }
81 }
82
83 /**
84 * 耗电量很大的,不用的话就关掉吧
85 */
86 public static void closeUpdate(Context context, LocationListener mLocationListener) {
87 try {
88 getLocationManager(context).removeUpdates(mLocationListener);
89 } catch (SecurityException e) {
90 e.printStackTrace();
91 Log.e("LocationUtils", "openUpdate--->权限拒绝");
92 }
93 }
94
95 /**
96 * 获取缓存中的位置信息 x = location.getLongitude() , y = location.getLatitude()
97 */
98 public static Location getLastLocation(Context context, String provider) {
99 Location location = new Location(provider);
100 // 默认天安门坐标
101 location.setLatitude(39.90960456049752);
102 location.setLongitude(116.3972282409668);
103 try {
104 location = getLocationManager(context).getLastKnownLocation(provider);
105
106 } catch (SecurityException e) {
107 e.printStackTrace();
108 Log.e("LocationUtils", "openUpdate--->权限拒绝");
109 }
110 return location;
111 }
112
113 }