getScanResults在Android6.0上返回了一个空列表,範例程式碼:
public List<ScanResult> getScanResults(String callingPackage) {
enforceAccessPermission();
int userId = UserHandle.getCallingUserId();
int uid = Binder.getCallingUid();
boolean canReadPeerMacAddresses = checkPeersMacAddress();
boolean isActiveNetworkScorer =
NetworkScorerAppManager.isCallerActiveScorer(mContext, uid);
boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
long ident = Binder.clearCallingIdentity();
try {
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !isLocationEnabled()) {
return new ArrayList<ScanResult>();
}
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !checkCallerCanAccessScanResults(callingPackage, uid)) {
return new ArrayList<ScanResult>();
}
if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
!= AppOpsManager.MODE_ALLOWED) {
return new ArrayList<ScanResult>();
}
if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
return new ArrayList<ScanResult>();
}
return mWifiStateMachine.syncGetScanResultsList();
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private boolean isLocationEnabled() {
return Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF) != Settings.Secure.LOCATION_MODE_OFF;
}
重点在:
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !isLocationEnabled()) {
return new ArrayList<ScanResult>();
}
可以看到如果定位关闭,那么将直接返回一个空的列表,当我去打开定位时,果然就正常的返回了WiFi列表,于是解决方案就是在6.0以上系统中,帮用户打开GPS开关:
if (Build.VERSION.SDK_INT >= 23 && !AppUtil.isGpsOPen(this)) {
Settings.Secure.putInt(getContentResolver(),Settings.Secure.LOCATION_MODE, 1);
}
当然,这里还需要用到一些权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
如果App不是system app,那么是获取不到WRITE_SECURE_SETTINGS权限的,此时就要引導使用者手動打啟GPS開關,上面的程式碼就會正常。也許有其他解法是不需要同時開啟 GPS。