1. 程式人生 > >Android M掃描WiFi列表的問題

Android M掃描WiFi列表的問題

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。