如何检查我输入的WiFi名称是否存在于我所在的区域?
我们的想法是从WiFi网络获取名称,将它们与我输入的名称进行比较并返回布尔值。
以下是我使用的代码,它总是返回false。
wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiMgr.startScan();
private class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifiScanList = wifiMgr.getScanResults();
wifis = new String[wifiScanList.size()];
for (int i = 0; i < wifiScanList.size(); i++) {
wifis[i] = wifiScanList.get(i).toString();
}
}
}
private boolean doesWifiExist(String string){
String[] array = string.split(" ");
String wifi = array[0];
boolean flag = false;
for (int i = 0; i < wifis.length; i++) {
if(wifis[i].equals(wifi)){
flag = true;
break;
}
}
return flag;
}
以下是我添加的代码以及我使用的清单中的权限
public boolean isInternetPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("PermissionGranted", "Permission is granted");
return true;
} else {
Log.v("PermissionGranted", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v("PermissionGranted", "Permission is granted");
return true;
}
}
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 0 :(得分:0)
它返回false可能是因为wifiScanList
为空。确保您明确要求获得新API的许可,并确保启用了wifi
答案 1 :(得分:0)
首先请确保您拥有<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"
此外,我相信如果你在,API&gt; = 23(或Marshmallow,如果api不同),你需要致电requestPermission(new String[] {Manifest.permission.ACCESS_WIFI_STATE})
这也可用于请求多个权限,只需用逗号分隔即可。
还可以通过调用来检查权限状态
checkSelfPermission(PERMISSION) == PackageManager.PERMISSION_DENIED
,其中PERMISSION等于您尝试检查的权限。