我想获得我的应用程序中可用的所有wifi连接的列表,但我没有得到任何列表。我的wifi连接正在上线,并且还连接到我的wifi,但我无法在我的应用程序中获取wifi连接列表。 谁能告诉我为什么这样?这是我的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
WifiManager wm;
ToggleButton tb;
ArrayAdapter<String> aa;
ListView l;
private static final int ENABLE_REQUEST=1;
private static final int DISCOVERABLE_REQUEST=2;
private static final int DISCOVERABLE_DURATION=120;
BroadcastReceiver br=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
List<ScanResult> hotspot= wm.getScanResults();
for(int i=0;i<hotspot.size();i++) {
aa.add(hotspot.get(i).toString());
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb= (ToggleButton) findViewById(R.id.toggle);
aa=new ArrayAdapter(this,android.R.layout.simple_list_item_1);
l= (ListView) findViewById(R.id.list);
l.setAdapter(aa);
wm= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
tb.setOnClickListener(this);
}
@Override
public void onClick(View v) {
tb= (ToggleButton) v;
if(wm==null) {
Toast.makeText(this, "This feature is not supported", Toast.LENGTH_SHORT).show();
tb.setChecked(false);
} else {
if (tb.isChecked()) {
wm.setWifiEnabled(true);
discover();
} else {
wm.setWifiEnabled(false);
}
}
}
private void discover() {
wm.startScan();
IntentFilter filter=new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
this.registerReceiver(br,filter);
}
}
的AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
答案 0 :(得分:0)
我认为你可能在另一个stackoverflow帖子中寻找这个answer。
如答案所示,您可以在mScanResults
中找到可以应用于ArrayAdapter
的列表,最后在列表视图中调用setAdapter
方法。
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
List<ScanResult> mScanResults = mWifiManager.getScanResults();
// add your logic here
}
}
}
请按照answer了解详情。