真实可行的android 基站定位代码

来自:http://blog.csdn.net/swqqcs/article/details/7064532

大部分国产的Android定制机里不支持最简单实用的基站和WIFI定位,只能使用速度慢而耗电的GPS定位,但OPhone和华为/中兴生产的一些Android定制机却占据了一定的市场,因此导致了很多使用了定位技术的Andorid应用挺尴尬的。

 

         不过其实只要明白了基站/WIFI定位的原理,自己实现基站/WIFI定位其实不难。基站定位一般有几种,第一种是利用手机附近的三个基站进行三角定位,由于每个基站的位置是固定的,利用电磁波在这三个基站间中转所需要时间来算出手机所在的坐标;第二种则是利用获取最近的基站的信息,其中包括基站id,location area code、mobile country code、mobile network code和信号强度,将这些数据发送到google的定位web服务里,就能拿到当前所在的位置信息,误差一般在几十米到几百米之内。其中信号强度这个数据很重要,网上很多所谓的手动通过基站和WIFI信息定位的方法误差大都是因为没使用信号强度而导致误差过大。高德也自己做了一个基站库,具体可以google搜索一下。

 

         现在在一些大中型城市里,WIFI已经普及,有私人或企业的WIFI,亦有中国电信的WIFI,通过WIFI信息进行定位,并不需要真正连接上指定的WIFI路由器,只需要探测到有WIFI存在即可,因此当手机使用的不是GSM制式(因为google的基站库里并没在保存太多的CDMA基站)的时候,也可以使用WIFI进行定位,原理也和基站定位一样,必须要拿到WIFI路由器的SSID和信号强度。

 

         由于有些用户默认是将WIFI关闭的,通过API开启WIFI硬件并进行搜索附近的WIFI路由器需要一段时间,怎样才能将手机基站定位和WIFI定位完美结合起来呢,Android提供了一种很好的机制,就是Handler和Looper,Handler和Looper一般用于跨线程传递数据,但当在单线程里使用时,就变成了一个先进先出的消息泵。利用这个消息泵进行调度,就可以将基站定位和WIFI定位完美结合。以下是相关的代码:

