java wifi定位原理_Android里实现基站和WIFI定位

CellInfoManager

importjava.lang.reflect.Method;

importjava.util.Iterator;

importjava.util.List;

importorg.json.JSONArray;

importorg.json.JSONException;

importorg.json.JSONObject;

importandroid.content.Context;

importandroid.telephony.CellLocation;

importandroid.telephony.NeighboringCellInfo;

importandroid.telephony.PhoneStateListener;

importandroid.telephony.TelephonyManager;

importandroid.telephony.gsm.GsmCellLocation;

importandroid.util.Log;

publicclassCellInfoManager {

privateintasu;

privateintbid;

privateintcid;

privatebooleanisCdma;

privatebooleanisGsm;

privateintlac;

privateintlat;

privatefinalPhoneStateListener listener;

privateintlng;

privateintmcc;

privateintmnc;

privateintnid;

privateintsid;

privateTelephonyManager tel;

privatebooleanvalid;

privateContext context;

publicCellInfoManager(Context paramContext) {

this.listener =newCellInfoListener(this);

tel = (TelephonyManager) paramContext.getSystemService(Context.TELEPHONY_SERVICE);

this.tel.listen(this.listener, PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_SIGNAL_STRENGTH);

context = paramContext;

}

publicstaticintdBm(inti) {

intj;

if(i >=0&& i <=31)

j = i * 2+ -113;

else

j = 0;

returnj;

}

publicintasu() {

returnthis.asu;

}

publicintbid() {

if(!this.valid)

update();

returnthis.bid;

}

publicJSONObject cdmaInfo() {

if(!isCdma()) {

returnnull;

}

JSONObject jsonObject = newJSONObject();

try{

jsonObject.put("bid", bid());

jsonObject.put("sid", sid());

jsonObject.put("nid", nid());

jsonObject.put("lat", lat());

jsonObject.put("lng", lng());

} catch(JSONException ex) {

jsonObject = null;

Log.e("CellInfoManager", ex.getMessage());

}

returnjsonObject;

}

publicJSONArray cellTowers() {

JSONArray jsonarray = newJSONArray();

intlat;

intmcc;

intmnc;

intaryCell[] = dumpCells();

lat = lac();

mcc = mcc();

mnc = mnc();

if(aryCell ==null|| aryCell.length <2) {

aryCell = newint[2];

aryCell[0] = cid;

aryCell[1] = -60;

}

for(inti =0; i 

try{

intj2 = dBm(i +1);

JSONObject jsonobject = newJSONObject();

jsonobject.put("cell_id", aryCell[i]);

jsonobject.put("location_area_code", lat);

jsonobject.put("mobile_country_code", mcc);

jsonobject.put("mobile_network_code", mnc);

jsonobject.put("signal_strength", j2);

jsonobject.put("age",0);

jsonarray.put(jsonobject);

} catch(Exception ex) {

ex.printStackTrace();

Log.e("CellInfoManager", ex.getMessage());

}

}

if(isCdma())

jsonarray = newJSONArray();

returnjsonarray;

}

publicintcid() {

if(!this.valid)

update();

returnthis.cid;

}

publicint[] dumpCells() {

int[] aryCells;

if(cid() ==0) {

aryCells = newint[0];

returnaryCells;

}

List lsCellInfo = this.tel.getNeighboringCellInfo();

if(lsCellInfo ==null|| lsCellInfo.size() ==0) {

aryCells = newint[1];

inti = cid();

aryCells[0] = i;

returnaryCells;

}

int[] arrayOfInt1 =newint[lsCellInfo.size() *2+2];

intj =0+1;

intk = cid();

arrayOfInt1[0] = k;

intm = j +1;

intn = asu();

arrayOfInt1[j] = n;

Iterator iter = lsCellInfo.iterator();

while(true) {

if(!iter.hasNext()) {

break;

}

NeighboringCellInfo localNeighboringCellInfo = (NeighboringCellInfo) iter.next();

inti2 = localNeighboringCellInfo.getCid();

if((i2 <=0) || (i2 ==65535))

continue;

inti3 = m +1;

arrayOfInt1[m] = i2;

m = i3 + 1;

inti4 = localNeighboringCellInfo.getRssi();

arrayOfInt1[i3] = i4;

}

int[] arrayOfInt2 =newint[m];

System.arraycopy(arrayOfInt1, 0, arrayOfInt2,0, m);

aryCells = arrayOfInt2;

returnaryCells;

}

publicJSONObject gsmInfo() {

if(!isGsm()) {

returnnull;

}

JSONObject localObject = null;

while(true) {

try{

JSONObject localJSONObject1 = newJSONObject();

String str1 = this.tel.getNetworkOperatorName();

localJSONObject1.put("operator", str1);

String str2 = this.tel.getNetworkOperator();

if((str2.length() ==5) || (str2.length() ==6)) {

String str3 = str2.substring(0,3);

String str4 = str2.substring(3, str2.length());

localJSONObject1.put("mcc", str3);

localJSONObject1.put("mnc", str4);

}

localJSONObject1.put("lac", lac());

int[] arrayOfInt = dumpCells();

JSONArray localJSONArray1 = newJSONArray();

intk =0;

intm = arrayOfInt.length /2;

while(true) {

if(k >= m) {

localJSONObject1.put("cells", localJSONArray1);

localObject = localJSONObject1;

break;

}

intn = k *2;

inti1 = arrayOfInt[n];

inti2 = k *2+1;

inti3 = arrayOfInt[i2];

JSONObject localJSONObject7 = newJSONObject();

localJSONObject7.put("cid", i1);

localJSONObject7.put("asu", i3);

localJSONArray1.put(localJSONObject7);

k += 1;

}

} catch(JSONException localJSONException) {

localObject = null;

}

}

}

publicbooleanisCdma() {

if(!this.valid)

update();

returnthis.isCdma;

}

publicbooleanisGsm() {

if(!this.valid)

update();

returnthis.isGsm;

}

publicintlac() {

if(!this.valid)

update();

returnthis.lac;

}

publicintlat() {

if(!this.valid)

update();

returnthis.lat;

}

publicintlng() {

if(!this.valid)

update();

returnthis.lng;

}

publicintmcc() {

if(!this.valid)

update();

returnthis.mcc;

}

publicintmnc() {

if(!this.valid)

update();

returnthis.mnc;

}

publicintnid() {

if(!this.valid)

update();

returnthis.nid;

}

publicfloatscore() {

floatf1 = 0f;

int[] aryCells =null;

inti =0;

floatf2 = 0f;

if(isCdma()) {

f2 = 1065353216;

returnf2;

}

if(isGsm()) {

f1 = 0.0F;

aryCells = dumpCells();

intj = aryCells.length;

if(i >= j)

f2 = f1;

}

if(i <=0) {

return1065353216;

}

intm = aryCells[i];

for(i =0; i 

if((m <0) || (m >31))

f1 += 0.5F;

else

f1 += 1.0F;

}

f2 = f1;

returnf2;

}

publicintsid() {

if(!this.valid)

update();

returnthis.sid;

}

publicvoidupdate() {

this.isGsm =false;

this.isCdma =false;

this.cid =0;

this.lac =0;

this.mcc =0;

this.mnc =0;

CellLocation cellLocation = this.tel.getCellLocation();

intnPhoneType =this.tel.getPhoneType();

if(nPhoneType ==1&& cellLocationinstanceofGsmCellLocation) {

this.isGsm =true;

GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;

intnGSMCID = gsmCellLocation.getCid();

if(nGSMCID >0) {

if(nGSMCID !=65535) {

this.cid = nGSMCID;

this.lac = gsmCellLocation.getLac();

}

}

}

try{

String strNetworkOperator = this.tel.getNetworkOperator();

intnNetworkOperatorLength = strNetworkOperator.length();

if(nNetworkOperatorLength !=5) {

if(nNetworkOperatorLength !=6)

;

} else{

this.mcc = Integer.parseInt(strNetworkOperator.substring(0,3));

this.mnc = Integer.parseInt(strNetworkOperator.substring(3, nNetworkOperatorLength));

}

if(this.tel.getPhoneType() ==2) {

this.valid =true;

Class> clsCellLocation = cellLocation.getClass();

Class>[] aryClass = newClass[0];

Method localMethod1 = clsCellLocation.getMethod("getBaseStationId", aryClass);

Method localMethod2 = clsCellLocation.getMethod("getSystemId", aryClass);

Method localMethod3 = clsCellLocation.getMethod("getNetworkId", aryClass);

Object[] aryDummy = newObject[0];

this.bid = ((Integer) localMethod1.invoke(cellLocation, aryDummy)).intValue();

this.sid = ((Integer) localMethod2.invoke(cellLocation, aryDummy)).intValue();

this.nid = ((Integer) localMethod3.invoke(cellLocation, aryDummy)).intValue();

Method localMethod7 = clsCellLocation.getMethod("getBaseStationLatitude", aryClass);

Method localMethod8 = clsCellLocation.getMethod("getBaseStationLongitude", aryClass);

this.lat = ((Integer) localMethod7.invoke(cellLocation, aryDummy)).intValue();

this.lng = ((Integer) localMethod8.invoke(cellLocation, aryDummy)).intValue();

this.isCdma =true;

}

} catch(Exception ex) {

Log.e("CellInfoManager", ex.getMessage());

}

}

classCellInfoListenerextendsPhoneStateListener {

CellInfoListener(CellInfoManager manager) {

}

publicvoidonCellLocationChanged(CellLocation paramCellLocation) {

CellInfoManager.this.valid =false;

}

publicvoidonSignalStrengthChanged(intparamInt) {

CellInfoManager.this.asu = paramInt;

}

}

}

