在 android 手機中 -> 設定 -> Wi-Fi , 每隔一段時間會自動搜尋附近的wifi ap的訊息並顯示在列表上, 本篇介紹如何同步取得這些wifi ap的訊息
這些wifi ap的訊息是藉由ScanResult來顯示, ScanResult 類別相當簡單, 請參考官網
而每次搜尋wifi ap的動作都是以Broadcast的方式來達成, 所以我們只要建立一個專門來接收該動作的Broadcast Receiver 就能自動同步取得其搜尋結果(ScanResult)
package com.foxx.wifiapreceiver; import java.util.List; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.util.Log; public class WifiApReceiver extends BroadcastReceiver { private static final String TAG = "WifiApResult"; private Activity mActivity; public WifiApReceiver(Activity activity) { mActivity = activity; mActivity.registerReceiver(this, new IntentFilter( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); } @Override public void onReceive(Context context, Intent intent) { getScanResults(); } private void getScanResults() { List<ScanResult> scanResults = getWifiManager().getScanResults(); Iterator<ScanResult> iter = scanResults.iterator(); while (iter.hasNext()) { showAllFieldOfScanResult(iter.next()); } } private WifiManager getWifiManager() { return (WifiManager) mActivity.getSystemService(Context.WIFI_SERVICE); } private void showAllFieldOfScanResult(ScanResult scanResult) { Log.d(TAG, "--------------------------------------"); Log.d(TAG, "scanResult.SSID:" + scanResult.SSID); Log.d(TAG, "scanResult.BSSID:" + scanResult.BSSID); Log.d(TAG, "scanResult.capabilities:" + scanResult.capabilities); Log.d(TAG, "scanResult.frequency:" + scanResult.frequency); Log.d(TAG, "scanResult.level:" + scanResult.level); Log.d(TAG, "scanResult.BSSID:" + scanResult.describeContents()); } public void unregisterReceiver() { try { mActivity.unregisterReceiver(this); } catch (Exception e) { Log.d(TAG, "execption in unregisterReceiver"); } } }
1. 在constructor註冊了receiver
2. OnReceiver 為 callback function , 只要有搜尋wifi ap的動作, OnReceiver就會被呼叫
在AndroidManifest.xml加入2個必要的permission
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
使用的方式相當簡單
package com.foxx.wifiapreceiver; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { private WifiApReceiver mWifiReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initWifiReceiver(); } private void initWifiReceiver(){ mWifiReceiver = new WifiApReceiver(this); } @Override protected void onStop() { mWifiReceiver.unregisterReceiver(); super.onStop(); } }
只要注意在onStop要unregister receiver即可