第一步:
第二步:这一步比较耗时,最好写在线程中。
ok. 到此就可以获取经纬度了。当然如果你所在的 WIFI从来没有通过其他设备定位过,及 google数据库中没有该wifi热点的位置信息,那就获取不到经纬度。如果各位大侠有更好的办法,共同讨论
Java代码
- //获取wifi管理对象
- WifiManager
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); - //判断wifi是否开启
- if
(mainWifi.isWifiEnabled()) - {
- //发送接入点的扫描请求,返回true成功。否则失败
- mainWifi.startScan();
- //启动一个线程执行第二步中的代码
- }
-
第二步:这一步比较耗时,最好写在线程中。
Java代码
- public
Location setWeather() - {
- BufferedReader
br = null; - try
- {
- //接收请求结果,它会将所有链接wifi热点的链接信息返回
- List<ScanResult>
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; - }
- }
-
ok. 到此就可以获取经纬度了。当然如果你所在的 WIFI从来没有通过其他设备定位过,及 google数据库中没有该wifi热点的位置信息,那就获取不到经纬度。如果各位大侠有更好的办法,共同讨论