起因

google 發(fā)了封郵件,ES 一直持有 Multicast Locks 導(dǎo)致耗電量增加。
解決方案
1.Utils 增加 getWifiManage 方法,防止內(nèi)存泄露,加上Nullable注解。
On versions prior to Android N (24), initializing the WifiManager via Context#getSystemService can cause a memory leak if the context is not the application context.
@Nullable
public static WifiManager getWifiManage() {
return (WifiManager) MainApplication.getInstance().getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
}
2.增加鎖屏銷毀組播,亮屏啟動(dòng)組播。釋放監(jiān)聽(tīng)的端口
IntentFilter filter=new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
MainApplication.getInstance().registerReceiver(mBroadcastReceiver, filter);
case Intent.ACTION_SCREEN_OFF:
destoryZeroconf(); // 執(zhí)行 MulticastSocket 的 close 方法關(guān)閉組播
break;
case Intent.ACTION_SCREEN_ON:
if (NetworkUtils.isWifiAvailable()) {
initZeroconf(); // 重啟組播
}
break;
3.去掉 MulticastLock 鎖
不再需要 MulticastLock 鎖,同時(shí)方便通過(guò)代碼靜態(tài)檢查。
總結(jié)
經(jīng)過(guò)上面的操作,在屏幕打開(kāi)的時(shí)候才監(jiān)聽(tīng)組播。屏幕關(guān)閉的時(shí)候就不消耗電量去監(jiān)聽(tīng)。
同時(shí) ES 有另外的 UDP 端口以及緩存方案去接收局域網(wǎng)的掃描請(qǐng)求,關(guān)閉組播不會(huì)導(dǎo)致功能的失效。