转载自:http://blog.csdn.net/luosiye312/article/details/50562309#comments

  Android 定位大致分为三大类:GPS定位;Network定位;AGPS定位。而Network又细分为WIFI定位和基站定位。下面详细讲解每种定位:

  Android GPS:需要GPS硬件支持,直接和卫星交互来获取当前经纬度。

  优点:速度快、精度高、可在无网络情况下使用。

  缺点:首次连接时间长、只能在户外已经开阔地使用,设备上方有遮挡物就不行了、比较耗电。

  代码:

[java] view plaincopyprint?
  1. /**
  2. * 通过LocationListener来获取Location信息
  3. */
  4. public static void formListenerGetLocation(){
  5. locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
  6. locationListener = new LocationListener() {
  7. @Override
  8. public void onLocationChanged(Location location) {
  9. //位置信息变化时触发
  10. Log4Lsy.i(TAG, ”纬度:”+location.getLatitude());
  11. Log4Lsy.i(TAG, ”经度:”+location.getLongitude());
  12. Log4Lsy.i(TAG, ”海拔:”+location.getAltitude());
  13. Log4Lsy.i(TAG, ”时间:”+location.getTime());
  14. }
  15. @Override
  16. public void onStatusChanged(String provider, int status,Bundle extras) {
  17. //GPS状态变化时触发
  18. }
  19. @Override
  20. public void onProviderEnabled(String provider) {
  21. //GPS禁用时触发
  22. }
  23. @Override
  24. public void onProviderDisabled(String provider) {
  25. //GPS开启时触发
  26. }
  27. };
  28. /**
  29. * 绑定监听
  30. * 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种,前者是GPS,后者是GPRS以及WIFI定位
  31. * 参数2,位置信息更新周期.单位是毫秒
  32. * 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息
  33. * 参数4,监听
  34. * 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新
  35. */
  36. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
  37. }
