Android应用程序扫描wifi aps并在列表视图中显示它们

时间:2016-06-22 19:26:33

标签: android listview wifi android-adapter android-wifi

我正在尝试创建一个简单的Android应用程序,它扫描wifi aps并在列表视图中显示它们,包括SSID,BSSID和Signal Strength。

虽然这可能不是太困难的任务,但我遇到了一个问题,因为我对android开发很新。

我编写了代码来完成这些基本任务。但是,它不会显示任何结果。它也没有显示任何错误。你能帮我解决它并让它起作用吗?

public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener{

// Declare View variables
private Button mRefreshButton;
private Switch mWifiSwitch;
private ListView mAPListView;
private List<ScanResult> mWifiList;
private List<String> mListOfProviders;
private ListAdapter mAdapter;
private WifiManager mWifiManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mListOfProviders = new ArrayList<String>();
    mAPListView = (ListView) findViewById(R.id.APListView);
    mRefreshButton = (Button) findViewById(R.id.refreshButton);
    mWifiSwitch = (Switch) findViewById(R.id.WiFiSwitch);
    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    boolean wasEnabled = mWifiManager.isWifiEnabled();
    if (wasEnabled){
        mWifiSwitch.setChecked(true);
    }
    mWifiSwitch.setOnCheckedChangeListener(this);

    mWifiManager.startScan();
    mWifiList = mWifiManager.getScanResults();

    for (ScanResult result : mWifiList) {
        mListOfProviders.add(result.SSID); //This will add the SSID of the connection
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mListOfProviders);
    mAPListView.setAdapter(adapter);

}


@Override
public void onClick(View view)
{

}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked){
        mWifiManager.setWifiEnabled(true);
    }
    else {
        mWifiManager.setWifiEnabled(false);
    }
}
}

1 个答案:

答案 0 :(得分:0)

尝试在清单中添加权限。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />