Android - 每3-4秒扫描一次Wi-Fi

时间:2016-02-24 17:36:08

标签: java android multithreading wifi rssi

我正在开发一个应用程序,其中我想获得所有可用Wifi网络的SSID和信号强度。问题是,当我将手机连接到网络时,只显示信号强度的变化。其他网络很少显示变化(10秒后)。 这是我为获取Wifi信息而创建的类:

class Wifi {
    Context cxt=null;
    public  Wifi(Context c){
        this.cxt=c;
    }

    public HashMap<String,Integer> getWifiStrength(){
        WifiManager wifiManager = (WifiManager) cxt.getSystemService(Context.WIFI_SERVICE);

    // Level of a Scan Result
        List<ScanResult> wifiList = wifiManager.getScanResults();

        HashMap<String, Integer> wireless=new HashMap<String, Integer>();

   for(int i=0; i< wifiList.size() ;i++) {
        ScanResult scanResult= wifiList.get(i);
        //int level = WifiManager.calculateSignalLevel(scanResult.level, 500);
        int level = wifiList.get(i).level;

        String SSID = scanResult.SSID;
        wireless.put(SSID,level);
    }
        return wireless;
    }



}

这就是我在MainActivity中所做的:

final TextView wifi = (TextView)findViewById(R.id.txtWIFI);

final Wifi LocalWireless = new Wifi(this.getApplicationContext());

    Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                HashMap<String, Integer> wireless = LocalWireless.getWifiStrength();
                                 wifi.setText("");

                                for (String key : wireless.keySet()) {
                                    wifi.append(key + " " +wireless.get(key)+"\n");
                                }


                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };

0 个答案:

没有答案