我正在为Android Nougat构建我的代码。
我在清单文件中给出了位置和WiFi权限,但是,我从wlan_Manager.getScanResults()得到“0”;
我的代码段是
wlan_Manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wlan_switch = (Switch)findViewById(R.id.switch1);
list = (ListView)findViewById(R.id.listview);
wlan_switch.setChecked(wlan_Manager.isWifiEnabled());
wifi_list = new ArrayList<>();
adapter = new Adapter(this,R.layout.default_listview,wifi_list);
list.setAdapter(adapter);
wifireceiver = new wifi_Receiver(adapter,wifi_list);
registerReceiver(wifireceiver,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
public void onClick(View view) {
Log.d("switch", "onClick: ");
if (wlan_switch.isChecked() && !wlan_Manager.isWifiEnabled())
{
Log.d(TAG, "true: ");
wlan_Manager.setWifiEnabled(true);
wifi_list.clear();
wlan_Manager.startScan();
}
else {
Log.d(TAG, "false ");
wlan_Manager.setWifiEnabled(false);
wifi_list.clear();
adapter.clear();
}
}
@Override
public void onReceive(Context context, Intent intent)
{
int size =0 ;
//scan_Result.clear();
Log.d("WifScanner", "onReceive");
wlan_Manager = (WifiManager)context.getApplicationContext().getSystemService(context.WIFI_SERVICE);
scan_Result = wlan_Manager.getScanResults();
size = scan_Result.size();
Log.d(TAG, "onReceive: " + size);
while (size > 0)
{
Log.d(TAG, "size : "+size);
size--;
wifi_list.add(scan_Result.get(size).SSID);
adapter.notifyDataSetChanged();
}
}
但是当我为Lower android版本构建代码时,它显示了WiFi列表。
答案 0 :(得分:0)
在开始任何扫描之前,您正在调用getScanResults()。 对于您的用例,您需要使用startScan()方法启动wifi扫描并注册一个BroadcastReceiver,它会对操作进行过滤:
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
在这里您可以找到一些示例代码: Android Wifi Scan - BroadcastReceiver for SCAN_RESULTS_AVAILABLE_ACTION not getting called
答案 1 :(得分:0)
这是Android 7.x版本中的一个问题。存在两种解决方案: