---
title: "Android开发:通过Wifi获取经纬度"
author: "kingliu"
date: "2012-07-05T20:06:00Z"
tags: ["WiFi"]
categories: ["移动开发"]
slug: "android-wifi"
draft: false
lastmod: "2012-07-05T20:07:30Z"
id: 1578423
url: "https://kingliu.iteye.com/blog/1578423"
---

\[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 &lt; 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]