Android6.0 掃描WiFi列表的問題

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
著作權歸作者所有,轉載請聯繫作者獲得授權,並標註“簡書作者”。

發佈了60 篇原創文章 · 獲贊 28 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章