[java]  view plain copy
  1. CellInfoManager  
  2.    
  3. import java.lang.reflect.Method;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6.    
  7. import org.json.JSONArray;  
  8. import org.json.JSONException;  
  9. import org.json.JSONObject;  
  10.    
  11. import android.content.Context;  
  12. import android.telephony.CellLocation;  
  13. import android.telephony.NeighboringCellInfo;  
  14. import android.telephony.PhoneStateListener;  
  15. import android.telephony.TelephonyManager;  
  16. import android.telephony.gsm.GsmCellLocation;  
  17. import android.util.Log;  
  18.    
  19. public class CellInfoManager {  
  20.        private int asu;  
  21.        private int bid;  
  22.        private int cid;  
  23.        private boolean isCdma;  
  24.        private boolean isGsm;  
  25.        private int lac;  
  26.        private int lat;  
  27.        private final PhoneStateListener listener;  
  28.        private int lng;  
  29.        private int mcc;  
  30.        private int mnc;  
  31.        private int nid;  
  32.        private int sid;  
  33.        private TelephonyManager tel;  
  34.        private boolean valid;  
  35.        private Context context;  
  36.    
  37.        public CellInfoManager(Context paramContext) {  
  38.               this.listener = new CellInfoListener(this);  
  39.               tel = (TelephonyManager) paramContext.getSystemService(Context.TELEPHONY_SERVICE);  
  40.               this.tel.listen(this.listener, PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_SIGNAL_STRENGTH);  
  41.               context = paramContext;  
  42.        }  
  43.    
  44.        public static int dBm(int i) {  
  45.               int j;  
  46.               if (i >= 0 && i <= 31)  
  47.                      j = i * 2 + -113;  
  48.               else  
  49.                      j = 0;  
  50.               return j;  
  51.        }  
  52.    
  53.        public int asu() {  
  54.               return this.asu;  
  55.        }  
  56.    
  57.        public int bid() {  
  58.               if (!this.valid)  
  59.                      update();  
  60.               return this.bid;  
  61.        }  
  62.    
  63.        public JSONObject cdmaInfo() {  
  64.               if (!isCdma()) {  
  65.                      return null;  
  66.               }  
  67.               JSONObject jsonObject = new JSONObject();  
  68.               try {  
  69.                      jsonObject.put("bid", bid());  
  70.                      jsonObject.put("sid", sid());  
  71.                      jsonObject.put("nid", nid());  
  72.                      jsonObject.put("lat", lat());  
  73.                      jsonObject.put("lng", lng());  
  74.               } catch (JSONException ex) {  
  75.                      jsonObject = null;  
  76.                      Log.e("CellInfoManager", ex.getMessage());  
  77.               }  
  78.               return jsonObject;  
  79.        }  
  80.    
  81.        public JSONArray cellTowers() {  
  82.               JSONArray jsonarray = new JSONArray();  
  83.    
  84.               int lat;  
  85.               int mcc;  
  86.               int mnc;  
  87.               int aryCell[] = dumpCells();  
  88.               lat = lac();  
  89.               mcc = mcc();  
  90.               mnc = mnc();  
  91.               if (aryCell == null || aryCell.length < 2) {  
  92.                      aryCell = new int[2];  
  93.                      aryCell[0] = cid;  
  94.                      aryCell[1] = -60;  
  95.               }  
  96.               for (int i = 0; i < aryCell.length; i += 2) {  
  97.                      try {  
  98.                             int j2 = dBm(i + 1);  
  99.                             JSONObject jsonobject = new JSONObject();  
  100.                             jsonobject.put("cell_id", aryCell[i]);  
  101.                             jsonobject.put("location_area_code", lat);  
  102.                             jsonobject.put("mobile_country_code", mcc);  
  103.                             jsonobject.put("mobile_network_code", mnc);  
  104.                             jsonobject.put("signal_strength", j2);  
  105.                             jsonobject.put("age"0);  
  106.                             jsonarray.put(jsonobject);  
  107.                      } catch (Exception ex) {  
  108.                             ex.printStackTrace();  
  109.                             Log.e("CellInfoManager", ex.getMessage());  
  110.                      }  
  111.               }  
  112.               if (isCdma())  
  113.                      jsonarray = new JSONArray();  
  114.               return jsonarray;  
  115.    
  116.        }  
  117.    
  118.        public int cid() {  
  119.               if (!this.valid)  
  120.                      update();  
  121.               return this.cid;  
  122.        }  
  123.    
  124.        public int[] dumpCells() {  
  125.               int[] aryCells;  
  126.               if (cid() == 0) {  
  127.                      aryCells = new int[0];  
  128.                      return aryCells;  
  129.               }  
  130.    
  131.               List<NeighboringCellInfo> lsCellInfo = this.tel.getNeighboringCellInfo();  
  132.               if (lsCellInfo == null || lsCellInfo.size() == 0) {  
  133.                      aryCells = new int[1];  
  134.                      int i = cid();  
  135.                      aryCells[0] = i;  
  136.                      return aryCells;  
  137.               }  
  138.               int[] arrayOfInt1 = new int[lsCellInfo.size() * 2 + 2];  
  139.               int j = 0 + 1;  
  140.               int k = cid();  
  141.               arrayOfInt1[0] = k;  
  142.               int m = j + 1;  
  143.               int n = asu();  
  144.               arrayOfInt1[j] = n;  
  145.               Iterator<NeighboringCellInfo> iter = lsCellInfo.iterator();  
  146.               while (true) {  
  147.                      if (!iter.hasNext()) {  
  148.                             break;  
  149.                      }  
  150.                      NeighboringCellInfo localNeighboringCellInfo = (NeighboringCellInfo) iter.next();  
  151.                      int i2 = localNeighboringCellInfo.getCid();  
  152.                      if ((i2 <= 0) || (i2 == 65535))  
  153.                             continue;  
  154.                      int i3 = m + 1;  
  155.                      arrayOfInt1[m] = i2;  
  156.                      m = i3 + 1;  
  157.                      int i4 = localNeighboringCellInfo.getRssi();  
  158.                      arrayOfInt1[i3] = i4;  
  159.               }  
  160.               int[] arrayOfInt2 = new int[m];  
  161.               System.arraycopy(arrayOfInt1, 0, arrayOfInt2, 0, m);  
  162.               aryCells = arrayOfInt2;  
  163.               return aryCells;  
  164.    
  165.        }  
  166.    
  167.        public JSONObject gsmInfo() {  
  168.               if (!isGsm()) {  
  169.                      return null;  
  170.               }  
  171.               JSONObject localObject = null;  
  172.               while (true) {  
  173.                      try {  
  174.                             JSONObject localJSONObject1 = new JSONObject();  
  175.                             String str1 = this.tel.getNetworkOperatorName();  
  176.                             localJSONObject1.put("operator", str1);  
  177.                             String str2 = this.tel.getNetworkOperator();  
  178.                             if ((str2.length() == 5) || (str2.length() == 6)) {  
  179.                                    String str3 = str2.substring(03);  
  180.                                    String str4 = str2.substring(3, str2.length());  
  181.                                    localJSONObject1.put("mcc", str3);  
  182.                                    localJSONObject1.put("mnc", str4);  
  183.                             }  
  184.                             localJSONObject1.put("lac", lac());  
  185.                             int[] arrayOfInt = dumpCells();  
  186.                             JSONArray localJSONArray1 = new JSONArray();  
  187.                             int k = 0;  
  188.                             int m = arrayOfInt.length / 2;  
  189.                             while (true) {  
  190.                                    if (k >= m) {  
  191.                                           localJSONObject1.put("cells", localJSONArray1);  
  192.                                           localObject = localJSONObject1;  
  193.                                           break;  
  194.                                    }  
  195.                                    int n = k * 2;  
  196.                                    int i1 = arrayOfInt[n];  
  197.                                    int i2 = k * 2 + 1;  
  198.                                    int i3 = arrayOfInt[i2];  
  199.                                    JSONObject localJSONObject7 = new JSONObject();  
  200.                                    localJSONObject7.put("cid", i1);  
  201.                                    localJSONObject7.put("asu", i3);  
  202.                                    localJSONArray1.put(localJSONObject7);  
  203.                                    k += 1;  
  204.                             }  
  205.                      } catch (JSONException localJSONException) {  
  206.                             localObject = null;  
  207.                      }  
  208.               }  
  209.        }  
  210.    
  211.        public boolean isCdma() {  
  212.               if (!this.valid)  
  213.                      update();  
  214.               return this.isCdma;  
  215.        }  
  216.    
  217.        public boolean isGsm() {  
  218.               if (!this.valid)  
  219.                      update();  
  220.               return this.isGsm;  
  221.        }  
  222.    
  223.        public int lac() {  
  224.               if (!this.valid)  
  225.                      update();  
  226.               return this.lac;  
  227.        }  
  228.    
  229.        public int lat() {  
  230.               if (!this.valid)  
  231.                      update();  
  232.               return this.lat;  
  233.        }  
  234.    
  235.        public int lng() {  
  236.               if (!this.valid)  
  237.                      update();  
  238.               return this.lng;  
  239.        }  
  240.    
  241.        public int mcc() {  
  242.               if (!this.valid)  
  243.                      update();  
  244.               return this.mcc;  
  245.        }  
  246.    
  247.        public int mnc() {  
  248.               if (!this.valid)  
  249.                      update();  
  250.               return this.mnc;  
  251.        }  
  252.    
  253.        public int nid() {  
  254.               if (!this.valid)  
  255.                      update();  
  256.               return this.nid;  
  257.        }  
  258.    
  259.        public float score() {  
  260.               float f1 = 0f;  
  261.               int[] aryCells = null;  
  262.               int i = 0;  
  263.               float f2 = 0f;  
  264.               if (isCdma()) {  
  265.                      f2 = 1065353216;  
  266.                      return f2;  
  267.               }  
  268.               if (isGsm()) {  
  269.                      f1 = 0.0F;  
  270.                      aryCells = dumpCells();  
  271.                      int j = aryCells.length;  
  272.                      if (i >= j)  
  273.                             f2 = f1;  
  274.               }  
  275.               if(i <=0 ) {  
  276.                      return 1065353216;  
  277.               }  
  278.               int m = aryCells[i];  
  279.               for (i = 0; i < m; i++) {  
  280.                      if ((m < 0) || (m > 31))  
  281.                             f1 += 0.5F;  
  282.                      else  
  283.                             f1 += 1.0F;  
  284.               }  
  285.               f2 = f1;  
  286.    
  287.               return f2;  
  288.        }  
  289.    
  290.        public int sid() {  
  291.               if (!this.valid)  
  292.                      update();  
  293.               return this.sid;  
  294.        }  
  295.    
  296.        public void update() {  
  297.               this.isGsm = false;  
  298.               this.isCdma = false;  
  299.               this.cid = 0;  
  300.               this.lac = 0;  
  301.               this.mcc = 0;  
  302.               this.mnc = 0;  
  303.               CellLocation cellLocation = this.tel.getCellLocation();  
  304.               int nPhoneType = this.tel.getPhoneType();  
  305.               if (nPhoneType == 1 && cellLocation instanceof GsmCellLocation) {  
  306.                      this.isGsm = true;  
  307.                      GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;  
  308.                      int nGSMCID = gsmCellLocation.getCid();  
  309.                      if (nGSMCID > 0) {  
  310.                             if (nGSMCID != 65535) {  
  311.                                    this.cid = nGSMCID;  
  312.                                    this.lac = gsmCellLocation.getLac();  
  313.                             }  
  314.                      }  
  315.               }  
  316.               try {  
  317.                      String strNetworkOperator = this.tel.getNetworkOperator();  
  318.                      int nNetworkOperatorLength = strNetworkOperator.length();  
  319.                      if (nNetworkOperatorLength != 5) {  
  320.                             if (nNetworkOperatorLength != 6)  
  321.                                    ;  
  322.                      } else {  
  323.                             this.mcc = Integer.parseInt(strNetworkOperator.substring(03));  
  324.                             this.mnc = Integer.parseInt(strNetworkOperator.substring(3, nNetworkOperatorLength));  
  325.                      }  
  326.                      if (this.tel.getPhoneType() == 2) {  
  327.                             this.valid = true;  
  328.                             Class<?> clsCellLocation = cellLocation.getClass();  
  329.                             Class<?>[] aryClass = new Class[0];  
  330.                             Method localMethod1 = clsCellLocation.getMethod("getBaseStationId", aryClass);  
  331.                             Method localMethod2 = clsCellLocation.getMethod("getSystemId", aryClass);  
  332.                             Method localMethod3 = clsCellLocation.getMethod("getNetworkId", aryClass);  
  333.                             Object[] aryDummy = new Object[0];   
  334.                             this.bid = ((Integer) localMethod1.invoke(cellLocation, aryDummy)).intValue();  
  335.                             this.sid = ((Integer) localMethod2.invoke(cellLocation, aryDummy)).intValue();  
  336.                             this.nid = ((Integer) localMethod3.invoke(cellLocation, aryDummy)).intValue();  
  337.                             Method localMethod7 = clsCellLocation.getMethod("getBaseStationLatitude", aryClass);  
  338.                             Method localMethod8 = clsCellLocation.getMethod("getBaseStationLongitude", aryClass);  
  339.                             this.lat = ((Integer) localMethod7.invoke(cellLocation, aryDummy)).intValue();  
  340.                             this.lng = ((Integer) localMethod8.invoke(cellLocation, aryDummy)).intValue();  
  341.                             this.isCdma = true;  
  342.                      }  
  343.               } catch (Exception ex) {  
  344.                      Log.e("CellInfoManager", ex.getMessage());  
  345.               }  
  346.        }  
  347.    
  348.        class CellInfoListener extends PhoneStateListener {  
  349.               CellInfoListener(CellInfoManager manager) {  
  350.    
  351.               }  
  352.    
  353.               public void onCellLocationChanged(CellLocation paramCellLocation) {  
  354.                      CellInfoManager.this.valid = false;  
  355.               }  
  356.    
  357.               public void onSignalStrengthChanged(int paramInt) {  
  358.                      CellInfoManager.this.asu = paramInt;  
  359.               }  
  360.        }  
  361. }  
  362.    
  363. WifiInfoManager  
  364.    
  365. import java.util.ArrayList;  
  366. import java.util.Iterator;  
  367. import java.util.List;  
  368.    
  369. import org.json.JSONArray;  
  370. import org.json.JSONObject;  
  371.    
  372. import android.content.Context;  
  373. import android.net.wifi.ScanResult;  
  374. import android.net.wifi.WifiManager;  
  375. import android.util.Log;  
  376.    
  377. public class WifiInfoManager {  
  378.        private WifiManager wifiManager;  
  379.    
  380.        public WifiInfoManager(Context paramContext) {  
  381.               this.wifiManager = (WifiManager) paramContext.getSystemService(Context.WIFI_SERVICE);  
  382.        }  
  383.    
  384.        public List<WifiInfo> dump() {  
  385.               if (!this.wifiManager.isWifiEnabled()) {  
  386.                      return new ArrayList<WifiInfo>();  
  387.               }  
  388.               android.net.wifi.WifiInfo wifiConnection = this.wifiManager.getConnectionInfo();  
  389.               WifiInfo currentWIFI = null;  
  390.               if (wifiConnection != null) {  
  391.                      String s = wifiConnection.getBSSID();  
  392.                      int i = wifiConnection.getRssi();  
  393.                      String s1 = wifiConnection.getSSID();  
  394.                      currentWIFI = new WifiInfo(s, i, s1);  
  395.    
  396.               }  
  397.               ArrayList<WifiInfo> lsAllWIFI = new ArrayList<WifiInfo>();  
  398.               if (currentWIFI != null) {  
  399.                      lsAllWIFI.add(currentWIFI);  
  400.               }  
  401.               List<ScanResult> lsScanResult = this.wifiManager.getScanResults();  
  402.               for (ScanResult result : lsScanResult) {  
  403.                      WifiInfo scanWIFI = new WifiInfo(result);  
  404.                      if (!scanWIFI.equals(currentWIFI))  
  405.                             lsAllWIFI.add(scanWIFI);  
  406.               }  
  407.               return lsAllWIFI;  
  408.        }  
  409.    
  410.        public boolean isWifiEnabled() {  
  411.               return this.wifiManager.isWifiEnabled();  
  412.        }  
  413.    
  414.        public JSONArray wifiInfo() {  
  415.               JSONArray jsonArray = new JSONArray();  
  416.    
  417.               for (WifiInfo wifi : dump()) {  
  418.                      JSONObject localJSONObject = wifi.info();  
  419.                      jsonArray.put(localJSONObject);  
  420.               }  
  421.               return jsonArray;  
  422.        }  
  423.    
  424.        public WifiManager wifiManager() {  
  425.               return this.wifiManager;  
  426.        }  
  427.    
  428.        public JSONArray wifiTowers() {  
  429.               JSONArray jsonArray = new JSONArray();  
  430.               try {  
  431.                      Iterator<WifiInfo> localObject = dump().iterator();  
  432.                      while (true) {  
  433.                             if (!(localObject).hasNext()) {  
  434.                                    return jsonArray;  
  435.                             }  
  436.                             jsonArray.put(localObject.next().wifi_tower());  
  437.                      }  
  438.               } catch (Exception localException) {  
  439.                      Log.e("location", localException.getMessage());  
  440.               }  
  441.               return jsonArray;  
  442.        }  
  443.    
  444.        public class WifiInfo implements Comparable<WifiInfo> {  
  445.               public int compareTo(WifiInfo wifiinfo) {  
  446.                      int i = wifiinfo.dBm;  
  447.                      int j = dBm;  
  448.                      return i - j;  
  449.               }  
  450.    
  451.               public boolean equals(Object obj) {  
  452.                      boolean flag = false;  
  453.                      if (obj == this) {  
  454.                             flag = true;  
  455.                             return flag;  
  456.                      } else {  
  457.                             if (obj instanceof WifiInfo) {  
  458.                                    WifiInfo wifiinfo = (WifiInfo) obj;  
  459.                                    int i = wifiinfo.dBm;  
  460.                                    int j = dBm;  
  461.                                    if (i == j) {  
  462.                                           String s = wifiinfo.bssid;  
  463.                                           String s1 = bssid;  
  464.                                           if (s.equals(s1)) {  
  465.                                                  flag = true;  
  466.                                                  return flag;  
  467.                                           }  
  468.                                    }  
  469.                                    flag = false;  
  470.                             } else {  
  471.                                    flag = false;  
  472.                             }  
  473.                      }  
  474.                      return flag;  
  475.               }  
  476.    
  477.               public int hashCode() {  
  478.                      int i = dBm;  
  479.                      int j = bssid.hashCode();  
  480.                      return i ^ j;  
  481.               }  
  482.    
  483.               public JSONObject info() {  
  484.                      JSONObject jsonobject = new JSONObject();  
  485.                      try {  
  486.                             String s = bssid;  
  487.                             jsonobject.put("mac", s);  
  488.                             String s1 = ssid;  
  489.                             jsonobject.put("ssid", s1);  
  490.                             int i = dBm;  
  491.                             jsonobject.put("dbm", i);  
  492.                      } catch (Exception ex) {  
  493.    
  494.                      }  
  495.                      return jsonobject;  
  496.               }  
  497.    
  498.               public JSONObject wifi_tower() {  
  499.                      JSONObject jsonobject = new JSONObject();  
  500.                      try {  
  501.    
  502.                             String s = bssid;  
  503.                             jsonobject.put("mac_address", s);  
  504.                             int i = dBm;  
  505.                             jsonobject.put("signal_strength", i);  
  506.                             String s1 = ssid;  
  507.                             jsonobject.put("ssid", s1);  
  508.                             jsonobject.put("age"0);  
  509.                      } catch (Exception ex) {  
  510.    
  511.                      }  
  512.                      return jsonobject;  
  513.               }  
  514.    
  515.               public final String bssid;  
  516.               public final int dBm;  
  517.               public final String ssid;  
  518.    
  519.               public WifiInfo(ScanResult scanresult) {  
  520.                      String s = scanresult.BSSID;  
  521.                      bssid = s;  
  522.                      int i = scanresult.level;  
  523.                      dBm = i;  
  524.                      String s1 = scanresult.SSID;  
  525.                      ssid = s1;  
  526.               }  
  527.    
  528.               public WifiInfo(String s, int i, String s1) {  
  529.                      bssid = s;  
  530.                      dBm = i;  
  531.                      ssid = s1;  
  532.               }  
  533.    
  534.        }  
  535. }  
  536.    
  537. CellLocationManager  
  538.    
  539. import java.util.ArrayList;  
  540. import java.util.Iterator;  
  541. import java.util.List;  
  542.    
  543. import org.apache.http.HttpEntity;  
  544. import org.apache.http.HttpResponse;  
  545. import org.apache.http.client.methods.HttpPost;  
  546. import org.apache.http.entity.StringEntity;  
  547. import org.apache.http.impl.client.DefaultHttpClient;  
  548. import org.apache.http.util.EntityUtils;  
  549. import org.json.JSONArray;  
  550. import org.json.JSONObject;  
  551.    
  552. import android.content.BroadcastReceiver;  
  553. import android.content.Context;  
  554. import android.content.Intent;  
  555. import android.content.IntentFilter;  
  556. import android.net.ConnectivityManager;  
  557. import android.net.NetworkInfo;  
  558. import android.net.wifi.WifiManager;  
  559. import android.os.Handler;  
  560. import android.os.Message;  
  561. import android.telephony.CellLocation;  
  562. import android.util.Log;  
  563. import android.widget.Toast;  
  564.    
  565. import com.google.android.photostream.UserTask;  
  566.    
  567. public abstract class CellLocationManager {  
  568.        public static int CHECK_INTERVAL = 15000;  
  569.        public static boolean ENABLE_WIFI = true;  
  570.        private static boolean IS_DEBUG = false;  
  571.        private static final int STATE_COLLECTING = 2;  
  572.        private static final int STATE_IDLE = 0;  
  573.        private static final int STATE_READY = 1;  
  574.        private static final int STATE_SENDING = 3;  
  575.        private static final int MESSAGE_INITIALIZE = 1;  
  576.        private static final int MESSAGE_COLLECTING_CELL = 2;  
  577.        private static final int MESSAGE_COLLECTING_WIFI = 5;  
  578.        private static final int MESSAGE_BEFORE_FINISH = 10;  
  579.        private int accuracy;  
  580.        private int bid;  
  581.        private CellInfoManager cellInfoManager;  
  582.        private Context context;  
  583.        private boolean disableWifiAfterScan;  
  584.        private int[] aryGsmCells;  
  585.        private double latitude;  
  586.        private double longitude;  
  587.        private MyLooper looper;  
  588.        private boolean paused;  
  589.        private final BroadcastReceiver receiver;  
  590.        private long startScanTimestamp;  
  591.        private int state;  
  592.        private Task task;  
  593.        private long timestamp;  
  594.        private boolean waiting4WifiEnable;  
  595.        private WifiInfoManager wifiManager;  
  596.    
  597.        public CellLocationManager(Context context, CellInfoManager cellinfomanager, WifiInfoManager wifiinfomanager) {  
  598.               receiver = new CellLocationManagerBroadcastReceiver();  
  599.               this.context = context.getApplicationContext();  
  600.               cellInfoManager = cellinfomanager;  
  601.               wifiManager = wifiinfomanager;  
  602.        }  
  603.    
  604.        private void debug(Object paramObject) {  
  605.               if (IS_DEBUG) {  
  606.                      System.out.println(paramObject);  
  607.                      String str = String.valueOf(paramObject);  
  608.                      Toast.makeText(this.context, str, Toast.LENGTH_SHORT).show();  
  609.               }  
  610.        }  
  611.    
  612.        public int accuracy() {  
  613.               return this.accuracy;  
  614.        }  
  615.    
  616.        public double latitude() {  
  617.               return this.latitude;  
  618.        }  
  619.    
  620.        public double longitude() {  
  621.               return this.longitude;  
  622.        }  
  623.    
  624.        public abstract void onLocationChanged();  
  625.    
  626.        public void pause() {  
  627.               if (state > 0 && !paused) {  
  628.                      looper.removeMessages(MESSAGE_BEFORE_FINISH);  
  629.                      paused = true;  
  630.               }  
  631.        }  
  632.    
  633.        public void requestUpdate() {  
  634.               if (state != STATE_READY) {  
  635.                      return;  
  636.               }  
  637.               boolean bStartScanSuccessful = false;  
  638.               CellLocation.requestLocationUpdate();  
  639.               state = STATE_COLLECTING;  
  640.               looper.sendEmptyMessage(MESSAGE_INITIALIZE);  
  641.               if (wifiManager.wifiManager().isWifiEnabled()) {  
  642.                      bStartScanSuccessful = wifiManager.wifiManager().startScan();  
  643.                      waiting4WifiEnable = false;  
  644.               } else {  
  645.                      startScanTimestamp = System.currentTimeMillis();  
  646.                      if (!ENABLE_WIFI || !wifiManager.wifiManager().setWifiEnabled(true)) {  
  647.                             int nDelay = 0;  
  648.    
  649.                             if (!bStartScanSuccessful)  
  650.                                    nDelay = 8000;  
  651.                             looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, nDelay);  
  652.                             debug("CELL UPDATE");  
  653.                      } else {  
  654.                             waiting4WifiEnable = true;  
  655.                      }  
  656.               }  
  657.        }  
  658.    
  659.        public void resume() {  
  660.               if (state > 0 && paused) {  
  661.                      paused = false;  
  662.                      looper.removeMessages(MESSAGE_BEFORE_FINISH);  
  663.                      looper.sendEmptyMessage(MESSAGE_BEFORE_FINISH);  
  664.               }  
  665.        }  
  666.    
  667.        public void start() {  
  668.               if (state <= STATE_IDLE) {  
  669.                      Log.i("CellLocationManager""Starting...");  
  670.                      context.registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));  
  671.                      context.registerReceiver(receiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));  
  672.                      looper = new MyLooper();  
  673.                      state = STATE_READY;  
  674.                      paused = false;  
  675.                      waiting4WifiEnable = false;  
  676.                      disableWifiAfterScan = false;  
  677.                      debug("CELL LOCATION START");  
  678.                      requestUpdate();  
  679.               }  
  680.        }  
  681.    
  682.        public void stop() {  
  683.               if (state > STATE_IDLE) {  
  684.                      context.unregisterReceiver(receiver);  
  685.                      debug("CELL LOCATION STOP");  
  686.                      looper = null;  
  687.                      state = STATE_IDLE;  
  688.                      if (disableWifiAfterScan) {  
  689.                             disableWifiAfterScan = false;  
  690.                             wifiManager.wifiManager().setWifiEnabled(false);  
  691.                      }  
  692.               }  
  693.        }  
  694.    
  695.        public long timestamp() {  
  696.               return this.timestamp;  
  697.        }  
  698.         
  699.        protected boolean isConnectedWithInternet() {  
  700.               ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  701.               NetworkInfo networkInfo = conManager.getActiveNetworkInfo();  
  702.               if (networkInfo != null) {  
  703.                      return networkInfo.isAvailable();  
  704.               }  
  705.               return false;  
  706.    
  707.        }  
  708.    
  709.        private class MyLooper extends Handler {  
  710.               private float fCellScore;  
  711.               private JSONArray objCellTowersJson;  
  712.    
  713.               public void handleMessage(Message paramMessage) {  
  714.                      if(CellLocationManager.this.looper != this)  
  715.                             return;  
  716.                      boolean flag = true;  
  717.                      switch (paramMessage.what) {  
  718.                      default:  
  719.                             break;  
  720.                      case MESSAGE_INITIALIZE:  
  721.                             this.objCellTowersJson = null;  
  722.                             this.fCellScore = 1.401298E-045F;  
  723.                      case MESSAGE_COLLECTING_CELL:  
  724.                             if (CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING)  
  725.                                    break;  
  726.                             JSONArray objCellTowers = CellLocationManager.this.cellInfoManager.cellTowers();  
  727.                             float fCellScore = CellLocationManager.this.cellInfoManager.score();  
  728.                             if (objCellTowers != null) {  
  729.                                    float fCurrentCellScore = this.fCellScore;  
  730.                                    if (fCellScore > fCurrentCellScore) {  
  731.                                           this.objCellTowersJson = objCellTowers;  
  732.                                           this.fCellScore = fCellScore;  
  733.                                    }  
  734.                             }  
  735.                             this.sendEmptyMessageDelayed(MESSAGE_COLLECTING_CELL, 600L);  
  736.                             break;  
  737.                      case MESSAGE_COLLECTING_WIFI:  
  738.                             if (CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING)  
  739.                                    break;  
  740.                             this.removeMessages(MESSAGE_COLLECTING_CELL);  
  741.                             this.removeMessages(MESSAGE_BEFORE_FINISH);  
  742. //                          if (CellLocationManager.this.disableWifiAfterScan && CellLocationManager.this.wifiManager.wifiManager().setWifiEnabled(true))  
  743. //                                 CellLocationManager.this.disableWifiAfterScan = false;  
  744.                             CellLocationManager.this.state = CellLocationManager.STATE_SENDING;  
  745.                             if (CellLocationManager.this.task != null)  
  746.                                    CellLocationManager.this.task.cancel(true);  
  747.                             int[] aryCell = null;  
  748.                             if (CellLocationManager.this.cellInfoManager.isGsm())  
  749.                                    aryCell = CellLocationManager.this.cellInfoManager.dumpCells();  
  750.                             int nBid = CellLocationManager.this.cellInfoManager.bid();  
  751.                             CellLocationManager.this.task = new CellLocationManager.Task(aryCell, nBid);  
  752.                             JSONArray[] aryJsonArray = new JSONArray[2];  
  753.                             aryJsonArray[0] = this.objCellTowersJson;  
  754.                             aryJsonArray[1] = CellLocationManager.this.wifiManager.wifiTowers();  
  755.                             if(this.objCellTowersJson != null)  
  756.                                    Log.i("CellTownerJSON"this.objCellTowersJson.toString());  
  757.                             if(aryJsonArray[1] != null)  
  758.                                    Log.i("WIFITownerJSON", aryJsonArray[1].toString());  
  759.                             CellLocationManager.this.debug("Post json");  
  760.                             CellLocationManager.this.task.execute(aryJsonArray);  
  761.                             break;  
  762.                      case MESSAGE_BEFORE_FINISH:  
  763.                             if (CellLocationManager.this.state != CellLocationManager.STATE_READY || CellLocationManager.this.paused)  
  764.                                    break;  
  765.                             // L7  
  766.                             if (CellLocationManager.this.disableWifiAfterScan && CellLocationManager.this.wifiManager.wifiManager().setWifiEnabled(false))  
  767.                                    CellLocationManager.this.disableWifiAfterScan = false;  
  768.                             if (!CellLocationManager.this.cellInfoManager.isGsm()) {  
  769.                                    // L9  
  770.                                    if (CellLocationManager.this.bid == CellLocationManager.this.cellInfoManager.bid()) {  
  771.                                           flag = true;  
  772.                                    } else {  
  773.                                           flag = false;  
  774.                                    }  
  775.                                    // L14  
  776.                                    if (flag) {  
  777.                                           requestUpdate();  
  778.                                    } else {  
  779.                                           this.sendEmptyMessageDelayed(10, CellLocationManager.CHECK_INTERVAL);  
  780.                                    }  
  781.                             } else {  
  782.                                    // L8  
  783.                                    if (CellLocationManager.this.aryGsmCells == null || CellLocationManager.this.aryGsmCells.length == 0) {  
  784.                                           // L10  
  785.                                           flag = true;  
  786.                                    } else {  
  787.                                           int[] aryCells = CellLocationManager.this.cellInfoManager.dumpCells();  
  788.                                           if (aryCells != null && aryCells.length != 0) {  
  789.                                                  // L13  
  790.                                                  int nFirstCellId = CellLocationManager.this.aryGsmCells[0];  
  791.                                                  if (nFirstCellId == aryCells[0]) {  
  792.                                                         // L16  
  793.                                                         int cellLength = CellLocationManager.this.aryGsmCells.length / 2;  
  794.                                                         List<Integer> arraylist = new ArrayList<Integer>(cellLength);  
  795.                                                         List<Integer> arraylist1 = new ArrayList<Integer>(aryCells.length / 2);  
  796.                                                         int nIndex = 0;  
  797.                                                         int nGSMCellLength = CellLocationManager.this.aryGsmCells.length;  
  798.                                                         while (nIndex < nGSMCellLength) {  
  799.                                                                // goto L18  
  800.                                                                arraylist.add(CellLocationManager.this.aryGsmCells[nIndex]);  
  801.                                                                nIndex += 2;  
  802.                                                         }  
  803.                                                         // goto L17  
  804.                                                         nIndex = 0;  
  805.                                                         while (nIndex < aryCells.length) {  
  806.                                                                // goto L20  
  807.                                                                arraylist1.add(aryCells[nIndex]);  
  808.                                                                nIndex += 2;  
  809.                                                         }  
  810.                                                         // goto L19  
  811.                                                         int nCounter = 0;  
  812.                                                         for(Iterator<Integer> iterator = arraylist.iterator(); iterator.hasNext();) {  
  813.                                                                // goto L22  
  814.                                                                if (arraylist1.contains(iterator.next()))  
  815.                                                                       nCounter++;  
  816.                                                         }  
  817.                                                         // goto L21  
  818.                                                         int k4 = arraylist.size() - nCounter;  
  819.                                                         int l4 = arraylist1.size() - nCounter;  
  820.    
  821.                                                         if (k4 + l4 > nCounter)  
  822.                                                                flag = true;  
  823.                                                         else  
  824.                                                                flag = false;  
  825.                                                         if (flag) {  
  826.                                                                StringBuilder stringbuilder = new StringBuilder(k4).append(" + ");  
  827.                                                                stringbuilder.append(l4).append(" > ");  
  828.                                                                stringbuilder.append(nCounter);  
  829.                                                                CellLocationManager.this.debug(stringbuilder.toString());  
  830.                                                         }  
  831.                                                         break;  
  832.    
  833.                                                  } else {  
  834.                                                         // L15  
  835.                                                         flag = true;  
  836.                                                         CellLocationManager.this.debug("PRIMARY CELL CHANGED");  
  837.                                                         // goto L14  
  838.                                                         if (flag) {  
  839.                                                                requestUpdate();  
  840.                                                         } else {  
  841.                                                                this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, CellLocationManager.CHECK_INTERVAL);  
  842.                                                         }  
  843.                                                  }  
  844.                                           } else {  
  845.                                                  // L12  
  846.                                                  flag = true;  
  847.                                                  // goto L14  
  848.                                                  if (flag) {  
  849.                                                         requestUpdate();  
  850.                                                  } else {  
  851.                                                         this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH,CellLocationManager.CHECK_INTERVAL);  
  852.                                                  }  
  853.                                           }  
  854.    
  855.                                    }  
  856.    
  857.                             }  
  858.    
  859.                      }  
  860.               }  
  861.        }  
  862.    
  863.        class Task extends UserTask<JSONArray, Void, Void> {  
  864.               int accuracy;  
  865.               int bid;  
  866.               int[] cells;  
  867.               double lat;  
  868.               double lng;  
  869.               long time;  
  870.    
  871.               public Task(int[] aryCell, int bid) {  
  872.                      this.time = System.currentTimeMillis();  
  873.                      this.cells = aryCell;  
  874.                      this.bid = bid;  
  875.               }  
  876.    
  877.               public Void doInBackground(JSONArray[] paramArrayOfJSONArray) {  
  878.                      try {  
  879.                             JSONObject jsonObject = new JSONObject();  
  880.                             jsonObject.put("version""1.1.0");  
  881.                             jsonObject.put("host""maps.google.com");  
  882.                             jsonObject.put("address_language""zh_CN");  
  883.                             jsonObject.put("request_address"true);  
  884.                             jsonObject.put("radio_type""gsm");  
  885.                             jsonObject.put("carrier""HTC");  
  886.                             JSONArray cellJson = paramArrayOfJSONArray[0];  
  887.                             jsonObject.put("cell_towers", cellJson);  
  888.                             JSONArray wifiJson = paramArrayOfJSONArray[1];  
  889.                             jsonObject.put("wifi_towers", wifiJson);  
  890.                             DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();  
  891.                             HttpPost localHttpPost = new HttpPost("http://www.google.com/loc/json");  
  892.                             String strJson = jsonObject.toString();  
  893.                             StringEntity objJsonEntity = new StringEntity(strJson);  
  894.                             localHttpPost.setEntity(objJsonEntity);  
  895.                             HttpResponse objResponse = localDefaultHttpClient.execute(localHttpPost);  
  896.                             int nStateCode = objResponse.getStatusLine().getStatusCode();  
  897.                             HttpEntity httpEntity = objResponse.getEntity();  
  898.                             byte[] arrayOfByte = null;  
  899.                             if (nStateCode / 100 == 2)  
  900.                                    arrayOfByte = EntityUtils.toByteArray(httpEntity);  
  901.                             httpEntity.consumeContent();  
  902.                             String strResponse = new String(arrayOfByte, "UTF-8");  
  903.                             jsonObject = new JSONObject(strResponse);  
  904.                             this.lat = jsonObject.getJSONObject("location").getDouble("latitude");  
  905.                             this.lng = jsonObject.getJSONObject("location").getDouble("longitude");  
  906.                             this.accuracy = jsonObject.getJSONObject("location").getInt("accuracy");;  
  907.                      } catch (Exception localException) {  
  908.                             return null;  
  909.                      }  
  910.                      return null;  
  911.               }  
  912.    
  913.               public void onPostExecute(Void paramVoid) {  
  914.                      if (CellLocationManager.this.state != CellLocationManager.STATE_SENDING || CellLocationManager.this.task != this)  
  915.                             return;  
  916.                      if ((this.lat != 0.0D) && (this.lng != 0.0D)) {  
  917.                             CellLocationManager.this.timestamp = this.time;  
  918.                             CellLocationManager.this.latitude = this.lat;  
  919.                             CellLocationManager.this.longitude = this.lng;  
  920.                             CellLocationManager.this.accuracy = this.accuracy;  
  921.                             CellLocationManager.this.aryGsmCells = this.cells;  
  922.                             CellLocationManager.this.bid = this.bid;  
  923.                             StringBuilder sb = new StringBuilder("CELL LOCATION DONE: (");  
  924.                             sb.append(this.lat).append(",").append(this.lng).append(")");  
  925.                             CellLocationManager.this.debug(sb.toString());  
  926.                             CellLocationManager.this.state = STATE_READY;  
  927.                             CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, CellLocationManager.CHECK_INTERVAL);  
  928.                             CellLocationManager.this.onLocationChanged();  
  929.                      } else {  
  930.                             CellLocationManager.this.task = null;  
  931.                             CellLocationManager.this.state = CellLocationManager.STATE_READY;  
  932.                             CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, 5000L);  
  933.                      }  
  934.               }  
  935.        }  
  936.    
  937.        private class CellLocationManagerBroadcastReceiver extends BroadcastReceiver {  
  938.    
  939.               @Override  
  940.               public void onReceive(Context arg0, Intent intent) {  
  941.                      // access$0 state  
  942.                      // 1 debug  
  943.                      // access$2 loop  
  944.                      // 3 startScanTimestamp  
  945.                      // 4 disableWifiAfterScan  
  946.                      // 5 wifimanager  
  947.                      if (CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING)  
  948.                             return;  
  949.                      String s = intent.getAction();  
  950.                      if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(s)) { // goto _L4; else goto _L3  
  951.                      // _L3:  
  952.                             CellLocationManager.this.debug("WIFI SCAN COMPLETE");  
  953.                             CellLocationManager.this.looper.removeMessages(MESSAGE_COLLECTING_WIFI);  
  954.                             long lInterval = System.currentTimeMillis() - CellLocationManager.this.startScanTimestamp;  
  955.                             if (lInterval > 4000L)  
  956.                                    CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, 4000L);  
  957.                             else  
  958.                                    CellLocationManager.this.looper.sendEmptyMessage(MESSAGE_COLLECTING_WIFI);  
  959.                      } else {  
  960.                             // _L4:  
  961.                             if (!CellLocationManager.this.waiting4WifiEnable)  
  962.                                    return;  
  963.                             String s1 = intent.getAction();  
  964.                             if (!WifiManager.WIFI_STATE_CHANGED_ACTION.equals(s1))  
  965.                                    return;  
  966.                             int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 4);  
  967.                             // _L5:  
  968.                             if (wifiState == WifiManager.WIFI_STATE_ENABLING) {  
  969.                                    boolean flag2 = CellLocationManager.this.wifiManager.wifiManager().startScan();  
  970.                                    // _L8:  
  971.                                    CellLocationManager.this.disableWifiAfterScan = true;  
  972.                                    CellLocationManager.this.paused = false;  
  973. //                                 int i = flag2 ? 1 : 0;  
  974. //                                 int nDelay = i != 0 ? 8000 : 0;  
  975. //                                 CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, nDelay);  
  976.                                    CellLocationManager.this.debug("WIFI ENABLED");  
  977.                             }  
  978.                      }  
  979.               }  
  980.        }  
  981.    
  982. }  
  983.    
  984. 调用方法:  
  985.    
  986.        CellInfoManager cellManager = new CellInfoManager(this);  
  987.               WifiInfoManager wifiManager = new WifiInfoManager(this);  
  988.               CellLocationManager locationManager = new CellLocationManager(this, cellManager, wifiManager) {  
  989.                       
  990.                      @Override  
  991.                      public void onLocationChanged() {  
  992.                             txtAutoNaviInfo.setText(this.latitude() + "-" + this.longitude());  
  993.                             this.stop();  
  994.                              
  995.                      }  
  996.               };  
  997.               locationManager.start();  
  998. 如果还想同时使用GPS定位,其实也很简单,可以和FourSquare提供的BestLocationListener结合起来,将上面那段代码添加到BestLocationListener的register方法里:  
  999.    
  1000.  public void register(LocationManager locationManager, boolean gps, Context context) {  
  1001.         if (DEBUG) Log.d(TAG, "Registering this location listener: " + this.toString());  
  1002.         long updateMinTime = SLOW_LOCATION_UPDATE_MIN_TIME;  
  1003.         long updateMinDistance = SLOW_LOCATION_UPDATE_MIN_DISTANCE;  
  1004.         if (gps) {  
  1005.             updateMinTime = LOCATION_UPDATE_MIN_TIME;  
  1006.             updateMinDistance = LOCATION_UPDATE_MIN_DISTANCE;  
  1007.         }  
  1008.         List<String> providers = locationManager.getProviders(true);  
  1009.         int providersCount = providers.size();  
  1010.         if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){  
  1011.                setChanged();  
  1012.                notifyObservers(null);  
  1013.         }  
  1014.         for (int i = 0; i < providersCount; i++) {  
  1015.             String providerName = providers.get(i);  
  1016.             if (locationManager.isProviderEnabled(providerName)) {  
  1017.                 updateLocation(locationManager.getLastKnownLocation(providerName));  
  1018.             }  
  1019.             // Only register with GPS if we've explicitly allowed it.  
  1020.             if (gps || !LocationManager.GPS_PROVIDER.equals(providerName)) {  
  1021.                 locationManager.requestLocationUpdates(providerName, updateMinTime,  
  1022.                         updateMinDistance, this);  
  1023.             }  
  1024.              
  1025.         }  
  1026.          
  1027.         if(cellLocationManager == null) {  
  1028.                CellInfoManager cellManager = new CellInfoManager(context);  
  1029.                  WifiInfoManager wifiManager = new WifiInfoManager(context);  
  1030.                  cellLocationManager = new CellLocationManager(context, cellManager, wifiManager) {  
  1031.                         @Override  
  1032.                         public void onLocationChanged() {  
  1033.                                if ((latitude() == 0.0D) || (longitude() == 0.0D)) return;  
  1034.                                Location result = new Location("CellLocationManager");  
  1035.                                result.setLatitude(latitude());  
  1036.                                result.setLongitude(longitude());  
  1037.                                result.setAccuracy(accuracy());  
  1038.                                onBestLocationChanged(result);  
  1039.                                this.stop();  
  1040.                         }  
  1041.                  };  
  1042.         }  
  1043.         //cellLocationManager.stop();  
  1044.         cellLocationManager.start();  
  1045. //        LocationController controller = LocationController.requestLocationUpdates("", updateMinTime,updateMinDistance, this, context);  
  1046. //        controller.requestCurrentLocation();  
  1047.     }  



评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值