gpt4 book ai didi

java - wifiManager.getScanResult() 返回空值

转载 作者:行者123 更新时间:2023-12-02 05:02:27 29 4
gpt4 key购买 nike

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

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

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

主要 Activity 类是:

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() 将立即产生结果,但它实际上只执行所说的操作,开始扫描。您正在触发 WiFiReceiver 中的 onReceive 之前访问 then results 变量,这就是为什么它始终为空(您的日志记录应该确认这一点) .

您需要的是在结果准备好时使用回调来获取结果,如代码here做。请注意 onReceive 方法如何调用 scanSuccess(),并且结果仅在 scanSuccess() 中访问,而不是在调用 startScan( )。另请注意他们如何通过检查 boolean startScan() 返回来检查启动扫描是否确实成功

关于java - wifiManager.getScanResult() 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56379635/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com