WifiInfoManager

importjava.util.ArrayList;

importjava.util.Iterator;

importjava.util.List;

importorg.json.JSONArray;

importorg.json.JSONObject;

importandroid.content.Context;

importandroid.net.wifi.ScanResult;

importandroid.net.wifi.WifiManager;

importandroid.util.Log;

publicclassWifiInfoManager {

privateWifiManager wifiManager;

publicWifiInfoManager(Context paramContext) {

this.wifiManager = (WifiManager) paramContext.getSystemService(Context.WIFI_SERVICE);

}

publicList dump() {

if(!this.wifiManager.isWifiEnabled()) {

returnnewArrayList();

}

android.net.wifi.WifiInfo wifiConnection = this.wifiManager.getConnectionInfo();

WifiInfo currentWIFI = null;

if(wifiConnection !=null) {

String s = wifiConnection.getBSSID();

inti = wifiConnection.getRssi();

String s1 = wifiConnection.getSSID();

currentWIFI = newWifiInfo(s, i, s1);

}

ArrayList lsAllWIFI = newArrayList();

if(currentWIFI !=null) {

lsAllWIFI.add(currentWIFI);

}

List lsScanResult = this.wifiManager.getScanResults();

for(ScanResult result : lsScanResult) {

WifiInfo scanWIFI = newWifiInfo(result);

if(!scanWIFI.equals(currentWIFI))

lsAllWIFI.add(scanWIFI);

}

returnlsAllWIFI;

}

publicbooleanisWifiEnabled() {

returnthis.wifiManager.isWifiEnabled();

}

publicJSONArray wifiInfo() {

JSONArray jsonArray = newJSONArray();

for(WifiInfo wifi : dump()) {

JSONObject localJSONObject = wifi.info();

jsonArray.put(localJSONObject);

}

returnjsonArray;

}

publicWifiManager wifiManager() {

returnthis.wifiManager;

}

publicJSONArray wifiTowers() {

JSONArray jsonArray = newJSONArray();

try{

Iterator localObject = dump().iterator();

while(true) {

if(!(localObject).hasNext()) {

returnjsonArray;

}

jsonArray.put(localObject.next().wifi_tower());

}

} catch(Exception localException) {

Log.e("location", localException.getMessage());

}

returnjsonArray;

}

publicclassWifiInfoimplementsComparable {

publicintcompareTo(WifiInfo wifiinfo) {

inti = wifiinfo.dBm;

intj = dBm;

returni - j;

}

publicbooleanequals(Object obj) {

booleanflag =false;

if(obj ==this) {

flag = true;

returnflag;

} else{

if(objinstanceofWifiInfo) {

WifiInfo wifiinfo = (WifiInfo) obj;

inti = wifiinfo.dBm;

intj = dBm;

if(i == j) {

String s = wifiinfo.bssid;

String s1 = bssid;

if(s.equals(s1)) {

flag = true;

returnflag;

}

}

flag = false;

} else{

flag = false;

}

}

returnflag;

}

publicinthashCode() {

inti = dBm;

intj = bssid.hashCode();

returni ^ j;

}

publicJSONObject info() {

JSONObject jsonobject = newJSONObject();

try{

String s = bssid;

jsonobject.put("mac", s);

String s1 = ssid;

jsonobject.put("ssid", s1);

inti = dBm;

jsonobject.put("dbm", i);

} catch(Exception ex) {

}

returnjsonobject;

}

publicJSONObject wifi_tower() {

JSONObject jsonobject = newJSONObject();

try{

String s = bssid;

jsonobject.put("mac_address", s);

inti = dBm;

jsonobject.put("signal_strength", i);

String s1 = ssid;

jsonobject.put("ssid", s1);

jsonobject.put("age",0);

} catch(Exception ex) {

}

returnjsonobject;

}

publicfinalString bssid;

publicfinalintdBm;

publicfinalString ssid;

publicWifiInfo(ScanResult scanresult) {

String s = scanresult.BSSID;

bssid = s;

inti = scanresult.level;

dBm = i;

String s1 = scanresult.SSID;

ssid = s1;

}

publicWifiInfo(String s,inti, String s1) {

bssid = s;

dBm = i;

ssid = s1;

}

}

}

