我无法获取wifi列表。为什么不起作用?
我使用下面的代码,但是不起作用。
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
此功能是使用BroadcastReceiver()开始wifi列表...
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// Intent request codes
private final static int PERMISSIONS_REQUEST_CODE = 100;
Handler handler;
Button wifisetting_btn;
TextView wifi_ssid;
EditText send_data;
Button send_btn;
OutputStream os;
Socket socket;
WifiManager wifiManager;
Button wifi_scan;
ListView listViwProvider;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
List<String> listOfProvider;
ListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
netthread thread = new netthread();
thread.start();
String stringdata="1234568"+send_data.getText().toString();
}
});
wifi_scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
scaning();
}
});
listViwProvider.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ImportDialog action = new ImportDialog(MainActivity.this, (wifiList.get(position)).toString());
action.showDialog();
}
});
}
private void scaning() {
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
}
@Override
protected void onDestroy() {
super.onDestroy();
try{
unregisterReceiver(receiverWifi);
unregisterReceiver(mReceiver);
}catch(IllegalArgumentException e){}
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
wifiList = wifiManager.getScanResults();
Collections.sort(wifiList, new Comparator<ScanResult>() {
@Override
public int compare(ScanResult lhs, ScanResult rhs) {
return (lhs.level > rhs.level ? -1
: (lhs.level == rhs.level ? 0 : 1));
}
});
listOfProvider.clear();
String providerName;
for (int i = 0; i < wifiList.size(); i++) {
providerName = (wifiList.get(i).SSID).toString()
+"\n"+(wifiList.get(i).BSSID).toString();
listOfProvider.add(providerName);
}
adapter = new ListAdapter(MainActivity.this, listOfProvider);
listViwProvider.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}