Android6.0 掃描WiFi列表的問題
阿新 • • 發佈:2019-02-14
Android 6.0釋出近一年之後,我們遇到了第一個Android 6.0的相容性問題,getScanResults在Android6.0上返回了一個空列表,納尼,你是在逗我麼?去看了下Android 6.0某個分支下的getScanResult原始碼:
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開關,使用者心裡應該是會罵孃的:為何掃描個WiFi也需要開啟GPS。
寫這篇文章時還是沒有想通為何要在掃描WiFi列表時開啟GPS,Google是怎麼想的,還請大神們賜教。
文/lbyte(簡書作者)原文連結:http://www.jianshu.com/p/3400ca0deeee
著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。