我想获得可用的WIF列表,我关注了这个问题: how to get available wifi networks and display them in a list in android
但是有一个问题,大部分时间它都没有返回WiFi列表! (当我在android 6下面的设备上运行我的应用程序时效果很好。)
这是我的代码:
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
private final Handler handler = new Handler();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new PermissionHandler().checkPermission(this, permissions, new PermissionHandler.OnPermissionResponse() {
@Override
public void onPermissionGranted() {
mainWifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (mainWifi.isWifiEnabled() == false)
{
// If wifi disabled then enable it
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
Toast.LENGTH_LONG).show();
mainWifi.setWifiEnabled(true);
}
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
}
@Override
public void onPermissionDenied(Activity activity, String[] deniedPermissions, PermissionHandler.OnPermissionResponse listener) {
}
});
}
class WifiReceiver extends BroadcastReceiver {
// This method call when number of wifi connections changed
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n");
for(int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ". ");
sb.append((wifiList.get(i)).toString());
sb.append("\n\n");
Log.i("LOGO_WIFI", sb.toString());
}
}
}
我在manifest
和运行时获得了这些权限:
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
Manifest.permission.ACCESS_WIFI_STATE
Manifest.permission.CHANGE_WIFI_STATE
Manifest.permission.ACCESS_NETWORK_STATE
Manifest.permission.CHANGE_NETWORK_STATE
答案 0 :(得分:0)
mainWifi.getScanResults()
会返回您解析后的 ScanResults 列表,以获取您想要的所有信息。
答案 1 :(得分:0)
我只是发现我的代码存在问题。
问题出在GPS上!我从用户那里获得了位置权限,但GPS已关闭,因此我到目前为止还没有获得任何列表!
现在当GPS开启时,我可以获得Wifi列表,当GPS关闭时,我什么也得不到!
有没有办法在不打开GPS的情况下获取此列表?
答案 2 :(得分:0)
mainWifi.getScanResults()
将返回0个结果(在Android 6.0+设备中)。添加运行时权限,您会很高兴。
随着Android 6.0的发布,授予权限的方式在App中发生了变化。如果您打算在Android 6.0+设备上运行您的应用程序,那么您还需要具有运行时权限以及清单中声明的权限。
假设您要访问 android.permission.ACCESS_COARSE_LOCATION ,然后
- 将其添加到清单文件中
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- 将此添加到代码中
@Override
public void onResume()
{
super.onResume();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 87);
}
}
}
1)您不需要同时拥有ACCESS_FINE_LOCATION
和ACCESS_COARSE_LOCATION
。 ACCESS_COARSE_LOCATION
足够
2)如果关闭GPS,您仍然会得到0个结果。