CellLocationManager

importjava.util.ArrayList;

importjava.util.Iterator;

importjava.util.List;

importorg.apache.http.HttpEntity;

importorg.apache.http.HttpResponse;

importorg.apache.http.client.methods.HttpPost;

importorg.apache.http.entity.StringEntity;

importorg.apache.http.impl.client.DefaultHttpClient;

importorg.apache.http.util.EntityUtils;

importorg.json.JSONArray;

importorg.json.JSONObject;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.content.IntentFilter;

importandroid.net.ConnectivityManager;

importandroid.net.NetworkInfo;

importandroid.net.wifi.WifiManager;

importandroid.os.Handler;

importandroid.os.Message;

importandroid.telephony.CellLocation;

importandroid.util.Log;

importandroid.widget.Toast;

importcom.google.android.photostream.UserTask;

publicabstractclassCellLocationManager {

publicstaticintCHECK_INTERVAL =15000;

publicstaticbooleanENABLE_WIFI =true;

privatestaticbooleanIS_DEBUG =false;

privatestaticfinalintSTATE_COLLECTING =2;

privatestaticfinalintSTATE_IDLE =0;

privatestaticfinalintSTATE_READY =1;

privatestaticfinalintSTATE_SENDING =3;

privatestaticfinalintMESSAGE_INITIALIZE =1;

privatestaticfinalintMESSAGE_COLLECTING_CELL =2;

privatestaticfinalintMESSAGE_COLLECTING_WIFI =5;

privatestaticfinalintMESSAGE_BEFORE_FINISH =10;

privateintaccuracy;

privateintbid;

privateCellInfoManager cellInfoManager;

privateContext context;

privatebooleandisableWifiAfterScan;

privateint[] aryGsmCells;

privatedoublelatitude;

privatedoublelongitude;

privateMyLooper looper;

privatebooleanpaused;

privatefinalBroadcastReceiver receiver;

privatelongstartScanTimestamp;

privateintstate;

privateTask task;

privatelongtimestamp;

privatebooleanwaiting4WifiEnable;

privateWifiInfoManager wifiManager;

publicCellLocationManager(Context context, CellInfoManager cellinfomanager, WifiInfoManager wifiinfomanager) {

receiver = newCellLocationManagerBroadcastReceiver();

this.context = context.getApplicationContext();

cellInfoManager = cellinfomanager;

wifiManager = wifiinfomanager;

}

privatevoiddebug(Object paramObject) {

if(IS_DEBUG) {

System.out.println(paramObject);

String str = String.valueOf(paramObject);

Toast.makeText(this.context, str, Toast.LENGTH_SHORT).show();

}

}

publicintaccuracy() {

returnthis.accuracy;

}

publicdoublelatitude() {

returnthis.latitude;

}

publicdoublelongitude() {

returnthis.longitude;

}

publicabstractvoidonLocationChanged();

publicvoidpause() {

if(state >0&& !paused) {

looper.removeMessages(MESSAGE_BEFORE_FINISH);

paused = true;

}

}

publicvoidrequestUpdate() {

if(state != STATE_READY) {

return;

}

booleanbStartScanSuccessful =false;

CellLocation.requestLocationUpdate();

state = STATE_COLLECTING;

looper.sendEmptyMessage(MESSAGE_INITIALIZE);

if(wifiManager.wifiManager().isWifiEnabled()) {

bStartScanSuccessful = wifiManager.wifiManager().startScan();

waiting4WifiEnable = false;

} else{

startScanTimestamp = System.currentTimeMillis();

if(!ENABLE_WIFI || !wifiManager.wifiManager().setWifiEnabled(true)) {

intnDelay =0;

if(!bStartScanSuccessful)

nDelay = 8000;

looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, nDelay);

debug("CELL UPDATE");

} else{

waiting4WifiEnable = true;

}

}

}

