Kotlin中 `companion object`内即为静态申明。以下代码并未申明在此内 ,下面就结合代码看一下自定义的Handler类
class MyHandler(var activity: TestActivity) : Handler(Looper.getMainLooper()) {
var weakReference = WeakReference(activity)
override fun handleMessage(msg: Message) {
weakReference.get()!!.activityMainBinding.tv.text = "测试"
}
}
在kotlin中定义一个Handler类,这时候使用Android Studio自带的工具转换成java文件
public static final class MyHandler extends Handler {
@NotNull
private WeakReference weakReference;
@NotNull
private TestActivity activity;
@NotNull
public final WeakReference getWeakReference() {
return this.weakReference;
}
public final void setWeakReference(@NotNull WeakReference var1) {
Intrinsics.checkNotNullParameter(var1, "" );
this.weakReference = var1;
}
public void handleMessage(@NotNull Message msg) {
TextView var2 = ((TestActivity)var10000).getActivityMainBinding().tv;
Intrinsics.checkNotNullExpressionValue(var2, "weakReference.get()!!.activityMainBinding.tv");
var2.setText((CharSequence)"测试");
}
转换后的java代码,发现这个handler为静态类,执行一段代码
myHandler.sendEmptyMessageDelayed(1, 10000)
这时候两个Activity反复点击几次使用leakcanary检测会发现出现泄露了,说明在使用这个弱引用的时候并不能解决泄漏问题,下面看另一种写法
inner class MyHandler(activity: TestActivity) : Handler(Looper.getMainLooper()) {
var weakReference = WeakReference(activity)
override fun handleMessage(msg: Message) {
weakReference.get()!!.activityMainBinding.tv.text = "测试"
}
}
inner既代表为内部类,转换成java代码后
public final class MyHandler extends Handler {
@NotNull
private WeakReference weakReference;
@NotNull
public final WeakReference getWeakReference() {
return this.weakReference;
}
public final void setWeakReference(@NotNull WeakReference var1) {
Intrinsics.checkNotNullParameter(var1, "" );
this.weakReference = var1;
}
public void handleMessage(@NotNull Message msg) {
TextView var2 = ((TestActivity)var10000).getActivityMainBinding().tv;
Intrinsics.checkNotNullExpressionValue(var2, "weakReference.get()!!.activityMainBinding.tv");
var2.setText((CharSequence)"测试");
}
public MyHandler(@NotNull TestActivity activity) {
Intrinsics.checkNotNullParameter(activity, "activity");
super(Looper.getMainLooper());
this.weakReference = new WeakReference(activity);
}
}
执行同样的操作后一样也会出现内存泄漏。经过测试发现最终解决泄漏的 是Handler的removeCallbacksAndMessages方法
myHandler.removeCallbacksAndMessages(null)
在结束Activity的时候执行这段代码即可解决泄漏问题(上述泄漏问题是Handler消息延迟问题导致)。
追根朔源看下这个方法最终的执行
synchronized (this) {
Message p = mMessages;
// Remove all messages after front.
while (p != null) {
Message n = p.next;//获取下一个message
if (n != null) {
if (n.target == h && (object == null || n.obj == object)) {
Message nn = n.next;//拿到下一个message
n.recycleUnchecked();//将当前的message重置释放掉
p.next = nn;//将拿到的message作为p.next的节点,再次执行重复操作,直到释放掉所有message
continue;
}
}
p = n;
}
}
最终解决了handler延迟消息导致的内存泄漏问题。
个人认为,handler不论任何情况下 ,在不需要的情况下执行removeCallbacksAndMessages即可,因为持有链
从as提供的工具profiler分析得出,Activity被handler持有,handler被message持有,message被MessageQueue持有。
以上仅是个人分析经过实践分析得出,希望大家多多指证。