/*** 通过LocationListener来获取Location信息*/public static void formListenerGetLocation(){locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);locationListener = new LocationListener() {@Overridepublic void onLocationChanged(Location location) {//位置信息变化时触发Log4Lsy.i(TAG, "纬度:"+location.getLatitude());Log4Lsy.i(TAG, "经度:"+location.getLongitude());Log4Lsy.i(TAG, "海拔:"+location.getAltitude());Log4Lsy.i(TAG, "时间:"+location.getTime());}@Overridepublic void onStatusChanged(String provider, int status,Bundle extras) {//GPS状态变化时触发}@Overridepublic void onProviderEnabled(String provider) {//GPS禁用时触发}@Overridepublic void onProviderDisabled(String provider) {//GPS开启时触发 }};/*** 绑定监听* 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种,前者是GPS,后者是GPRS以及WIFI定位* 参数2,位置信息更新周期.单位是毫秒* 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息* 参数4,监听* 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新*/locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}

   基站定位:基站定位的方式有多种,一般手机附近的三个基站进行三角定位,由于每个基站的位置是固定的,利用电磁波在这三个基站间中转所需要时间来算出手机所在的坐标,还有一种则是,利用电磁波在这三个基站间中转所需要时间来算出手机所在的坐标;第二种则是利用获取最近的基站的信息,其中包括基站 id,location area code、mobile country code、mobile network code和信号强度,将这些数据发送到google的定位web服务里,就能拿到当前所在的位置信息。

  优点:受环境的影响情况较小,不管在室内还是人烟稀少的地方都能用,只要有基站。

  缺点: 首先需要消耗流量、其实精度没有GPS那么准确,大概在十几米到几十米之间、

  代码:

[java] view plaincopyprint?
  1. /**
  2. * 主动获取Location,通过以下方法获取到的是最后一次定位信息。
  3. * 注意:Location location=new Location(LocationManager.GPS_PROVIDER)方式获取的location的各个参数值都是为0。
  4. */
  5. public static void getLocation(){
  6. locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
  7. Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  8. Log4Lsy.i(TAG, ”纬度:”+location.getLatitude());
  9. Log4Lsy.i(TAG, ”经度:”+location.getLongitude());
  10. Log4Lsy.i(TAG, ”海拔:”+location.getAltitude());
  11. Log4Lsy.i(TAG, ”时间:”+location.getTime());
  12. }
/*** 主动获取Location,通过以下方法获取到的是最后一次定位信息。* 注意:Location location=new Location(LocationManager.GPS_PROVIDER)方式获取的location的各个参数值都是为0。*/public static void getLocation(){locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);Log4Lsy.i(TAG, "纬度:"+location.getLatitude());Log4Lsy.i(TAG, "经度:"+location.getLongitude());Log4Lsy.i(TAG, "海拔:"+location.getAltitude());Log4Lsy.i(TAG, "时间:"+location.getTime());}

   WIFI定位:Wifi定位是根据一个固定的WifiMAC地址,通过收集到的该Wifi热点的位置,然后访问网络上的定位服务以获得经纬度坐标。

  优点:和基站定位一样,它的优势在于收环境影响较小,只要有Wifi的地方可以使用。

  缺点:需要有wifi、精度不准。

  代码:

[java] view plaincopyprint?
  1. /**
  2. * 通过WIFI获取定位信息
  3. */
  4. public static void fromWIFILocation(){
  5. //WIFI的MAC地址
  6. WifiManager manager = (WifiManager)mActivity.getSystemService(Context.WIFI_SERVICE);
  7. String wifiAddress = manager.getConnectionInfo().getBSSID();
  8. //根据WIFI信息定位
  9. DefaultHttpClient client = new DefaultHttpClient();
  10. HttpPost post = new HttpPost(“http://www.google.com/loc/json”);
  11. JSONObject holder = new JSONObject();
  12. try {
  13. holder.put(”version” , “1.1.0”);
  14. holder.put( ”host” , “maps.google.com”);
  15. JSONObject data;
  16. JSONArray array = new JSONArray();
  17. if(wifiAddress!=null&&!wifiAddress.equals(“”)){
  18. data = new JSONObject();
  19. data.put(”mac_address”, wifiAddress);
  20. data.put(”signal_strength”, 8);
  21. data.put(”age”, 0);
  22. array.put(data);
  23. }
  24. holder.put(”wifi_towers”,array);
  25. StringEntity se = new StringEntity(holder.toString());
  26. post.setEntity(se);
  27. HttpResponse resp =client.execute(post);
  28. int state =resp.getStatusLine().getStatusCode();
  29. if (state == HttpStatus.SC_OK) {
  30. HttpEntity entity =resp.getEntity();
  31. if (entity != null) {
  32. BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
  33. StringBuffer sb = new StringBuffer();
  34. String resute = ”“;
  35. while ((resute =br.readLine()) != null) {
  36. sb.append(resute);
  37. }
  38. br.close();
  39. data = new JSONObject(sb.toString());
  40. data = (JSONObject)data.get(”location”);
  41. Location loc = new Location(LocationManager.NETWORK_PROVIDER);
  42. loc.setLatitude((Double)data.get(”latitude”));
  43. loc.setLongitude((Double)data.get(”longitude”));
  44. //其他信息同样获取方法
  45. Log4Lsy.i(TAG, ”latitude ===== ”+(Double)data.get(“latitude”));
  46. Log4Lsy.i(TAG, ”longitude ===== ”+(Double)data.get(“longitude”));
  47. }
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
/*** 通过WIFI获取定位信息*/public static void fromWIFILocation(){//WIFI的MAC地址WifiManager manager = (WifiManager)mActivity.getSystemService(Context.WIFI_SERVICE); String wifiAddress = manager.getConnectionInfo().getBSSID(); //根据WIFI信息定位DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.google.com/loc/json"); JSONObject holder = new JSONObject();try {holder.put("version" , "1.1.0");holder.put( "host" , "maps.google.com"); JSONObject data;               JSONArray array = new JSONArray();if(wifiAddress!=null&&!wifiAddress.equals("")){data = new JSONObject(); data.put("mac_address", wifiAddress); data.put("signal_strength", 8); data.put("age", 0); array.put(data); }holder.put("wifi_towers",array); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se);HttpResponse resp =client.execute(post); int state =resp.getStatusLine().getStatusCode(); if (state == HttpStatus.SC_OK) {HttpEntity entity =resp.getEntity(); if (entity != null) {BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));StringBuffer sb = new StringBuffer(); String resute = "";while ((resute =br.readLine()) != null) {                     sb.append(resute);                   }                   br.close(); data = new JSONObject(sb.toString()); data = (JSONObject)data.get("location"); Location loc = new Location(LocationManager.NETWORK_PROVIDER);loc.setLatitude((Double)data.get("latitude"));                   loc.setLongitude((Double)data.get("longitude"));//其他信息同样获取方法Log4Lsy.i(TAG, "latitude ===== "+(Double)data.get("latitude"));Log4Lsy.i(TAG, "longitude ===== "+(Double)data.get("longitude"));}}} catch (Exception e) {e.printStackTrace();}}

关于WIFI定位,此处有一篇非常详尽的文章,大家可参考此文章: http://www.jb51.net/article/52673.htm
   AGPS定位:AssistedGPS(辅助全球卫星定位系统), 是结合GSM或GPRS与传统卫星定位,利用基地台代送辅助卫星信息,以缩减GPS芯片获取卫星信号的延迟时间,受遮盖的室内也能借基地台讯号弥补,减轻GPS芯片对卫星的依赖度。和纯GPS、基地台三角定位比较,AGPS能提供范围更广、更省电、速度更快的定位服务,理想误差范围在10公尺以内,日本和美国都已经成熟运用AGPS于LBS服务(Location Based Service,基于位置的服务)。AGPS技术是一种结合了网络基站信息和GPS信息对移动台进行定位的技术,可以在GSM/GPRS、WCDMA和CDMA2000网络中使进行用。该技术需要在手机内增加GPS接收机模块,并改造手机的天线,同时要在移动网络上加建位置服务器、差分GPS基准站等设备。AGPS解决方案的优势主要体现在其定位精度上,在室外等空旷地区,其精度在正常的GPS工作环境下,可以达到10米左右,堪称目前定位精度最高的一种定位技术。该技术的另一优点为:首次捕获GPS信号的时间一般仅需几秒,不像GPS的首次捕获时间可能要1分多钟,但很明显,他的硬件要求很高,造价自然高。

  代码:AGPS的定位原理和GPS原理是差不多的,所以代码其实也是用GPS的定位方式就OK了。

最后,把我写的LocationUtil类贴上。

[java] view plaincopyprint?
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.HttpStatus;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.DefaultHttpClient;
  12. import org.json.JSONArray;
  13. import org.json.JSONObject;
  14. import android.annotation.SuppressLint;
  15. import android.annotation.TargetApi;
  16. import android.app.Activity;
  17. import android.app.AlertDialog;
  18. import android.content.Context;
  19. import android.content.DialogInterface;
  20. import android.content.Intent;
  21. import android.location.GpsSatellite;
  22. import android.location.GpsStatus;
  23. import android.location.Location;
  24. import android.location.LocationListener;
  25. import android.location.LocationManager;
  26. import android.net.wifi.WifiManager;
  27. import android.os.Build;
  28. import android.os.Bundle;
  29. import android.provider.Settings;
  30. import com.function.utils.Log4Lsy;
  31. /**
  32. * Android API本身提供的定位功能,也是GPS定位。
  33. * GPS定位,是基于卫星定位。它受环境影响很大。并且是单向定位,也就是只有你自己知道你的地理坐标。
  34. * @author LuoSiye
  35. */
  36. @TargetApi(Build.VERSION_CODES.CUPCAKE)
  37. @SuppressLint(“NewApi”)
  38. public class LocationUtil{
  39. private static final String TAG = “LocationUtil”;
  40. private static LocationUtil instance;
  41. private static Activity mActivity;
  42. private static LocationManager locationManager;
  43. private static LocationListener locationListener;
  44. public static LocationUtil getInstance(Activity activity){
  45. mActivity = activity;
  46. if(instance==null){
  47. instance = new LocationUtil();
  48. }
  49. locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
  50. return instance;
  51. }
  52. /**
  53. * 判断GPS导航是否打开.
  54. * false:弹窗提示打开,不建议采用在后台强行开启的方式。
  55. * true:不做任何处理
  56. * @return
  57. */
  58. public static void isOpenGPS(){
  59. if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)){
  60. AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
  61. dialog.setMessage(”GPS未打开,是否打开?”);
  62. dialog.setPositiveButton(”确定”, new DialogInterface.OnClickListener() {
  63. @Override
  64. public void onClick(DialogInterface dialog, int which) {
  65. Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  66. // 设置完成后返回到原来的界面
  67. mActivity.startActivityForResult(intent, 0);
  68. }
  69. });
  70. dialog.setNegativeButton(”取消”, new DialogInterface.OnClickListener() {
  71. @Override
  72. public void onClick(DialogInterface dialog, int which) {
  73. dialog.dismiss();
  74. }
  75. });
  76. dialog.show();
  77. }
  78. }
  79. /**
  80. * 通过LocationListener来获取Location信息
  81. */
  82. public static void formListenerGetLocation(){
  83. locationListener = new LocationListener() {
  84. @Override
  85. public void onLocationChanged(Location location) {
  86. //位置信息变化时触发
  87. Log4Lsy.i(TAG, ”纬度:”+location.getLatitude());
  88. Log4Lsy.i(TAG, ”经度:”+location.getLongitude());
  89. Log4Lsy.i(TAG, ”海拔:”+location.getAltitude());
  90. Log4Lsy.i(TAG, ”时间:”+location.getTime());
  91. }
  92. @Override
  93. public void onStatusChanged(String provider, int status,Bundle extras) {
  94. //GPS状态变化时触发
  95. }
  96. @Override
  97. public void onProviderEnabled(String provider) {
  98. //GPS禁用时触发
  99. }
  100. @Override
  101. public void onProviderDisabled(String provider) {
  102. //GPS开启时触发
  103. }
  104. };
  105. /**
  106. * 绑定监听
  107. * 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种,前者是GPS,后者是GPRS以及WIFI定位
  108. * 参数2,位置信息更新周期.单位是毫秒
  109. * 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息
  110. * 参数4,监听
  111. * 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新
  112. */
  113. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
  114. }
  115. /**
  116. * 主动获取Location,通过以下方法获取到的是最后一次定位信息。
  117. * 注意:Location location=new Location(LocationManager.GPS_PROVIDER)方式获取的location的各个参数值都是为0。
  118. */
  119. public static void getLocation(){
  120. Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  121. Log4Lsy.i(TAG, ”纬度:”+location.getLatitude());
  122. Log4Lsy.i(TAG, ”经度:”+location.getLongitude());
  123. Log4Lsy.i(TAG, ”海拔:”+location.getAltitude());
  124. Log4Lsy.i(TAG, ”时间:”+location.getTime());
  125. }
  126. /**
  127. * 获取GPS状态监听,包括GPS启动、停止、第一次定位、卫星变化等事件。
  128. */
  129. public static void getStatusListener(){
  130. GpsStatus.Listener listener = new GpsStatus.Listener(){
  131. @Override
  132. public void onGpsStatusChanged(int event) {
  133. if(event==GpsStatus.GPS_EVENT_FIRST_FIX){
  134. //第一次定位
  135. }else if(event==GpsStatus.GPS_EVENT_SATELLITE_STATUS){
  136. //卫星状态改变
  137. GpsStatus gpsStauts= locationManager.getGpsStatus(null); // 取当前状态
  138. int maxSatellites = gpsStauts.getMaxSatellites(); //获取卫星颗数的默认最大值
  139. Iterator<GpsSatellite> it = gpsStauts.getSatellites().iterator();//创建一个迭代器保存所有卫星
  140. int count = 0;
  141. while (it.hasNext() && count <= maxSatellites) {
  142. count++;
  143. GpsSatellite s = it.next();
  144. }
  145. Log4Lsy.i(TAG, ”搜索到:”+count+“颗卫星”);
  146. }else if(event==GpsStatus.GPS_EVENT_STARTED){
  147. //定位启动
  148. }else if(event==GpsStatus.GPS_EVENT_STOPPED){
  149. //定位结束
  150. }
  151. }
  152. };
  153. //绑定
  154. locationManager.addGpsStatusListener(listener);
  155. }
  156. /**
  157. * 获取所有卫星状态
  158. * @return
  159. */
  160. public static List<GpsSatellite> getGpsStatus(){
  161. List<GpsSatellite> result = new ArrayList<GpsSatellite>();
  162. GpsStatus gpsStatus = locationManager.getGpsStatus(null); // 取当前状态
  163. //获取默认最大卫星数
  164. int maxSatellites = gpsStatus.getMaxSatellites();
  165. //获取第一次定位时间(启动到第一次定位)
  166. int costTime=gpsStatus.getTimeToFirstFix();
  167. Log4Lsy.i(TAG, ”第一次定位时间:”+costTime);
  168. //获取卫星
  169. Iterable<GpsSatellite> iterable=gpsStatus.getSatellites();
  170. //一般再次转换成Iterator
  171. Iterator<GpsSatellite> itrator=iterable.iterator();
  172. int count = 0;
  173. while (itrator.hasNext() && count <= maxSatellites){
  174. count++;
  175. GpsSatellite s = itrator.next();
  176. result.add(s);
  177. }
  178. return result;
  179. }
  180. /**
  181. * 某一个卫星的信息.
  182. * @param gpssatellite
  183. */
  184. public static void getGpsStatelliteInfo(GpsSatellite gpssatellite){
  185. //卫星的方位角,浮点型数据
  186. Log4Lsy.i(TAG, ”卫星的方位角:”+gpssatellite.getAzimuth());
  187. //卫星的高度,浮点型数据
  188. Log4Lsy.i(TAG, ”卫星的高度:”+gpssatellite.getElevation());
  189. //卫星的伪随机噪声码,整形数据
  190. Log4Lsy.i(TAG, ”卫星的伪随机噪声码:”+gpssatellite.getPrn());
  191. //卫星的信噪比,浮点型数据
  192. Log4Lsy.i(TAG, ”卫星的信噪比:”+gpssatellite.getSnr());
  193. //卫星是否有年历表,布尔型数据
  194. Log4Lsy.i(TAG, ”卫星是否有年历表:”+gpssatellite.hasAlmanac());
  195. //卫星是否有星历表,布尔型数据
  196. Log4Lsy.i(TAG, ”卫星是否有星历表:”+gpssatellite.hasEphemeris());
  197. //卫星是否被用于近期的GPS修正计算
  198. Log4Lsy.i(TAG, ”卫星是否被用于近期的GPS修正计算:”+gpssatellite.hasAlmanac());
  199. }
  200. /**
  201. * 通过WIFI获取定位信息
  202. */
  203. public static void fromWIFILocation(){
  204. //WIFI的MAC地址
  205. WifiManager manager = (WifiManager)mActivity.getSystemService(Context.WIFI_SERVICE);
  206. String wifiAddress = manager.getConnectionInfo().getBSSID();
  207. //根据WIFI信息定位
  208. DefaultHttpClient client = new DefaultHttpClient();
  209. HttpPost post = new HttpPost(“http://www.google.com/loc/json”);
  210. JSONObject holder = new JSONObject();
  211. try {
  212. holder.put(”version” , “1.1.0”);
  213. holder.put( ”host” , “maps.google.com”);
  214. JSONObject data;
  215. JSONArray array = new JSONArray();
  216. if(wifiAddress!=null&&!wifiAddress.equals(“”)){
  217. data = new JSONObject();
  218. data.put(”mac_address”, wifiAddress);
  219. data.put(”signal_strength”, 8);
  220. data.put(”age”, 0);
  221. array.put(data);
  222. }
  223. holder.put(”wifi_towers”,array);
  224. StringEntity se = new StringEntity(holder.toString());
  225. post.setEntity(se);
  226. HttpResponse resp =client.execute(post);
  227. int state =resp.getStatusLine().getStatusCode();
  228. if (state == HttpStatus.SC_OK) {
  229. HttpEntity entity =resp.getEntity();
  230. if (entity != null) {
  231. BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
  232. StringBuffer sb = new StringBuffer();
  233. String resute = ”“;
  234. while ((resute =br.readLine()) != null) {
  235. sb.append(resute);
  236. }
  237. br.close();
  238. data = new JSONObject(sb.toString());
  239. data = (JSONObject)data.get(”location”);
  240. Location loc = new Location(LocationManager.NETWORK_PROVIDER);
  241. loc.setLatitude((Double)data.get(”latitude”));
  242. loc.setLongitude((Double)data.get(”longitude”));
  243. //其他信息同样获取方法
  244. Log4Lsy.i(TAG, ”latitude ===== ”+(Double)data.get(“latitude”));
  245. Log4Lsy.i(TAG, ”longitude ===== ”+(Double)data.get(“longitude”));
  246. }
  247. }
  248. } catch (Exception e) {
  249. e.printStackTrace();
  250. }
  251. }
  252. }
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;import com.function.utils.Log4Lsy;/*** Android API本身提供的定位功能,也是GPS定位。* GPS定位,是基于卫星定位。它受环境影响很大。并且是单向定位,也就是只有你自己知道你的地理坐标。* @author LuoSiye*/
@TargetApi(Build.VERSION_CODES.CUPCAKE)
@SuppressLint("NewApi")
public class LocationUtil{private static final String TAG = "LocationUtil";private static LocationUtil instance;private static Activity mActivity;private static LocationManager locationManager;private static LocationListener locationListener;public static LocationUtil getInstance(Activity activity){mActivity = activity;if(instance==null){instance = new LocationUtil();}locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);return instance;}/*** 判断GPS导航是否打开.* false:弹窗提示打开,不建议采用在后台强行开启的方式。* true:不做任何处理* @return*/public static void isOpenGPS(){if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)){AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);dialog.setMessage("GPS未打开,是否打开?");dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);// 设置完成后返回到原来的界面mActivity.startActivityForResult(intent, 0); }});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});dialog.show();}}/*** 通过LocationListener来获取Location信息*/public static void formListenerGetLocation(){locationListener = new LocationListener() {@Overridepublic void onLocationChanged(Location location) {//位置信息变化时触发Log4Lsy.i(TAG, "纬度:"+location.getLatitude());Log4Lsy.i(TAG, "经度:"+location.getLongitude());Log4Lsy.i(TAG, "海拔:"+location.getAltitude());Log4Lsy.i(TAG, "时间:"+location.getTime());}@Overridepublic void onStatusChanged(String provider, int status,Bundle extras) {//GPS状态变化时触发}@Overridepublic void onProviderEnabled(String provider) {//GPS禁用时触发}@Overridepublic void onProviderDisabled(String provider) {//GPS开启时触发 }};/*** 绑定监听* 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种,前者是GPS,后者是GPRS以及WIFI定位* 参数2,位置信息更新周期.单位是毫秒* 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息* 参数4,监听* 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新*/locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}/*** 主动获取Location,通过以下方法获取到的是最后一次定位信息。* 注意:Location location=new Location(LocationManager.GPS_PROVIDER)方式获取的location的各个参数值都是为0。*/public static void getLocation(){Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);Log4Lsy.i(TAG, "纬度:"+location.getLatitude());Log4Lsy.i(TAG, "经度:"+location.getLongitude());Log4Lsy.i(TAG, "海拔:"+location.getAltitude());Log4Lsy.i(TAG, "时间:"+location.getTime());}/*** 获取GPS状态监听,包括GPS启动、停止、第一次定位、卫星变化等事件。*/public static void getStatusListener(){GpsStatus.Listener listener = new GpsStatus.Listener(){@Overridepublic void onGpsStatusChanged(int event) {if(event==GpsStatus.GPS_EVENT_FIRST_FIX){//第一次定位}else if(event==GpsStatus.GPS_EVENT_SATELLITE_STATUS){//卫星状态改变GpsStatus gpsStauts= locationManager.getGpsStatus(null); // 取当前状态int maxSatellites = gpsStauts.getMaxSatellites(); //获取卫星颗数的默认最大值Iterator<GpsSatellite> it = gpsStauts.getSatellites().iterator();//创建一个迭代器保存所有卫星int count = 0;while (it.hasNext() && count <= maxSatellites) {    count++;   GpsSatellite s = it.next();  }Log4Lsy.i(TAG, "搜索到:"+count+"颗卫星");}else if(event==GpsStatus.GPS_EVENT_STARTED){//定位启动}else if(event==GpsStatus.GPS_EVENT_STOPPED){//定位结束}}};//绑定locationManager.addGpsStatusListener(listener); }/*** 获取所有卫星状态* @return*/public static List<GpsSatellite> getGpsStatus(){List<GpsSatellite> result = new ArrayList<GpsSatellite>();GpsStatus gpsStatus = locationManager.getGpsStatus(null); // 取当前状态//获取默认最大卫星数int maxSatellites = gpsStatus.getMaxSatellites();//获取第一次定位时间(启动到第一次定位)int costTime=gpsStatus.getTimeToFirstFix();Log4Lsy.i(TAG, "第一次定位时间:"+costTime);//获取卫星Iterable<GpsSatellite> iterable=gpsStatus.getSatellites();//一般再次转换成IteratorIterator<GpsSatellite> itrator=iterable.iterator();int count = 0;while (itrator.hasNext() && count <= maxSatellites){count++;GpsSatellite s = itrator.next();result.add(s);}return result;}/*** 某一个卫星的信息.* @param gpssatellite*/public static void getGpsStatelliteInfo(GpsSatellite gpssatellite){//卫星的方位角,浮点型数据  Log4Lsy.i(TAG, "卫星的方位角:"+gpssatellite.getAzimuth());//卫星的高度,浮点型数据  Log4Lsy.i(TAG, "卫星的高度:"+gpssatellite.getElevation());//卫星的伪随机噪声码,整形数据  Log4Lsy.i(TAG, "卫星的伪随机噪声码:"+gpssatellite.getPrn());//卫星的信噪比,浮点型数据  Log4Lsy.i(TAG, "卫星的信噪比:"+gpssatellite.getSnr());//卫星是否有年历表,布尔型数据  Log4Lsy.i(TAG, "卫星是否有年历表:"+gpssatellite.hasAlmanac());//卫星是否有星历表,布尔型数据  Log4Lsy.i(TAG, "卫星是否有星历表:"+gpssatellite.hasEphemeris());//卫星是否被用于近期的GPS修正计算  Log4Lsy.i(TAG, "卫星是否被用于近期的GPS修正计算:"+gpssatellite.hasAlmanac());}/*** 通过WIFI获取定位信息*/public static void fromWIFILocation(){//WIFI的MAC地址WifiManager manager = (WifiManager)mActivity.getSystemService(Context.WIFI_SERVICE); String wifiAddress = manager.getConnectionInfo().getBSSID(); //根据WIFI信息定位DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.google.com/loc/json"); JSONObject holder = new JSONObject();try {holder.put("version" , "1.1.0");holder.put( "host" , "maps.google.com"); JSONObject data;               JSONArray array = new JSONArray();if(wifiAddress!=null&&!wifiAddress.equals("")){data = new JSONObject(); data.put("mac_address", wifiAddress); data.put("signal_strength", 8); data.put("age", 0); array.put(data); }holder.put("wifi_towers",array); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se);HttpResponse resp =client.execute(post); int state =resp.getStatusLine().getStatusCode(); if (state == HttpStatus.SC_OK) {HttpEntity entity =resp.getEntity(); if (entity != null) {BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));StringBuffer sb = new StringBuffer(); String resute = "";while ((resute =br.readLine()) != null) {                     sb.append(resute);                   }                   br.close(); data = new JSONObject(sb.toString()); data = (JSONObject)data.get("location"); Location loc = new Location(LocationManager.NETWORK_PROVIDER);loc.setLatitude((Double)data.get("latitude"));                   loc.setLongitude((Double)data.get("longitude"));//其他信息同样获取方法Log4Lsy.i(TAG, "latitude ===== "+(Double)data.get("latitude"));Log4Lsy.i(TAG, "longitude ===== "+(Double)data.get("longitude"));}}} catch (Exception e) {e.printStackTrace();}}
}

Android 的三种定位方式相关推荐

  1. 百度地图三种定位方式测试(高精度、低功耗、仅用设备)

    百度地图三种定位方式测试(高精度.低功耗.仅用设备) Android定位SDK自v7.0版本起,按照附加功能不同,向开发者提供了四种不同类型的定位开发包,可根据不同需求,自有选择所需类型的开发包使用. ...

  2. android中几种定位方式详解

    目录 前言: 1.GPS定位 2.NETWORK定位 3.AGPS定位 4.基站定位 5.WIFI定位 6.混合定位 目前,移动端大致通过三种方式来进行设备定位:GPS.基站.wifi.本文就详细的讲 ...

  3. html5边框顶格,CSS 三种定位方式以及格式化上下文详解 》 html5jscss

    常规流( Normal flow ) 之称之为常规流,是因为这是相对于后面的浮动和绝对定位的一个概念,浮动和绝对定位元素都脱离了当前的常规流. 在 CSS2.1中,常规流包括块框( block box ...

  4. ios wifi 定位_iOS中三种定位方式

    手机基站定位 原理 每个手机基站都有一个标识符,iPhone或3G iPad可以搜集周围所有收到信号的基站和它们的标识符,通过联网发送到苹果云端服务器,再由服务器根据这些基站的的位置信息查询并计算出当 ...

  5. android 三种定位方式

    最近在看android关于定位的方式,查了很多资料,也做了相关实验,在手机上做了测试,下面总结: 一共有三种定位方式,一种是GPS,一种是通过网络的方式,一种则是在基于基站的方式,但是,不管哪种方式, ...

  6. android 三种定位方式 介绍

    三种获取手机的位置的方式_20 1.网络定位(network).前提是必须连上网络:wifi.3G.2G: 获取到IP地址 例如:传美版QQ,彩虹版QQ,珊瑚虫版QQ,就有一个功能显示对方的IP: 根 ...

  7. css的三种定位方式使用探讨

    css 3种类型定位方式,进行控制页面布局:普通定位,浮动定位,绝对定位. 默认使用普通流技术再页面中布局元素,希望表现与普通流不同,另外两个特性position和float 具体实例 复制代码 代码 ...

  8. ios wifi 定位_iOS 中的三种定位方式

    1.手机基站定位 原理: 每个手机基站都有一个标识符,iPhone或3G iPad可以搜集周围所有收到信号的基站和它们的标识符,通过联网发送到苹果云端服务器,再由服务器根据这些基站的的位置信息查询并计 ...

  9. android画面数据存储方式,Android的三种储存方式

    SharePreferences SharePreferences适合用来保存相对较小的键值集合,比如应用程序的配置文件,它本质是存放在/data/data/[包名]/shared_prefs文件夹下 ...

最新文章

  1. 深度理解目标检测(MMdetection)-HOOK机制
  2. Mysql悲观锁乐观锁区别使用区别
  3. 《算法竞赛入门经典》 例题5-2 木块问题(The Blocks Problem,UVa 101)
  4. 微信、QQ都在用的腾讯云EB级对象存储架构剖析
  5. LINUX 下mysql主从安装与同步
  6. opencv cv.findContours 函数详解
  7. python基础数据结构,Python基本数据结构
  8. oracle sql索引查询,Oracle查询数据库的索引字段以及查询用索引
  9. ABAQUS混凝土CDP插件,一键生成混凝土CDP本构曲线
  10. C++ 数据结构实战:快速查找
  11. 『SnowFlake』雪花算法的详解及时间回拨解决方案
  12. 常用分子对接软件简介
  13. Google guava之SortedMultiset简介说明
  14. TLS协议分析------
  15. jxl 删除excel重复的行
  16. 使用哈尔滨工业大学SCIR的开源代码训练自己的ELMo
  17. css 设置body的最小高度是100%,满屏显示
  18. table中英文值显示其对应中文
  19. 【Eelectron-vue】构建桌面应用(20)-electron的退出quit和exit
  20. 网站页面布局的原则有哪些呢?

热门文章

  1. 为何专利总是抓不到对手侵权?-Capability Claim对直接侵权的影响
  2. JavaScript的小游戏——贪吃蛇
  3. matlab中索引超过维度,索引超出矩阵维度怎么解决?
  4. 扫描windows或Linux内网中正在使用的ip
  5. 机械清洗时洗衣液加入运作过程中大量泡沫出现洗衣液专用消泡粉
  6. Msys2常见问题解决办法札记
  7. 公司内部分享文档应该怎么写?看这篇就够了
  8. redis内存突然增大怎么排查问题
  9. 查询员工信息(C语言)
  10. 【调剂】黑龙江科技大学2020年硕士研究生招生预调剂政策