publicvoidresume() {

if(state >0&& paused) {

paused = false;

looper.removeMessages(MESSAGE_BEFORE_FINISH);

looper.sendEmptyMessage(MESSAGE_BEFORE_FINISH);

}

}

publicvoidstart() {

if(state <= STATE_IDLE) {

Log.i("CellLocationManager","Starting...");

context.registerReceiver(receiver, newIntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

context.registerReceiver(receiver, newIntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));

looper = newMyLooper();

state = STATE_READY;

paused = false;

waiting4WifiEnable = false;

disableWifiAfterScan = false;

debug("CELL LOCATION START");

requestUpdate();

}

}

publicvoidstop() {

if(state > STATE_IDLE) {

context.unregisterReceiver(receiver);

debug("CELL LOCATION STOP");

looper = null;

state = STATE_IDLE;

if(disableWifiAfterScan) {

disableWifiAfterScan = false;

wifiManager.wifiManager().setWifiEnabled(false);

}

}

}

publiclongtimestamp() {

returnthis.timestamp;

}

protectedbooleanisConnectedWithInternet() {

ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = conManager.getActiveNetworkInfo();

if(networkInfo !=null) {

returnnetworkInfo.isAvailable();

}

returnfalse;

}

privateclassMyLooperextendsHandler {

privatefloatfCellScore;

privateJSONArray objCellTowersJson;

publicvoidhandleMessage(Message paramMessage) {

if(CellLocationManager.this.looper !=this)

return;

booleanflag =true;

switch(paramMessage.what) {

default:

break;

caseMESSAGE_INITIALIZE:

this.objCellTowersJson =null;

this.fCellScore =1.401298E-045F;

caseMESSAGE_COLLECTING_CELL:

if(CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING)

break;

JSONArray objCellTowers = CellLocationManager.this.cellInfoManager.cellTowers();

floatfCellScore = CellLocationManager.this.cellInfoManager.score();

if(objCellTowers !=null) {

floatfCurrentCellScore =this.fCellScore;

if(fCellScore > fCurrentCellScore) {

this.objCellTowersJson = objCellTowers;

this.fCellScore = fCellScore;

}

}

this.sendEmptyMessageDelayed(MESSAGE_COLLECTING_CELL, 600L);

break;

caseMESSAGE_COLLECTING_WIFI:

if(CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING)

break;

this.removeMessages(MESSAGE_COLLECTING_CELL);

this.removeMessages(MESSAGE_BEFORE_FINISH);

//                          if (CellLocationManager.this.disableWifiAfterScan && CellLocationManager.this.wifiManager.wifiManager().setWifiEnabled(true))

//                                 CellLocationManager.this.disableWifiAfterScan = false;

CellLocationManager.this.state = CellLocationManager.STATE_SENDING;

if(CellLocationManager.this.task !=null)

CellLocationManager.this.task.cancel(true);

int[] aryCell =null;

if(CellLocationManager.this.cellInfoManager.isGsm())

aryCell = CellLocationManager.this.cellInfoManager.dumpCells();

intnBid = CellLocationManager.this.cellInfoManager.bid();

CellLocationManager.this.task =newCellLocationManager.Task(aryCell, nBid);

JSONArray[] aryJsonArray = newJSONArray[2];

aryJsonArray[0] =this.objCellTowersJson;

aryJsonArray[1] = CellLocationManager.this.wifiManager.wifiTowers();

if(this.objCellTowersJson !=null)

Log.i("CellTownerJSON",this.objCellTowersJson.toString());

if(aryJsonArray[1] !=null)

Log.i("WIFITownerJSON", aryJsonArray[1].toString());

CellLocationManager.this.debug("Post json");

CellLocationManager.this.task.execute(aryJsonArray);

break;

caseMESSAGE_BEFORE_FINISH:

if(CellLocationManager.this.state != CellLocationManager.STATE_READY || CellLocationManager.this.paused)

break;

// L7

if(CellLocationManager.this.disableWifiAfterScan && CellLocationManager.this.wifiManager.wifiManager().setWifiEnabled(false))

CellLocationManager.this.disableWifiAfterScan =false;

if(!CellLocationManager.this.cellInfoManager.isGsm()) {

// L9

if(CellLocationManager.this.bid == CellLocationManager.this.cellInfoManager.bid()) {

flag = true;

} else{

flag = false;

}

// L14

if(flag) {

requestUpdate();

} else{

this.sendEmptyMessageDelayed(10, CellLocationManager.CHECK_INTERVAL);

}

} else{

// L8

if(CellLocationManager.this.aryGsmCells ==null|| CellLocationManager.this.aryGsmCells.length ==0) {

// L10

flag = true;

} else{

int[] aryCells = CellLocationManager.this.cellInfoManager.dumpCells();

if(aryCells !=null&& aryCells.length !=0) {

// L13

intnFirstCellId = CellLocationManager.this.aryGsmCells[0];

if(nFirstCellId == aryCells[0]) {

// L16

intcellLength = CellLocationManager.this.aryGsmCells.length /2;

List arraylist = newArrayList(cellLength);

List arraylist1 = newArrayList(aryCells.length /2);

intnIndex =0;

intnGSMCellLength = CellLocationManager.this.aryGsmCells.length;

while(nIndex 

// goto L18

arraylist.add(CellLocationManager.this.aryGsmCells[nIndex]);

nIndex += 2;

}

// goto L17

nIndex = 0;

while(nIndex 

// goto L20

arraylist1.add(aryCells[nIndex]);

nIndex += 2;

}

// goto L19

intnCounter =0;

for(Iterator iterator = arraylist.iterator(); iterator.hasNext();) {

// goto L22

if(arraylist1.contains(iterator.next()))

nCounter++;

}

// goto L21

intk4 = arraylist.size() - nCounter;

intl4 = arraylist1.size() - nCounter;

if(k4 + l4 > nCounter)

flag = true;

else

flag = false;

if(flag) {

StringBuilder stringbuilder = newStringBuilder(k4).append(" + ");

stringbuilder.append(l4).append(" > ");

stringbuilder.append(nCounter);

CellLocationManager.this.debug(stringbuilder.toString());

}

break;

} else{

// L15

flag = true;

CellLocationManager.this.debug("PRIMARY CELL CHANGED");

// goto L14

if(flag) {

requestUpdate();

} else{

this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, CellLocationManager.CHECK_INTERVAL);

}

}

} else{

// L12

flag = true;

// goto L14

if(flag) {

requestUpdate();

} else{

this.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH,CellLocationManager.CHECK_INTERVAL);

}

}

}

}

}

}

}

