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

真实可行的android 基站定位代码相关推荐

  1. Android基站定位

    Android基站定位   一.通过手机信号获取基站信息 通过TelephonyManager 获取lac:mcc:mnc:cell-id(基站信息)的解释: MCC,Mobile Country C ...

  2. Android基站定位——三基站(多基站)定位(三)

    转载请标明出处:http://blog.csdn.net/android_ls/article/details/8673532 这一篇基于:Android基站定位--单基站定位(二) 阐述几个概念: ...

  3. Android基站定位——单基站定位(二)

    转载请标明出处:http://blog.csdn.net/android_ls/article/details/8672856 基站定位原理:通过手机信号获取基站信息,然后调用第三方公开的根据基站信息 ...

  4. Android基站定位——通过手机信号获取基站信息(一)

    转载请标明出处:http://blog.csdn.net/android_ls/article/details/8672442 基站定位原理:通过手机信号获取基站信息,然后调用第三方公开的根据基站信息 ...

  5. Android 基站定位源代码

    经过几天的调研以及测试,终于解决了联通2G.移动2G.电信3G的基站定位代码.团队里面只有这些机器的制式了.下面就由我来做一个详细的讲解吧. 1 相关技术内容 Google Android Api里面 ...

  6. 无线基站定位服务器,android 基站定位api

    android 基站定位api 内容精选 换一换 网络告警需要有确切的发生时间.所在网元.告警名称等信息,且告警能挂载于拓扑数据的网元之上.具体告警数据格式参见API文档.设备之间需要有确定的拓扑关系 ...

  7. Android基站定位——通过手机信号获取基站信息

    基站定位原理:通过手机信号获取基站信息,然后调用第三方公开的根据基站信息查找基站的经纬度值,想要具体地址信息的再根据经纬度值获取具体的地址信息. 一.通过手机信号获取基站信息 通过TelephonyM ...

  8. android 基站定位

    这里给大家分享下基站定位的实现,基站定位首先要通过TelephonyManager得到手机的信号信息,比如基站的国家编码,小区id等......得到这些后需要向google提供的接口提交这些参数,然后 ...

  9. android 基站定位 api,基站定位查询接口 - whoisliang的个人空间 - OSCHINA - 中文开源技术交流社区...

    本站查询接口免费开放 所有免费接口禁止从移动设备端直接访问,请使用固定IP的服务器转发请求. 每5分钟限制查询300次,基站/WIFI/经纬度查询接口每日限制查询1000次,反向基站查询接口每日限制查 ...

最新文章

  1. WSL:WSL(Windows Subsystem for Linux)的简介、安装、使用方法之详细攻略
  2. 腾讯云副总裁答治茜:移动互联网破局要借助“三张网”
  3. linux C/C++开发环境搭建指南
  4. 消息队列RabbitMQ入门与5种模式详解
  5. RE正则表达式与grep
  6. SaltStack Syndic配置
  7. 图像主观质量评价 评分_图像质量分析工具哪家强?
  8. Vue的批量更新原理
  9. 深度学习网络架构(三):VGG
  10. 2.10 数值分析: 条件数的定义及计算
  11. MapServer教程
  12. 城市与城乡规划用地分类和色块标准|CSV|C#程序|Excel
  13. 有趣的深度学习——使用 BERT 实现一个古体诗生成器
  14. 密码学系列之四:一文搞懂序列密码
  15. php后台登录页,后台登录页面模板源码
  16. 精进1-职业价值 by采铜
  17. 第二个c程序,日语208音练习
  18. 软件企业认定的标准要求
  19. 【爬虫实战】斗鱼直播(你想看的都有呀!)
  20. 2.6什么是VPS?为什么要用vps?一个vps可以跟几个mt4?

热门文章

  1. QAD2016EE的知识点
  2. VC,CString,UTF8与GBK互转
  3. 统计矢量数据占用三调国有建设用地部分面积
  4. 如何解决nas无公网问题,实现kodbox可道云内网映射外网访问
  5. 前端福音:Serverless 和 SSR 的天作之合
  6. 从ST官网获取标准外设库以及官方例程
  7. 如何在EditPlus、UltraEdit中正常显示韩文
  8. 易语言 ftp控制html,【原创】利用FTP实现软件自动更新
  9. 【无标题】一款功能非常强大的免费串口示波器串口助手,支持绘图,logo保存数据保存,历史数据加载与对比。
  10. iOS疯狂详解之自动布局(autolayout)下图片编辑器的实现