2 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
問(wèn)題是您假設(shè)startScan()
會(huì)立即產(chǎn)生結(jié)果,但實(shí)際上它只按照所說(shuō)的進(jìn)行,開(kāi)始掃描。您在被觸發(fā)之前正在訪問(wèn) thenresults
變量,這就是為什么它始終為 null(您的日志記錄應(yīng)該確認(rèn)這一點(diǎn))。onReceive
WiFiReceiver
您需要做的是在結(jié)果準(zhǔn)備就緒時(shí)使用回調(diào)來(lái)獲取結(jié)果,就像此處的代碼一樣。請(qǐng)注意onReceive
方法調(diào)用scanSuccess()
和結(jié)果是如何只在調(diào)用時(shí)訪問(wèn)的,scanSuccess()
而不是在調(diào)用后立即訪問(wèn)的startScan()
。還要注意他們?nèi)绾瓮ㄟ^(guò)檢查布爾startScan()
返回來(lái)檢查開(kāi)始掃描是否真的成功

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
從 API 級(jí)別 23(Android 6.0 Marshmallow)開(kāi)始,我們需要向用戶端請(qǐng)求運(yùn)行時(shí)許可。特別是 ACCESS_FINE_LOCATION。在wifiManager.startScan()之前需要檢查權(quán)限是否被授予,如果沒(méi)有授予權(quán)限,則需要調(diào)用requestPermissions()。
這是一個(gè)例子:
public void startScanningWifi(){if ( Build.VERSION.SDK_INT >= 23){
if (ActivityCompat.checkSelfPermission(context, Manifest.
permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED ){
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_ASK_PERMISSIONS);
Log.i(TAG, "User location NOT ENABLED, waiting for permission");
}else{
//Start scanning for wifi
}}
您還需要在活動(dòng)中包含此方法
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//start scanning
wifiManager.startScan();
} else {
// Permission for location Denied
Toast.makeText( this,"Well cant help you then!" ,
Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
也不要忘記在您的活動(dòng)中聲明這一點(diǎn)
private final int REQUEST_CODE_ASK_PERMISSIONS = 1;
添加回答
舉報(bào)