classTaskextendsUserTask {

intaccuracy;

intbid;

int[] cells;

doublelat;

doublelng;

longtime;

publicTask(int[] aryCell,intbid) {

this.time = System.currentTimeMillis();

this.cells = aryCell;

this.bid = bid;

}

publicVoid doInBackground(JSONArray[] paramArrayOfJSONArray) {

try{

JSONObject jsonObject = newJSONObject();

jsonObject.put("version","1.1.0");

jsonObject.put("host","maps.google.com");

jsonObject.put("address_language","zh_CN");

jsonObject.put("request_address",true);

jsonObject.put("radio_type","gsm");

jsonObject.put("carrier","HTC");

JSONArray cellJson = paramArrayOfJSONArray[0];

jsonObject.put("cell_towers", cellJson);

JSONArray wifiJson = paramArrayOfJSONArray[1];

jsonObject.put("wifi_towers", wifiJson);

DefaultHttpClient localDefaultHttpClient = newDefaultHttpClient();

HttpPost localHttpPost = newHttpPost("http://www.google.com/loc/json");

String strJson = jsonObject.toString();

StringEntity objJsonEntity = newStringEntity(strJson);

localHttpPost.setEntity(objJsonEntity);

HttpResponse objResponse = localDefaultHttpClient.execute(localHttpPost);

intnStateCode = objResponse.getStatusLine().getStatusCode();

HttpEntity httpEntity = objResponse.getEntity();

byte[] arrayOfByte =null;

if(nStateCode /100==2)

arrayOfByte = EntityUtils.toByteArray(httpEntity);

httpEntity.consumeContent();

String strResponse = newString(arrayOfByte,"UTF-8");

jsonObject = newJSONObject(strResponse);

this.lat = jsonObject.getJSONObject("location").getDouble("latitude");

this.lng = jsonObject.getJSONObject("location").getDouble("longitude");

this.accuracy = jsonObject.getJSONObject("location").getInt("accuracy");;

} catch(Exception localException) {

returnnull;

}

returnnull;

}

publicvoidonPostExecute(Void paramVoid) {

if(CellLocationManager.this.state != CellLocationManager.STATE_SENDING || CellLocationManager.this.task !=this)

return;

if((this.lat !=0.0D) && (this.lng !=0.0D)) {

CellLocationManager.this.timestamp =this.time;

CellLocationManager.this.latitude =this.lat;

CellLocationManager.this.longitude =this.lng;

CellLocationManager.this.accuracy =this.accuracy;

CellLocationManager.this.aryGsmCells =this.cells;

CellLocationManager.this.bid =this.bid;

StringBuilder sb = newStringBuilder("CELL LOCATION DONE: (");

sb.append(this.lat).append(",").append(this.lng).append(")");

CellLocationManager.this.debug(sb.toString());

CellLocationManager.this.state = STATE_READY;

CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, CellLocationManager.CHECK_INTERVAL);

CellLocationManager.this.onLocationChanged();

} else{

CellLocationManager.this.task =null;

CellLocationManager.this.state = CellLocationManager.STATE_READY;

CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_BEFORE_FINISH, 5000L);

}

}

}

