我正在搜索可用的wifi网络,但方法getScanResults()返回空列表。

我包括了所需的所有权限:

android.permission.ACCESS_COARSE_LOCATION
android.permission.CHANGE_WIFI_STATE
android.permission.ACCESS_FINE_LOCATION
android.permission.ACCESS_WIFI_STATE


主要活动类别是:

public class Home extends Activity {`

    Context context;
    WifiManager wifiManager = null;
    WiFiReceiver wifiReceiver = null;

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

        context = this;
        wifiManager = (WifiManager)
        context.getSystemService(Context.WIFI_SERVICE);
        wifiReceiver = new WiFiReceiver(wifiManager);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(wifiReceiver, intentFilter);

        wifiManager.startScan();
        List<ScanResult> results = wifiReceiver.results;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(wifiReceiver);
    }
}


广播接收器是:

public class WiFiReceiver extends BroadcastReceiver {`

    public List<ScanResult> results;
    private WifiManager wifiManager;

    public WiFiReceiver(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
        if (success) {
            results = wifiManager.getScanResults();
            Log.e("wiFi Manager", "Done");

        } else {
            Log.e("wiFi Manager", "Scan failure");
        }
    }
}

最佳答案

问题是您假设startScan()会立即产生结果,但实际上只执行所说的操作,开始扫描。您正在访问results中的onReceive变量之前触发的WiFiReceiver变量,这就是为什么它始终为null的原因(您的日志记录应该确认)。

您需要做的是像代码here一样使用回调获取准备好的结果。注意onReceive方法是如何调用scanSuccess()的,结果只能在scanSuccess()中访问,而不能在调用startScan()之后立即访问。
还要注意他们如何通过检查布尔值startScan()返回值来检查启动扫描是否实际上成功

08-05 07:41