参考网站:https://blog.csdn.net/Gods_magic/article/details/85255860
内存泄漏的危害
内存泄漏的危害就是会使虚拟机占用内存过高,导致OOM(内存溢出),使程序异常。
对于一个Android应用来说,打开一个Activity,使用完后关闭,出现内存泄漏;又打开,又关闭,又泄漏;几次之后,程序占用的内存就会超过系统的限制,导致FC。
public class TestActivity extends AppCompatActivity {
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
handler.postDelayed(new Runnable() {
@Override
public void run() {
}
},10000);
finish();
}
}
public static class MyHandler extends Handler{
private WeakReference<TestActivity> mActivity;
public MyHandler(TestActivity activity){
mActivity = new WeakReference(activity);
}
@Override
public void handleMessage(Message msg) {
if (mActivity.get() == null) {
return;
}
//接受到消息的处理
}
}