privateclassCellLocationManagerBroadcastReceiverextendsBroadcastReceiver {

@Override

publicvoidonReceive(Context arg0, Intent intent) {

// access$0 state

// 1 debug

// access$2 loop

// 3 startScanTimestamp

// 4 disableWifiAfterScan

// 5 wifimanager

if(CellLocationManager.this.state != CellLocationManager.STATE_COLLECTING)

return;

String s = intent.getAction();

if(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(s)) {// goto _L4; else goto _L3

// _L3:

CellLocationManager.this.debug("WIFI SCAN COMPLETE");

CellLocationManager.this.looper.removeMessages(MESSAGE_COLLECTING_WIFI);

longlInterval = System.currentTimeMillis() - CellLocationManager.this.startScanTimestamp;

if(lInterval > 4000L)

CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, 4000L);

else

CellLocationManager.this.looper.sendEmptyMessage(MESSAGE_COLLECTING_WIFI);

} else{

// _L4:

if(!CellLocationManager.this.waiting4WifiEnable)

return;

String s1 = intent.getAction();

if(!WifiManager.WIFI_STATE_CHANGED_ACTION.equals(s1))

return;

intwifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,4);

// _L5:

if(wifiState == WifiManager.WIFI_STATE_ENABLING) {

booleanflag2 = CellLocationManager.this.wifiManager.wifiManager().startScan();

// _L8:

CellLocationManager.this.disableWifiAfterScan =true;

CellLocationManager.this.paused =false;

//                                 int i = flag2 ? 1 : 0;

//                                 int nDelay = i != 0 ? 8000 : 0;

//                                 CellLocationManager.this.looper.sendEmptyMessageDelayed(MESSAGE_COLLECTING_WIFI, nDelay);

CellLocationManager.this.debug("WIFI ENABLED");

}

}

}

}

}

