在Android中显示可用的WIFI网络列表

时间:2016-08-17 21:47:01

标签: android android-wifi

我一直试图获得ScanResult的列表,但没有成功。

这里附有我的代码:

public class listenerActivity extends AppCompatActivity {
    String netSsid;
    ListView groups;
    EditText filter;
    WifiManager wifi;
    String wifis[];
    WifiScanReceiver wifiReciever;
    Button refreshGroups;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listener);
        groups = (ListView) findViewById(R.id.listView);
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false){
            Toast.makeText(getApplicationContext(), "wifi is disabled. making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        wifiReciever = new WifiScanReceiver();
        registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
         wifi.startScan();
    }

private class WifiScanReceiver extends BroadcastReceiver {
    public void onReceive(Context c, Intent intent) {
        List<ScanResult> wifiScanList = wifi.getScanResults();
        wifis = new String[wifiScanList.size()];

        for(int i = 0; i < wifiScanList.size(); i++) {
                wifis[i] = wifiScanList.get(i).toString();
        }
        groups.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.adapte_layout, (wifiScanList.size() > 0 ? wifis : new String[]{"No net available"})));
    }
}

在我的manifest.xml(部分权限)中:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

这不起作用。

我会很高兴你的帮助(我很抱歉我的英语)。 谢谢!

1 个答案:

答案 0 :(得分:0)

初看起来我认为你根本没有得到结果  但是你的代码很好,它可以检索ScanResult。唯一的问题是你的ArrayAdapter。由于您没有附加布局xmls,因此很难知道什么不能正常工作 无论如何,我使用了适配器的默认布局。以下是您需要更改以在屏幕上查看结果的代码

groups.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, (wifiScanList.size() > 0 ? wifis : new String[]{"No net available"})));