開發(fā)中用到了LeankCanary,在一個(gè)簡單的頁面中(例如 :僅僅 包含Edittext),也會(huì)導(dǎo)致內(nèi)訓(xùn)泄漏,為此,我在網(wǎng)上找了大量資料,最終解決。
例如一個(gè)布局:
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical">
創(chuàng)新互聯(lián)專注于曲周網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供曲周營銷型網(wǎng)站建設(shè),曲周網(wǎng)站制作、曲周網(wǎng)頁設(shè)計(jì)、曲周網(wǎng)站官網(wǎng)定制、小程序定制開發(fā)服務(wù),打造曲周網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供曲周網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
以上會(huì)導(dǎo)致內(nèi)存泄漏,是由于EditText引用了Activity的context的原因,在Activity銷毀的時(shí)候,
由于Edittext持有對Activity的context的引用,導(dǎo)致Activity無法正?;厥?。
解決辦法:重寫EditText,將對Activity中Context的引用,改為對ApplicationContext的引用。
代碼如下:
@SuppressLint("AppCompatCustomView")
public class BaseEditText extends EditText {
private static java.lang.reflect.Field mParent;
static {
try {
mParent = View.class.getDeclaredField("mParent");
mParent.setAccessible(true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public BaseEditText(Context context) {
super(context.getApplicationContext());
}
public BaseEditText(Context context, AttributeSet attrs) {
super(context.getApplicationContext(), attrs);
}
public BaseEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context.getApplicationContext(), attrs, defStyleAttr);
}
@SuppressLint("NewApi")
public BaseEditText(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context.getApplicationContext(), attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onDetachedFromWindow() {
try {
if (mParent != null)
mParent.set(this, null);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
super.onDetachedFromWindow();
}
}
然后xml中的布局引用自定義的EditText:
<包名.路徑.BaseEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="@null"
android:hint="4-20位不包含特殊字符"
android:textSize="15dp" />
另外,由于LinearLayout獲取了焦點(diǎn),也可能會(huì)導(dǎo)致內(nèi)存的泄漏,
需要在Activity中的onDestroy里清除掉焦點(diǎn):
LinearLayout.clearFocus();
再次測試,問題解決!
感謝 https://www.jianshu.com/p/e1b41fb80cdc 文章的啟發(fā)。