×

Android M扫描WiFi列表的问题

96
lbyte
2016.04.10 22:24* 字数 279

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是怎么想的,还请大神们赐教。

欢迎进入我的博客查看更多文章

Android的那些坑
Web note ad 1