最近的视频项目遇到了内存泄漏,找问题真是蛋疼的事。主要就是 context 没有释放,handler 的不合理使用,bitmap 没有回收,connection 没有 close 等首先纪录一下 sdk 官方写 handler 的方式
public abstract class WeakHandler<T> extends Handler {
private WeakReference<T> mOwner;
public WeakHandler(T owner) {
mOwner = new WeakReference<T>(owner);
}
public T getOwner() {
return mOwner.get();
}
}
复制代码
activity 中
public abstract class BaseActivity extends AppCompatActivity {
private final UIActivityHandler uiHandler = new UIActivityHandler(this);
public static class UIActivityHandler extends
WeakHandler<BaseActivity> {
public UIActivityHandler(BaseActivity owner) {
super(owner);
}
public void handleMessage(Message msg) {
BaseActivity owner = getOwner();
if (owner == null) {
return;
}
owner.handleUIMessage(msg);
}
}
protected final void postMessageDelay(int what, Object object,
long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = object;
uiHandler.sendMessageDelayed(msg, delayMillis);
}
protected final void postMessage(int what, Object object) {
Message.obtain(uiHandler, what, object).sendToTarget();
}
public void handleUIMessage(Message msg) {
}
}
复制代码
最后积累一个内存泄露监测工具,square 公司的 LeakCanary,square 确实开源了些好用的东西。LeakCanary 作为一个简单粗暴的工具,用法也相当简单在 build.gradle 中引入 LeakCanary
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
复制代码
一个是 debug 包,一个是 release 包的,从引入包的结构也能看出端倪由于 LeakCanary 是测试整个 app 的内存泄露情况,所以你需要在你的 application 中启动它
package com.zimo.guo;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
/**
* Created by zimo on 15/8/7.
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
复制代码
评论