使用可用的wifi地址填充微调器

时间:2014-06-19 20:03:51

标签: android spinner android-arrayadapter android-spinner

我正在努力让微调器显示可用的wifi SSID列表。我使用以下内容将SSID存储到我的广播接收器的onReceive中的字符串数组中。

List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
        wifis = new String[wifiScanList.size()];
        for (int i = 0; i < wifiScanList.size(); i++) {
            wifis[i] = ((wifiScanList.get(i).SSID));
        }

然后我如何将wifis数组显示给我的微调器?我在我的xml中有我的微调器对象,在我的onCreate中我有

sp = (Spinner) findViewById(R.id.spinner);

在我的广播接收器中,我尝试这样做......

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
wifis, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

但由于我的数组不是资源,因此不起作用。我一直在寻找其他方法,但我遇到的是如何从xml文件中访问字符串。

所以我的问题是,如何使用我现有的代码然后使用我的wifi选项列表填充微调器。感谢您的任何帮助。

编辑:完整的代码现在有效:

public class MainActivity extends Activity {

WifiManager mainWifiObj;
WifiScanReceiver wifiReciever;
ListView list;
Spinner sp;
String wifis[];

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sp = (Spinner) findViewById(R.id.spinner);
    mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiReciever = new WifiScanReceiver();
    mainWifiObj.startScan();
}

protected void onPause() {
    unregisterReceiver(wifiReciever);
    super.onPause();
}

protected void onResume() {
    registerReceiver(wifiReciever, new IntentFilter(
            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    super.onResume();
}

class WifiScanReceiver extends BroadcastReceiver {
    @SuppressLint("UseValueOf")
    public void onReceive(Context c, Intent intent) {
        List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
        wifis = new String[wifiScanList.size()];
        for (int i = 0; i < wifiScanList.size(); i++) {
            wifis[i] = ((wifiScanList.get(i).SSID));
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, wifis);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(adapter);
    }
}
}

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
    wifis = new ArrayList<String>();
    for (int i = 0; i < wifiScanList.size(); i++) {
        wifis.add(((wifiScanList.get(i).SSID)));
    }

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, wifis);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);