调用方法:

CellInfoManager cellManager = newCellInfoManager(this);

WifiInfoManager wifiManager = newWifiInfoManager(this);

CellLocationManager locationManager = newCellLocationManager(this, cellManager, wifiManager) {

@Override

publicvoidonLocationChanged() {

txtAutoNaviInfo.setText(this.latitude() +"-"+this.longitude());

this.stop();

}

};

locationManager.start();

如果还想同时使用GPS定位,其实也很简单,可以和FourSquare提供的BestLocationListener结合起来,将上面那段代码添加到BestLocationListener的register方法里:

publicvoidregister(LocationManager locationManager,booleangps, Context context) {

if(DEBUG) Log.d(TAG,"Registering this location listener: "+this.toString());

longupdateMinTime = SLOW_LOCATION_UPDATE_MIN_TIME;

longupdateMinDistance = SLOW_LOCATION_UPDATE_MIN_DISTANCE;

if(gps) {

updateMinTime = LOCATION_UPDATE_MIN_TIME;

updateMinDistance = LOCATION_UPDATE_MIN_DISTANCE;

}

List providers = locationManager.getProviders(true);

intprovidersCount = providers.size();

if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){

setChanged();

notifyObservers(null);

}

for(inti =0; i 

String providerName = providers.get(i);

if(locationManager.isProviderEnabled(providerName)) {

updateLocation(locationManager.getLastKnownLocation(providerName));

}

// Only register with GPS if we've explicitly allowed it.

if(gps || !LocationManager.GPS_PROVIDER.equals(providerName)) {

locationManager.requestLocationUpdates(providerName, updateMinTime,

updateMinDistance, this);

}

}

if(cellLocationManager ==null) {

CellInfoManager cellManager = newCellInfoManager(context);

WifiInfoManager wifiManager = newWifiInfoManager(context);

cellLocationManager = newCellLocationManager(context, cellManager, wifiManager) {

@Override

publicvoidonLocationChanged() {

if((latitude() ==0.0D) || (longitude() ==0.0D))return;

Location result = newLocation("CellLocationManager");

result.setLatitude(latitude());

result.setLongitude(longitude());

result.setAccuracy(accuracy());

onBestLocationChanged(result);

this.stop();

}

};

}

//cellLocationManager.stop();

cellLocationManager.start();

//        LocationController controller = LocationController.requestLocationUpdates("", updateMinTime,updateMinDistance, this, context);

//        controller.requestCurrentLocation();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值