来自: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. importjava.lang.reflect.Method;
  3. importjava.util.Iterator;
  4. importjava.util.List;
  5. importorg.json.JSONArray;
  6. importorg.json.JSONException;
  7. importorg.json.JSONObject;
  8. importandroid.content.Context;
  9. importandroid.telephony.CellLocation;
  10. importandroid.telephony.NeighboringCellInfo;
  11. importandroid.telephony.PhoneStateListener;
  12. importandroid.telephony.TelephonyManager;
  13. importandroid.telephony.gsm.GsmCellLocation;
  14. importandroid.util.Log;
  15. publicclassCellInfoManager{
  16. privateintasu;
  17. privateintbid;
  18. privateintcid;
  19. privatebooleanisCdma;
  20. privatebooleanisGsm;
  21. privateintlac;
  22. privateintlat;
  23. privatefinalPhoneStateListenerlistener;
  24. privateintlng;
  25. privateintmcc;
  26. privateintmnc;
  27. privateintnid;
  28. privateintsid;
  29. privateTelephonyManagertel;
  30. privatebooleanvalid;
  31. privateContextcontext;
  32. publicCellInfoManager(ContextparamContext){
  33. this.listener=newCellInfoListener(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. publicstaticintdBm(inti){
  39. intj;
  40. if(i>=0&&i<=31)
  41. j=i*2+-113;
  42. else
  43. j=0;
  44. returnj;
  45. }
  46. publicintasu(){
  47. returnthis.asu;
  48. }
  49. publicintbid(){
  50. if(!this.valid)
  51. update();
  52. returnthis.bid;
  53. }
  54. publicJSONObjectcdmaInfo(){
  55. if(!isCdma()){
  56. returnnull;
  57. }
  58. JSONObjectjsonObject=newJSONObject();
  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(JSONExceptionex){
  66. jsonObject=null;
  67. Log.e("CellInfoManager",ex.getMessage());
  68. }
  69. returnjsonObject;
  70. }
  71. publicJSONArraycellTowers(){
  72. JSONArrayjsonarray=newJSONArray();
  73. intlat;
  74. intmcc;
  75. intmnc;
  76. intaryCell[]=dumpCells();
  77. lat=lac();
  78. mcc=mcc();
  79. mnc=mnc();
  80. if(aryCell==null||aryCell.length<2){
  81. aryCell=newint[2];
  82. aryCell[0]=cid;
  83. aryCell[1]=-60;
  84. }
  85. for(inti=0;i<aryCell.length;i+=2){
  86. try{
  87. intj2=dBm(i+1);
  88. JSONObjectjsonobject=newJSONObject();
  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(Exceptionex){
  97. ex.printStackTrace();
  98. Log.e("CellInfoManager",ex.getMessage());
  99. }
  100. }
  101. if(isCdma())
  102. jsonarray=newJSONArray();
  103. returnjsonarray;
  104. }
  105. publicintcid(){
  106. if(!this.valid)
  107. update();
  108. returnthis.cid;
  109. }
  110. publicint[]dumpCells(){
  111. int[]aryCells;
  112. if(cid()==0){
  113. aryCells=newint[0];
  114. returnaryCells;
  115. }
  116. List<NeighboringCellInfo>lsCellInfo=this.tel.getNeighboringCellInfo();
  117. if(lsCellInfo==null||lsCellInfo.size()==0){
  118. aryCells=newint[1];
  119. inti=cid();
  120. aryCells[0]=i;
  121. returnaryCells;
  122. }
  123. int[]arrayOfInt1=newint[lsCellInfo.size()*2+2];
  124. intj=0+1;
  125. intk=cid();
  126. arrayOfInt1[0]=k;
  127. intm=j+1;
  128. intn=asu();
  129. arrayOfInt1[j]=n;
  130. Iterator<NeighboringCellInfo>iter=lsCellInfo.iterator();
  131. while(true){
  132. if(!iter.hasNext()){
  133. break;
  134. }
  135. NeighboringCellInfolocalNeighboringCellInfo=(NeighboringCellInfo)iter.next();
  136. inti2=localNeighboringCellInfo.getCid();
  137. if((i2<=0)||(i2==65535))
  138. continue;
  139. inti3=m+1;
  140. arrayOfInt1[m]=i2;
  141. m=i3+1;
  142. inti4=localNeighboringCellInfo.getRssi();
  143. arrayOfInt1[i3]=i4;
  144. }
  145. int[]arrayOfInt2=newint[m];
  146. System.arraycopy(arrayOfInt1,0,arrayOfInt2,0,m);
  147. aryCells=arrayOfInt2;
  148. returnaryCells;
  149. }
  150. publicJSONObjectgsmInfo(){
  151. if(!isGsm()){
  152. returnnull;
  153. }
  154. JSONObjectlocalObject=null;
  155. while(true){
  156. try{
  157. JSONObjectlocalJSONObject1=newJSONObject();
  158. Stringstr1=this.tel.getNetworkOperatorName();
  159. localJSONObject1.put("operator",str1);
  160. Stringstr2=this.tel.getNetworkOperator();
  161. if((str2.length()==5)||(str2.length()==6)){
  162. Stringstr3=str2.substring(0,3);
  163. Stringstr4=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. JSONArraylocalJSONArray1=newJSONArray();
  170. intk=0;
  171. intm=arrayOfInt.length/2;
  172. while(true){
  173. if(k>=m){
  174. localJSONObject1.put("cells",localJSONArray1);
  175. localObject=localJSONObject1;
  176. break;
  177. }
  178. intn=k*2;
  179. inti1=arrayOfInt[n];
  180. inti2=k*2+1;
  181. inti3=arrayOfInt[i2];
  182. JSONObjectlocalJSONObject7=newJSONObject();
  183. localJSONObject7.put("cid",i1);
  184. localJSONObject7.put("asu",i3);
  185. localJSONArray1.put(localJSONObject7);
  186. k+=1;
  187. }
  188. }catch(JSONExceptionlocalJSONException){
  189. localObject=null;
  190. }
  191. }
  192. }
  193. publicbooleanisCdma(){
  194. if(!this.valid)
  195. update();
  196. returnthis.isCdma;
  197. }
  198. publicbooleanisGsm(){
  199. if(!this.valid)
  200. update();
  201. returnthis.isGsm;
  202. }
  203. publicintlac(){
  204. if(!this.valid)
  205. update();
  206. returnthis.lac;
  207. }
  208. publicintlat(){
  209. if(!this.valid)
  210. update();
  211. returnthis.lat;
  212. }
  213. publicintlng(){
  214. if(!this.valid)
  215. update();
  216. returnthis.lng;
  217. }
  218. publicintmcc(){
  219. if(!this.valid)
  220. update();
  221. returnthis.mcc;
  222. }
  223. publicintmnc(){
  224. if(!this.valid)
  225. update();
  226. returnthis.mnc;
  227. }
  228. publicintnid(){
  229. if(!this.valid)
  230. update();
  231. returnthis.nid;
  232. }
  233. publicfloatscore(){
  234. floatf1=0f;
  235. int[]aryCells=null;
  236. inti=0;
  237. floatf2=0f;
  238. if(isCdma()){
  239. f2=1065353216;
  240. returnf2;
  241. }
  242. if(isGsm()){
  243. f1=0.0F;
  244. aryCells=dumpCells();
  245. intj=aryCells.length;
  246. if(i>=j)
  247. f2=f1;
  248. }
  249. if(i<=0){
  250. return1065353216;
  251. }
  252. intm=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. returnf2;
  261. }
  262. publicintsid(){
  263. if(!this.valid)
  264. update();
  265. returnthis.sid;
  266. }
  267. publicvoidupdate(){
  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. CellLocationcellLocation=this.tel.getCellLocation();
  275. intnPhoneType=this.tel.getPhoneType();
  276. if(nPhoneType==1&&cellLocationinstanceofGsmCellLocation){
  277. this.isGsm=true;
  278. GsmCellLocationgsmCellLocation=(GsmCellLocation)cellLocation;
  279. intnGSMCID=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. StringstrNetworkOperator=this.tel.getNetworkOperator();
  289. intnNetworkOperatorLength=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=newClass[0];
  301. MethodlocalMethod1=clsCellLocation.getMethod("getBaseStationId",aryClass);
  302. MethodlocalMethod2=clsCellLocation.getMethod("getSystemId",aryClass);
  303. MethodlocalMethod3=clsCellLocation.getMethod("getNetworkId",aryClass);
  304. Object[]aryDummy=newObject[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. MethodlocalMethod7=clsCellLocation.getMethod("getBaseStationLatitude",aryClass);
  309. MethodlocalMethod8=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(Exceptionex){
  315. Log.e("CellInfoManager",ex.getMessage());
  316. }
  317. }
  318. classCellInfoListenerextendsPhoneStateListener{
  319. CellInfoListener(CellInfoManagermanager){
  320. }
  321. publicvoidonCellLocationChanged(CellLocationparamCellLocation){
  322. CellInfoManager.this.valid=false;
  323. }
  324. publicvoidonSignalStrengthChanged(intparamInt){
  325. CellInfoManager.this.asu=paramInt;
  326. }
  327. }
  328. }
  329. WifiInfoManager
  330. importjava.util.ArrayList;
  331. importjava.util.Iterator;
  332. importjava.util.List;
  333. importorg.json.JSONArray;
  334. importorg.json.JSONObject;
  335. importandroid.content.Context;
  336. importandroid.net.wifi.ScanResult;
  337. importandroid.net.wifi.WifiManager;
  338. importandroid.util.Log;
  339. publicclassWifiInfoManager{
  340. privateWifiManagerwifiManager;
  341. publicWifiInfoManager(ContextparamContext){
  342. this.wifiManager=(WifiManager)paramContext.getSystemService(Context.WIFI_SERVICE);
  343. }
  344. publicList<WifiInfo>dump(){
  345. if(!this.wifiManager.isWifiEnabled()){
  346. returnnewArrayList<WifiInfo>();
  347. }
  348. android.net.wifi.WifiInfowifiConnection=this.wifiManager.getConnectionInfo();
  349. WifiInfocurrentWIFI=null;
  350. if(wifiConnection!=null){
  351. Strings=wifiConnection.getBSSID();
  352. inti=wifiConnection.getRssi();
  353. Strings1=wifiConnection.getSSID();
  354. currentWIFI=newWifiInfo(s,i,s1);
  355. }
  356. ArrayList<WifiInfo>lsAllWIFI=newArrayList<WifiInfo>();
  357. if(currentWIFI!=null){
  358. lsAllWIFI.add(currentWIFI);
  359. }
  360. List<ScanResult>lsScanResult=this.wifiManager.getScanResults();
  361. for(ScanResultresult:lsScanResult){
  362. WifiInfoscanWIFI=newWifiInfo(result);
  363. if(!scanWIFI.equals(currentWIFI))
  364. lsAllWIFI.add(scanWIFI);
  365. }
  366. returnlsAllWIFI;
  367. }
  368. publicbooleanisWifiEnabled(){
  369. returnthis.wifiManager.isWifiEnabled();
  370. }
  371. publicJSONArraywifiInfo(){
  372. JSONArrayjsonArray=newJSONArray();
  373. for(WifiInfowifi:dump()){
  374. JSONObjectlocalJSONObject=wifi.info();
  375. jsonArray.put(localJSONObject);
  376. }
  377. returnjsonArray;
  378. }
  379. publicWifiManagerwifiManager(){
  380. returnthis.wifiManager;
  381. }
  382. publicJSONArraywifiTowers(){
  383. JSONArrayjsonArray=newJSONArray();
  384. try{
  385. Iterator<WifiInfo>localObject=dump().iterator();
  386. while(true){
  387. if(!(localObject).hasNext()){
  388. returnjsonArray;
  389. }
  390. jsonArray.put(localObject.next().wifi_tower());
  391. }
  392. }catch(ExceptionlocalException){
  393. Log.e("location",localException.getMessage());
  394. }
  395. returnjsonArray;
  396. }
  397. publicclassWifiInfoimplementsComparable<WifiInfo>{
  398. publicintcompareTo(WifiInfowifiinfo){
  399. inti=wifiinfo.dBm;
  400. intj=dBm;
  401. returni-j;
  402. }
  403. publicbooleanequals(Objectobj){
  404. booleanflag=false;
  405. if(obj==this){
  406. flag=true;
  407. returnflag;
  408. }else{
  409. if(objinstanceofWifiInfo){
  410. WifiInfowifiinfo=(WifiInfo)obj;
  411. inti=wifiinfo.dBm;
  412. intj=dBm;
  413. if(i==j){
  414. Strings=wifiinfo.bssid;
  415. Strings1=bssid;
  416. if(s.equals(s1)){
  417. flag=true;
  418. returnflag;
  419. }
  420. }
  421. flag=false;
  422. }else{
  423. flag=false;
  424. }
  425. }
  426. returnflag;
  427. }
  428. publicinthashCode(){
  429. inti=dBm;
  430. intj=bssid.hashCode();
  431. returni^j;
  432. }
  433. publicJSONObjectinfo(){
  434. JSONObjectjsonobject=newJSONObject();
  435. try{
  436. Strings=bssid;
  437. jsonobject.put("mac",s);
  438. Strings1=ssid;
  439. jsonobject.put("ssid",s1);
  440. inti=dBm;
  441. jsonobject.put("dbm",i);
  442. }catch(Exceptionex){
  443. }
  444. returnjsonobject;
  445. }
  446. publicJSONObjectwifi_tower(){
  447. JSONObjectjsonobject=newJSONObject();
  448. try{
  449. Strings=bssid;
  450. jsonobject.put("mac_address",s);
  451. inti=dBm;
  452. jsonobject.put("signal_strength",i);
  453. Strings1=ssid;
  454. jsonobject.put("ssid",s1);
  455. jsonobject.put("age",0);
  456. }catch(Exceptionex){
  457. }
  458. returnjsonobject;
  459. }
  460. publicfinalStringbssid;
  461. publicfinalintdBm;
  462. publicfinalStringssid;
  463. publicWifiInfo(ScanResultscanresult){
  464. Strings=scanresult.BSSID;
  465. bssid=s;
  466. inti=scanresult.level;
  467. dBm=i;
  468. Strings1=scanresult.SSID;
  469. ssid=s1;
  470. }
  471. publicWifiInfo(Strings,inti,Strings1){
  472. bssid=s;
  473. dBm=i;
  474. ssid=s1;
  475. }
  476. }
  477. }
  478. CellLocationManager
  479. importjava.util.ArrayList;
  480. importjava.util.Iterator;
  481. importjava.util.List;
  482. importorg.apache.http.HttpEntity;
  483. importorg.apache.http.HttpResponse;
  484. importorg.apache.http.client.methods.HttpPost;
  485. importorg.apache.http.entity.StringEntity;
  486. importorg.apache.http.impl.client.DefaultHttpClient;
  487. importorg.apache.http.util.EntityUtils;
  488. importorg.json.JSONArray;
  489. importorg.json.JSONObject;
  490. importandroid.content.BroadcastReceiver;
  491. importandroid.content.Context;
  492. importandroid.content.Intent;
  493. importandroid.content.IntentFilter;
  494. importandroid.net.ConnectivityManager;
  495. importandroid.net.NetworkInfo;
  496. importandroid.net.wifi.WifiManager;
  497. importandroid.os.Handler;
  498. importandroid.os.Message;
  499. importandroid.telephony.CellLocation;
  500. importandroid.util.Log;
  501. importandroid.widget.Toast;
  502. importcom.google.android.photostream.UserTask;
  503. publicabstractclassCellLocationManager{
  504. publicstaticintCHECK_INTERVAL=15000;
  505. publicstaticbooleanENABLE_WIFI=true;
  506. privatestaticbooleanIS_DEBUG=false;
  507. privatestaticfinalintSTATE_COLLECTING=2;
  508. privatestaticfinalintSTATE_IDLE=0;
  509. privatestaticfinalintSTATE_READY=1;
  510. privatestaticfinalintSTATE_SENDING=3;
  511. privatestaticfinalintMESSAGE_INITIALIZE=1;
  512. privatestaticfinalintMESSAGE_COLLECTING_CELL=2;
  513. privatestaticfinalintMESSAGE_COLLECTING_WIFI=5;
  514. privatestaticfinalintMESSAGE_BEFORE_FINISH=10;
  515. privateintaccuracy;
  516. privateintbid;
  517. privateCellInfoManagercellInfoManager;
  518. privateContextcontext;
  519. privatebooleandisableWifiAfterScan;
  520. privateint[]aryGsmCells;
  521. privatedoublelatitude;
  522. privatedoublelongitude;
  523. privateMyLooperlooper;
  524. privatebooleanpaused;
  525. privatefinalBroadcastReceiverreceiver;
  526. privatelongstartScanTimestamp;
  527. privateintstate;
  528. privateTasktask;
  529. privatelongtimestamp;
  530. privatebooleanwaiting4WifiEnable;
  531. privateWifiInfoManagerwifiManager;
  532. publicCellLocationManager(Contextcontext,CellInfoManagercellinfomanager,WifiInfoManagerwifiinfomanager){
  533. receiver=newCellLocationManagerBroadcastReceiver();
  534. this.context=context.getApplicationContext();
  535. cellInfoManager=cellinfomanager;
  536. wifiManager=wifiinfomanager;
  537. }
  538. privatevoiddebug(ObjectparamObject){
  539. if(IS_DEBUG){
  540. System.out.println(paramObject);
  541. Stringstr=String.valueOf(paramObject);
  542. Toast.makeText(this.context,str,Toast.LENGTH_SHORT).show();
  543. }
  544. }
  545. publicintaccuracy(){
  546. returnthis.accuracy;
  547. }
  548. publicdoublelatitude(){
  549. returnthis.latitude;
  550. }
  551. publicdoublelongitude(){
  552. returnthis.longitude;
  553. }
  554. publicabstractvoidonLocationChanged();
  555. publicvoidpause(){
  556. if(state>0&&!paused){
  557. looper.removeMessages(MESSAGE_BEFORE_FINISH);
  558. paused=true;
  559. }
  560. }
  561. publicvoidrequestUpdate(){
  562. if(state!=STATE_READY){
  563. return;
  564. }
  565. booleanbStartScanSuccessful=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. intnDelay=0;
  576. if(!bStartScanSuccessful)
  577. nDelay=8000;
  578. looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI,nDelay);
  579. debug("CELLUPDATE");
  580. }else{
  581. waiting4WifiEnable=true;
  582. }
  583. }
  584. }
  585. publicvoidresume(){
  586. if(state>0&&paused){
  587. paused=false;
  588. looper.removeMessages(MESSAGE_BEFORE_FINISH);
  589. looper.sendEmptyMessage(MESSAGE_BEFORE_FINISH);
  590. }
  591. }
  592. publicvoidstart(){
  593. if(state<=STATE_IDLE){
  594. Log.i("CellLocationManager","Starting...");
  595. context.registerReceiver(receiver,newIntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
  596. context.registerReceiver(receiver,newIntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
  597. looper=newMyLooper();
  598. state=STATE_READY;
  599. paused=false;
  600. waiting4WifiEnable=false;
  601. disableWifiAfterScan=false;
  602. debug("CELLLOCATIONSTART");
  603. requestUpdate();
  604. }
  605. }
  606. publicvoidstop(){
  607. if(state>STATE_IDLE){
  608. context.unregisterReceiver(receiver);
  609. debug("CELLLOCATIONSTOP");
  610. looper=null;
  611. state=STATE_IDLE;
  612. if(disableWifiAfterScan){
  613. disableWifiAfterScan=false;
  614. wifiManager.wifiManager().setWifiEnabled(false);
  615. }
  616. }
  617. }
  618. publiclongtimestamp(){
  619. returnthis.timestamp;
  620. }
  621. protectedbooleanisConnectedWithInternet(){
  622. ConnectivityManagerconManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  623. NetworkInfonetworkInfo=conManager.getActiveNetworkInfo();
  624. if(networkInfo!=null){
  625. returnnetworkInfo.isAvailable();
  626. }
  627. returnfalse;
  628. }
  629. privateclassMyLooperextendsHandler{
  630. privatefloatfCellScore;
  631. privateJSONArrayobjCellTowersJson;
  632. publicvoidhandleMessage(MessageparamMessage){
  633. if(CellLocationManager.this.looper!=this)
  634. return;
  635. booleanflag=true;
  636. switch(paramMessage.what){
  637. default:
  638. break;
  639. caseMESSAGE_INITIALIZE:
  640. this.objCellTowersJson=null;
  641. this.fCellScore=1.401298E-045F;
  642. caseMESSAGE_COLLECTING_CELL:
  643. if(CellLocationManager.this.state!=CellLocationManager.STATE_COLLECTING)
  644. break;
  645. JSONArrayobjCellTowers=CellLocationManager.this.cellInfoManager.cellTowers();
  646. floatfCellScore=CellLocationManager.this.cellInfoManager.score();
  647. if(objCellTowers!=null){
  648. floatfCurrentCellScore=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. caseMESSAGE_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. intnBid=CellLocationManager.this.cellInfoManager.bid();
  670. CellLocationManager.this.task=newCellLocationManager.Task(aryCell,nBid);
  671. JSONArray[]aryJsonArray=newJSONArray[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("Postjson");
  679. CellLocationManager.this.task.execute(aryJsonArray);
  680. break;
  681. caseMESSAGE_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. intnFirstCellId=CellLocationManager.this.aryGsmCells[0];
  710. if(nFirstCellId==aryCells[0]){
  711. //L16
  712. intcellLength=CellLocationManager.this.aryGsmCells.length/2;
  713. List<Integer>arraylist=newArrayList<Integer>(cellLength);
  714. List<Integer>arraylist1=newArrayList<Integer>(aryCells.length/2);
  715. intnIndex=0;
  716. intnGSMCellLength=CellLocationManager.this.aryGsmCells.length;
  717. while(nIndex<nGSMCellLength){
  718. //gotoL18
  719. arraylist.add(CellLocationManager.this.aryGsmCells[nIndex]);
  720. nIndex+=2;
  721. }
  722. //gotoL17
  723. nIndex=0;
  724. while(nIndex<aryCells.length){
  725. //gotoL20
  726. arraylist1.add(aryCells[nIndex]);
  727. nIndex+=2;
  728. }
  729. //gotoL19
  730. intnCounter=0;
  731. for(Iterator<Integer>iterator=arraylist.iterator();iterator.hasNext();){
  732. //gotoL22
  733. if(arraylist1.contains(iterator.next()))
  734. nCounter++;
  735. }
  736. //gotoL21
  737. intk4=arraylist.size()-nCounter;
  738. intl4=arraylist1.size()-nCounter;
  739. if(k4+l4>nCounter)
  740. flag=true;
  741. else
  742. flag=false;
  743. if(flag){
  744. StringBuilderstringbuilder=newStringBuilder(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("PRIMARYCELLCHANGED");
  754. //gotoL14
  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. //gotoL14
  765. if(flag){
  766. requestUpdate();
  767. }else{
  768. this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH,CellLocationManager.CHECK_INTERVAL);
  769. }
  770. }
  771. }
  772. }
  773. }
  774. }
  775. }
  776. classTaskextendsUserTask<JSONArray,Void,Void>{
  777. intaccuracy;
  778. intbid;
  779. int[]cells;
  780. doublelat;
  781. doublelng;
  782. longtime;
  783. publicTask(int[]aryCell,intbid){
  784. this.time=System.currentTimeMillis();
  785. this.cells=aryCell;
  786. this.bid=bid;
  787. }
  788. publicVoiddoInBackground(JSONArray[]paramArrayOfJSONArray){
  789. try{
  790. JSONObjectjsonObject=newJSONObject();
  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. JSONArraycellJson=paramArrayOfJSONArray[0];
  798. jsonObject.put("cell_towers",cellJson);
  799. JSONArraywifiJson=paramArrayOfJSONArray[1];
  800. jsonObject.put("wifi_towers",wifiJson);
  801. DefaultHttpClientlocalDefaultHttpClient=newDefaultHttpClient();
  802. HttpPostlocalHttpPost=newHttpPost("http://www.google.com/loc/json");
  803. StringstrJson=jsonObject.toString();
  804. StringEntityobjJsonEntity=newStringEntity(strJson);
  805. localHttpPost.setEntity(objJsonEntity);
  806. HttpResponseobjResponse=localDefaultHttpClient.execute(localHttpPost);
  807. intnStateCode=objResponse.getStatusLine().getStatusCode();
  808. HttpEntityhttpEntity=objResponse.getEntity();
  809. byte[]arrayOfByte=null;
  810. if(nStateCode/100==2)
  811. arrayOfByte=EntityUtils.toByteArray(httpEntity);
  812. httpEntity.consumeContent();
  813. StringstrResponse=newString(arrayOfByte,"UTF-8");
  814. jsonObject=newJSONObject(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(ExceptionlocalException){
  819. returnnull;
  820. }
  821. returnnull;
  822. }
  823. publicvoidonPostExecute(VoidparamVoid){
  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. StringBuildersb=newStringBuilder("CELLLOCATIONDONE:(");
  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. privateclassCellLocationManagerBroadcastReceiverextendsBroadcastReceiver{
  847. @Override
  848. publicvoidonReceive(Contextarg0,Intentintent){
  849. //access$0state
  850. //1debug
  851. //access$2loop
  852. //3startScanTimestamp
  853. //4disableWifiAfterScan
  854. //5wifimanager
  855. if(CellLocationManager.this.state!=CellLocationManager.STATE_COLLECTING)
  856. return;
  857. Strings=intent.getAction();
  858. if(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(s)){//goto_L4;elsegoto_L3
  859. //_L3:
  860. CellLocationManager.this.debug("WIFISCANCOMPLETE");
  861. CellLocationManager.this.looper.removeMessages(MESSAGE_COLLECTING_WIFI);
  862. longlInterval=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. Strings1=intent.getAction();
  872. if(!WifiManager.WIFI_STATE_CHANGED_ACTION.equals(s1))
  873. return;
  874. intwifiState=intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,4);
  875. //_L5:
  876. if(wifiState==WifiManager.WIFI_STATE_ENABLING){
  877. booleanflag2=CellLocationManager.this.wifiManager.wifiManager().startScan();
  878. //_L8:
  879. CellLocationManager.this.disableWifiAfterScan=true;
  880. CellLocationManager.this.paused=false;
  881. //inti=flag2?1:0;
  882. //intnDelay=i!=0?8000:0;
  883. //CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI,nDelay);
  884. CellLocationManager.this.debug("WIFIENABLED");
  885. }
  886. }
  887. }
  888. }
  889. }
  890. 调用方法:
  891. CellInfoManagercellManager=newCellInfoManager(this);
  892. WifiInfoManagerwifiManager=newWifiInfoManager(this);
  893. CellLocationManagerlocationManager=newCellLocationManager(this,cellManager,wifiManager){
  894. @Override
  895. publicvoidonLocationChanged(){
  896. txtAutoNaviInfo.setText(this.latitude()+"-"+this.longitude());
  897. this.stop();
  898. }
  899. };
  900. locationManager.start();
  901. 如果还想同时使用GPS定位,其实也很简单,可以和FourSquare提供的BestLocationListener结合起来,将上面那段代码添加到BestLocationListener的register方法里:
  902. publicvoidregister(LocationManagerlocationManager,booleangps,Contextcontext){
  903. if(DEBUG)Log.d(TAG,"Registeringthislocationlistener:"+this.toString());
  904. longupdateMinTime=SLOW_LOCATION_UPDATE_MIN_TIME;
  905. longupdateMinDistance=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. intprovidersCount=providers.size();
  912. if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)&&!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
  913. setChanged();
  914. notifyObservers(null);
  915. }
  916. for(inti=0;i<providersCount;i++){
  917. StringproviderName=providers.get(i);
  918. if(locationManager.isProviderEnabled(providerName)){
  919. updateLocation(locationManager.getLastKnownLocation(providerName));
  920. }
  921. //OnlyregisterwithGPSifwe'veexplicitlyallowedit.
  922. if(gps||!LocationManager.GPS_PROVIDER.equals(providerName)){
  923. locationManager.requestLocationUpdates(providerName,updateMinTime,
  924. updateMinDistance,this);
  925. }
  926. }
  927. if(cellLocationManager==null){
  928. CellInfoManagercellManager=newCellInfoManager(context);
  929. WifiInfoManagerwifiManager=newWifiInfoManager(context);
  930. cellLocationManager=newCellLocationManager(context,cellManager,wifiManager){
  931. @Override
  932. publicvoidonLocationChanged(){
  933. if((latitude()==0.0D)||(longitude()==0.0D))return;
  934. Locationresult=newLocation("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. //LocationControllercontroller=LocationController.requestLocationUpdates("",updateMinTime,updateMinDistance,this,context);
  946. //controller.requestCurrentLocation();
  947. }



更多相关文章

  1. android系统设置-修改睡眠时间,修改背光强度
  2. Android(安卓)得到当前已连接的wifi的信号强度
  3. Android里实现基站和WIFI定位
  4. android gps ,wifi ,基站定位集合
  5. android 3g状态及信号监测
  6. Android Bluetooth 蓝牙强度Rssi
  7. Android之获取wifi信号强度
  8. Android iPhone 手机查看基站信息
  9. android 定位的几种方式介绍

随机推荐

  1. 一道php自增运算符题
  2. ThinkPHP的create方法的一系列操作
  3. PHP不区分大小写数组搜索函数[duplicate]
  4. PHP是否以不同方式(内部)处理数字索引数组?
  5. php中的PCRE 函数,正则表达式处理函数。
  6. 将SQL查询的SELECT子句解析为PHP数组
  7. php 模板框架之smarty 的下载和安装
  8. 编译php时遇到的错误
  9. Doctrine 2.0 entitymanager-> replace()等
  10. PHP和MySQL应用实战