本文介紹Android終端持續掃描AP資訊並發送給伺服器端的實現。首先基於TCP協議在Android終端和PC兩端之間形成網路虛擬連結。使用ServerSocket建立TCP伺服器端,然後在Android用戶端使用Socket的構造器來串連伺服器。其中Android終端通過WIFI串連和PC處於同一區域網路。
1. PC伺服器啟用ServerSocket
兩個通訊實體在建立虛擬連結之前,需要有一方先準備好,主動接受來自其他通訊實體的串連請求。
使用ServerSocket對象監聽來自用戶端的Socket串連
//建立ServerSocket對象
//by wayne from www.cnblog.com/dwayne/
ServerSocket ss = new ServerSocket(30000);//監聽來自用戶端的請求while(true){ Socket s = ss.accept(); …}
如果沒有串連,則將一直處於等待狀態。
當接收到串連請求後,擷取訊息到輸入資料流,並儲存到檔案。
//接收用戶端訊息
//by wayne from www.cnblog.com/dwayne/
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String str;BufferedWriter bw = new BufferedWriter(new FileWriter("D:/ApInfo"+ (i++) +".txt"));while ((str = in.readLine()) != null) { System.out.println(str); bw.write(str); bw.newLine(); }
2. Android終端使用Socket通訊
用戶端使用Socket的構造器串連伺服器,指定伺服器IP和連接埠號碼就可以了。
Socket s = new Socket(“192.168.1.100”, 30000);
這樣伺服器端的accept()方法就得到響應,從而向下執行,伺服器端和用戶端就形成了一對互相串連的Socket。再進行通訊時就沒有伺服器和用戶端之分了,都是通過輸入輸出資料流進行通訊。
詳細步驟
採用Handler和TimerTask來定時掃描AP資訊並發送給伺服器端。
TimerTask規定了到達指定的時間所要進行的任務。
TimerTask task = new TimerTask(){ public void run() { Message message = new Message(); message.what = 1; handler.sendMessage(message); } };
handler傳遞message內容:
Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: // 執行定時器時間到了之後由handler傳遞的任務 break; } super.handleMessage(msg); }};
因為需要持續執行掃描任務,所以啟用新線程執行定時任務
//啟動單獨線程定時向伺服器發送AP資訊
//by wayne from www.cnblogs.com/dwayne
new Thread(){ @Override public void run() { // TODO Auto-generated method stub timer.schedule(task, 2000,10000); //在2秒後每10秒執行一次定時器中的方法 } }.start();
接下來掃描AP資訊並發送給伺服器端,然後將結果儲存。
WifiManager wifiManager=(WifiManager) getSystemService(WIFI_SERVICE);wifiManager.startScan();mWifiList = wifiManager.getScanResults();
由WifiManager說明可知,它可以用於處理已配置的網路,當前串連的網路及AP資訊的掃描等情況。
This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items:
- The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
- The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
- Results of access point scans, containing enough information to make decisions about what access point to connect to.
- It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.
向伺服器發送訊息:
socket = new Socket("192.168.1.211",30000);//向伺服器端發送訊息PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); out.println(message);
其中message為擷取的AP資訊
測試收到的資訊格式為:
SSID: ICIS_LAB, BSSID: 1c:af:f7:9a:65:e4, capabilities: [WPA-PSK-TKIP+CCMP], level: -80, frequency: 2437