編輯:關於 Android 程式設計
WIFI 定位的原理和基站定位其實差不多,核心在於取得 WIFI 的 MAC 位址,再把它傳給定位服務(本文以 Google 的服務為例)來換算座標。以下分兩部分說明:先取得 MAC 位址,再向伺服器請求定位。
[java]
import android.content.Context;
import android.net.wifi.WifiManager;
import android.util.Log;
public class WiFiInfoManager {
private Context context;
public WiFiInfoManager(Context context) {
this.context = context;
}
public WifiInfo getWifiInfo() {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = new WifiInfo();
info.mac = manager.getConnectionInfo().getBSSID();
Log.i("TAG", "WIFI MAC is:" + info.mac);
return info;
}
public class WifiInfo { public String mac; }
}
將取得的位置資訊組成 JSON 傳給 Google 的定位服務,解析回傳結果並建立 Location 物件:
[java]
public static Location getWIFILocation(WifiInfo wifi) {
if (wifi == null) { return null; }
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/loc/json");
JSONObject holder = new JSONObject();
try {
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
JSONArray array = new JSONArray();
if (wifi.mac != null && wifi.mac.trim().length() > 0) {
JSONObject data = new JSONObject();
data.put("mac_address", wifi.mac);
array.put(data);
}
holder.put("wifi_towers", array);
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
int state = resp.getStatusLine().getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity entity = resp.getEntity();
if (entity != null) {
// 讀取回應字串並解析 JSON
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuffer sb = new StringBuffer();
String resute = "";
while ((resute = br.readLine()) != null) { sb.append(resute); }
br.close();
JSONObject data = new JSONObject(sb.toString());
data = (JSONObject) data.get("location");
Location loc = new Location(LocationManager.NETWORK_PROVIDER);
loc.setLatitude((Double) data.get("latitude"));
loc.setLongitude((Double) data.get("longitude"));
loc.setAccuracy(Float.parseFloat(data.get("accuracy").toString()));
loc.setTime(System.currentTimeMillis());
return loc;
}
}
} catch (Exception e) {
Log.e("TAG", e.getMessage());
return null;
}
}
提醒:取得 WIFI MAC 位址需要定位與網路相關的權限,且 Google 的這套 loc/json 介面在後續版本已大幅調整,實際專案可改用 Google Location Services 或其他定位 SDK。此外,MAC 位址屬於敏感資訊,高版本 Android 對其取用有諸多限制。
Android UI 控件 ExpandableListView 基本用法詳解
ExpandableListView 是 Android 中一個非常實用的分組列表控件,本文從介紹到實現代碼,帶大家完整掌握它的基本用法。 一、ExpandableLis
Android 應用如何選擇系統 API 版本號(uses-sdk 介紹)
在開發一個應用之前,特別是 Android 應用,首先要決定這個系統要運行在 Android 2.3、4.0,還是希望相容所有版本。有了這個決定之後,接著就要告訴系統你目
Android 列表懸停效果:WindowManager 與滾動監聽
懸停效果常見於分類列表或日曆列表中。當列表滾動到某個位置時,一個標題或提示布局會固定在頂部,形成懸停感。這種效果可以通過 ListView 的滾動監聽與 WindowMa
Android 百度地圖開發系列:地圖初始化與定位功能實作
在 Android 應用中,地圖功能的使用頻率相當高。回顧過去寫過的專案和用過的百度地圖 API,這裡整理一份從零開始實作 Android 百度地圖的完整流程,第一篇聚焦