Re: [問題] wifimanager scan問題
※ 引述《choYM (choYM)》之銘言:
: 大家好
: 最近在寫有關抓周圍AP的小程式
: 這個程式必須在每1秒取得兩次wifi scan的結果 並存起來
因為WiFi掃瞄是Android系統和硬體的行為
不是你一秒掃幾次他就回你幾次的
: 但是我發現 這兩次的scan結果 不管如何 都是一樣的
: 我不確定是不是我寫法有問題 還是WiFiManager的限制
: 如果改成每1秒掃一次 就不會有這問題==
: 附上程式碼片段 請大家幫我看看 謝謝
: String s = "";
: for(int i=0; i<2; i++)//1秒內scan的次數
: s += wifiScan();
: public String scanWifi(){
: String s = "";
: WiFiManager wifiManager = (WifiManager)this.getSystemService(
: Context.WIFI_SERVICE);
: if (!wifiManager.isWifiEnabled())//打開wifi
: wifiManager.setWifiEnabled(true);
: //掃描 將資訊存在list
: wifiManager.startScan();
來看看 WifiManager.startScan()
http://tinyurl.com/5sdrfvr
Request a scan for access points. Returns immediately.
The availability of the results is made known later by means of
an asynchronous event sent on completion of the scan.
呼叫 WifiManager.startScan() 之後,回傳的值為是否呼叫成功
而掃描是非同步進行的,比較可靠的就是用 BroadcastReceiver 去等掃瞄完成的通知
順帶一提,WifiManager.setWifiEnabled(boolean) 也是一樣的
不是呼叫後就瞬間開啟完成,也是要用 BroadcastReceiver 去等
以下你的程式馬上就取回呼叫結果
當掃描還沒完成,取到一樣的結果的可能是很大的
: List<ScanResult> list = wifiManager.getScanResults();
: //將資訊以字串方式輸出
: if(list != null){
: for(int j=0; j<list.size(); j++){
: s += list.get(j).BSSID + "%%" + list.get(j).SSID + "%%" +
: list.get(j).level + "%%" +
: list.get(j).frequency + "%%" +
: list.get(j).capabilities + "%%" +
: list.get(j).describeContents() + "\r\n";
: }
: s+="-\r\n";
: }
: return s;
: }
關鍵部份大概長這樣
// 要註冊給系統的 BroadcastReceiver
// 當有符合的事件發生時,便會被呼叫
BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// 取得你要的掃描結果
}
};
// 像系統註冊,並以 IntentFilter 告訴系統你要接收的事件是什麼
// 也就是 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
context.registerReceiver(
wifiScanReceiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
);
// 然後發出掃描需求
wifiManager.startScan();
// 當不需要再接收時,記得取消
context.unregisterReceiver(wifiScanReceiver);
--
如果 BroadcastReceiver 沒用過或不熟
就先看一下他的原理吧
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.165.176.207
推
10/27 10:55, , 1F
10/27 10:55, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):