33

朋友们,我想找到所有可用的 WiFi 网络并将它们显示在我尝试过的列表中,如下所示。但它不起作用。我已经编辑了我的代码,现在我得到了结果,但得到了我不需要的所有结果。我只需要列表中的 wifi 网络名称。

public class MainActivity extends Activity {

    TextView mainText;
    WifiManager mainWifi;
    WifiReceiver receiverWifi;
    List<ScanResult> wifiList;
    StringBuilder sb = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainText = (TextView) findViewById(R.id.tv1);
        mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        if (mainWifi.isWifiEnabled() == false)
        {  
             // If wifi disabled then enable it
             Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
             Toast.LENGTH_LONG).show();
             mainWifi.setWifiEnabled(true);
         } 

         receiverWifi = new WifiReceiver();
         registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
         mainWifi.startScan();
         mainText.setText("Starting Scan...");

     }

     public boolean onCreateOptionsMenu(Menu menu) {
            menu.add(0, 0, 0, "Refresh");
            return super.onCreateOptionsMenu(menu);
     }

     public boolean onMenuItemSelected(int featureId, MenuItem item) {
            mainWifi.startScan();
            mainText.setText("Starting Scan");
            return super.onMenuItemSelected(featureId, item);
     }

     protected void onPause() {
            unregisterReceiver(receiverWifi);
            super.onPause();
     }

     protected void onResume() {
            registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
            super.onResume();
     }

        // Broadcast receiver class called its receive method
        // when number of wifi connections changed

      class WifiReceiver extends BroadcastReceiver {

            // This method call when number of wifi connections changed
            public void onReceive(Context c, Intent intent) {

                sb = new StringBuilder();
                wifiList = mainWifi.getScanResults();
                sb.append("\n        Number Of Wifi connections :"+wifiList.size()+"\n\n");

                for(int i = 0; i < wifiList.size(); i++){

                    sb.append(new Integer(i+1).toString() + ". ");
                    sb.append((wifiList.get(i)).toString());
                    sb.append("\n\n");
                }

                mainText.setText(sb); 
            }

       }
}
4

3 回答 3

43

您需要创建一个BroadcastReceiver来监听 Wifi 扫描结果:

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
        }
    }
}

onCreate()您将分配mWifiManager并启动扫描:

mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
registerReceiver(mWifiScanReceiver,
        new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();

getScanResults()仅当您具有适当的权限时才会返回数据。为此,将以下两行之一添加到您的AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

另请注意,在 API 23+ 中,必须在运行时请求权限。(对于实验室环境,您也可以改为在“设置”中手动授予权限 - 需要较少的编码,但不建议用于最终用户应用程序。)

请注意,每次有新的扫描结果可用时,处理您的扫描结果的代码都会运行,从而更新结果。

于 2013-09-11T12:30:34.053 回答
12

安卓6.0之后

如果您的 Android 操作系统版本为6.0 或更高版本,那么您的应用程序必须在运行时请求以下权限(以下任一项)。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

如何在运行时请求权限

只需在活动的 onResume 方法中添加此代码

@Override
public void onResume()
{
    super.onResume();

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 87);
        }
    }
}

如果您在运行时没有上述权限会怎样?

Wifi.getScanResults() 将返回 0 个结果。

包括我在内的很多人都在 Nexus 5 手机中遇到过这个问题,并将其称为“错误”。

如何扫描和读取wifi网络?(更深入的了解)

可以通过以下方式请求扫描

wifiManager.startScan();

boolean startScan()根据扫描是否成功开始,立即返回 true 或 false。但是,它会启动一个异步事件,该事件会在扫描完成时
发送一个意图(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION )。由于扫描结果(异步事件结果)不会立即可用,因此您必须使用 BroadcastReceiver 注册您的活动。

这是使用 BroadcastReceiver(异步)读取这些结果的代码片段。

public class WifiScanReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
        {
            List<ScanResult> scanResults = wifimanager.getScanResults();
            // Write your logic to show in the list
        }

    }
}

你可以在 BroadcastReceiver 上看到这个演示

相关链接

扫描结果在 Android 6.0 中返回一个空列表

于 2018-02-23T11:59:28.260 回答
6
  class WifiReceiver extends BroadcastReceiver {

       public void onReceive(Context c, Intent intent) {

          sb = new StringBuilder();
          wifiList = mainWifi.getScanResults();

            for (int i = 0; i < wifiList.size(); i++){
                sb.append(new Integer(i+1).toString() + ".");
                sb.append((wifiList.get(i)).SSID);
                sb.append("\n");
            }

          mainText.setText(sb);

        }

  }
于 2015-09-01T05:19:44.060 回答