Handler防治内存泄漏的优化使用方法
.
…
一.为什么进行优化:
在使用handler时,有时候我们会传递参数,这些参数可能包含对某个已经销毁的Activity的上下文的引用。从而导致系统不能回收掉这个Activity导致资源浪费。其根本原因是静态内部类持有了外部类的引用,导致外部activity无法被回收。
.
.
二.怎么优化:
1.将handler设置为静态
2.传递参数时传递弱引用而不是强引用
3.在创建handler的activity中的onDestory回调方法里,加入handler的释放方法:handler.removeCallBack()
案例:
倒计时程序
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello W