我想扫描周围的WiFi网络并显示它们但是当我使用 WifiManager.getScanResult()时,我会得到一个空列表。
我已经在Manifest中获得了许可,我尝试使用Run-time但调试器从不进入(我读到"正常许可"所以我认为它是正常的:D但是在他们使用它的其他帖子)
主要:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listeViewWifi = (ListView) findViewById(R.id.listViewWifi);
wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
listeWifiItem = new ArrayList<WifiItem>();
wifiAdapter = new WifiAdapter(this, listeWifiItem);
listeViewWifi.setAdapter(wifiAdapter);
broadcastReceiver = new WifiBroadcastReceiver();
registerReceiver(broadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
boutonRechercher = (Button) findViewById(R.id.buttonRefresh);
boutonRechercher.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (wifiManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& (checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
|| checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE},
WIFI_PERMISSION);
}
wifiManager.setWifiEnabled(true);
wifiManager.startScan();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == WIFI_PERMISSION
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
wifiManager.setWifiEnabled(true);
wifiManager.startScan();
}
else {
Toast.makeText(MainActivity.this, "Allow Permissions", Toast.LENGTH_LONG).show();
}
}
接收者:
public class WifiBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = ((MainActivity) context).getCurrentWifiManager();
WifiAdapter wifiAdapter = ((MainActivity) context).getWifiAdapter();
List<WifiItem> listeWifiItem = ((MainActivity) context).getListeWifiItem();
if (wifiManager != null) {
List<ScanResult> listeScan = wifiManager.getScanResults(); //empty
listeWifiItem.clear();
for (ScanResult scanResult : listeScan) {
WifiItem item = new WifiItem();
item.setAdresseMac(scanResult.BSSID);
item.setAPName(scanResult.SSID);
item.setForceSignal(scanResult.level);
Log.d("FormationWifi", scanResult.SSID + " LEVEL "
+ scanResult.level);
listeWifiItem.add(item);
}
wifiAdapter.notifyDataSetChanged();
}
}
}
答案 0 :(得分:0)
您必须要求:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
}
此检查后的位置是什么? You can use this library为了您的目标。