Este código me deja listar las wifi pero con la localización activada. Estoy usando android 7.0. Creo que no debo de tener la ubicación activada para que el scan funcione, ¿o sí?
private WifiManager wifiManager;
private List<ScanResult> wifiList;
private StringBuilder sb = new StringBuilder();
private final int ACCESS = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
btnwifi = (Button) findViewById(R.id.btnWifi);
txtInfo = (TextView) findViewById(R.id.wifi_info);
btnwifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(Login2.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS);
}
} else {
MyWifiMethod();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case ACCESS:
if (grantResults.length >= 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
MyWifiMethod();
else
Toast.makeText(Login2.this, "No tiene permisos", Toast.LENGTH_SHORT).show();
break;
}
}
private void MyWifiMethod()
{
wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
registerReceiver(wifiScanReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
}
private final BroadcastReceiver wifiScanReciever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
{
wifiList = wifiManager.getScanResults();
sb = new StringBuilder();
sb.append("\n" + "numero de conexiones: " + wifiList.size() + "\n");
for(int i = 0; i < wifiList.size(); i++)
{
sb.append(new Integer(i+1).toString() + ". ");
sb.append("SSID " + (wifiList.get(i).SSID));
}
txtInfo.setText(sb);
}
}
};