Android开发:通过Wifi获取经纬度

[size=medium]
第一步:

//获取wifi管理对象

第二步:这一步比较耗时,最好写在线程中。

ok. 到此就可以获取经纬度了。当然如果你所在的WIFI从来没有通过其他设备定位过,及google数据库中没有该wifi热点的位置信息,那就获取不到经纬度了。

WifiManager mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (mainWifi.isWifiEnabled())
{
//发送接入点的扫描请求,返回true成功。否则失败
mainWifi.startScan();
//启动一个线程执行第二步中的代码
}
public Location setWeather()
{
BufferedReader br = null;
try
{
//接收请求结果,它会将所有链接wifi热点的链接信息返回
List wifiList = mainWifi.getScanResults();
HttpPost httpRequest = new HttpPost("http://www.google.com/loc/json");
//封装请求的参数
JSONObject holder = new JSONObject();
JSONArray array = new JSONArray();
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("request_address", true);
for (int i = 0; i < wifiList.size(); i++)
{
//只取当前链接信息。通过mac地址进行匹配
//mac地址可以用macAddress = mainWifi.getConnectionInfo().getMacAddress();获得
if (wifiList.get(i).BSSID.equals(macAddress))
{
JSONObject current_data = new JSONObject();
current_data.put("mac_address", wifiList.get(i).BSSID);
current_data.put("ssid", wifiList.get(i).SSID);
current_data.put("signal_strength", wifiList.get(i).level);
array.put(current_data);
}
}
holder.put("wifi_towers", array);
StringEntity se = new StringEntity(holder.toString());
httpRequest.setEntity(se);
HttpResponse resp = new DefaultHttpClient().execute(httpRequest);
if (resp.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = resp.getEntity();
br = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuffer sb = new StringBuffer();
String result = br.readLine();
while (result != null)
{
sb.append(result);
result = br.readLine();
}
JSONObject location = new JSONObject(sb.toString());
location = (JSONObject) location.get("location");
Location loc = new Location(LocationManager.NETWORK_PROVIDER);
loc.setLatitude((Double) location.get("latitude"));
loc.setLongitude((Double) location.get("longitude"));
return loc;
}
return null;
}
catch (JSONException e)
{
Log.e(e.toString());
}
catch (ClientProtocolException e)
{
Log.e(e.toString());
}
catch (IOException e)
{
Log.e(e.toString());
}
catch (Exception e)
{
Log.e(e.toString());
}
finally
{
if (null != br)
{
try
{
br.close();
}
catch (IOException e)
{
Log.e(e.toString());
}
}
}
return null;
}
}

所需权限


[/size]

你可能感兴趣的:(android)