一、Context引起内存泄漏的原因
我们在Android开发的过程中经常会用到Context,比如自定义一个Toast工具类,里面封装了连续点击不会重复弹出Toast的功能,当调用这个工具类时传入Activity的Context就有可能引起内存泄漏。
具体原因通过一个例子来分析:
private static Toast sToast;
public static void show(Context context, String text) {
if (sToast == null) {
sToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
} else {
sToast.setText(text);
}
sToast.setGravity(Gravity.CENTER, 0, 0);
sToast.show();
}
以上写法当在Activity中调用时可能会引起Activity的内存泄漏
MToast.show(this, "安卓梦雪");
这是因为sToast对象是静态的,因此它的生命周期与Application一样长,当Activity被销毁后,Activity的实例仍然被sToast持有,导致Activity无法被GC回收从而引起内存泄漏。
二、解决Context引起的内存泄漏
既然我们已经知道了Context引起内存泄漏的原因,那么我们就可以对症下药来解决这个问题。
private static Toast sToast;
public static void show(Context context, String text) {
if (sToast == null) {
sToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);
} else {
sToast.setText(text);
}
sToast.setGravity(Gravity.CENTER, 0, 0);
sToast.show();
}
这里我们修改成了使用getApplicationContext()去弹出Toast,因为getApplicationContext()返回的对象是Application的Context,而Application的生命周期和整个应用是一样的,应用启动后Application被创建,整个应用退出后Application被摧毁。所以Application的Context的生命周期就是整个应用的生命周期。使用Application的Context就不会引起内存泄漏了。
本文由安卓梦雪发布于AIDE教程网
Yes, if an individual declares that he/she consumes tobacco/alcohol then the premium for a
life insurance plan increases because of high-risk concerned.
https://cutt.ly/cTQzyQ5
Title insurance provides a guarantee that title to actual property
is vested in the purchaser or mortgagee, free and clear of liens or encumbrances.
https://bit.ly/3oApjKw
Such insurance is often very restricted in the scope of problems
that are covered by the policy.
With Progressive, you presumably can take your boat to any lake or river, plus ocean waters inside 75 miles
of the coast.
https://cutt.ly/xTQzjTP
The deductible is a certain quantity the policy-holder must pay
out-of-pocket before the insurer pays a declare.
Annual premium for a basic legal responsibility policy excludes
journey trailer and is not out there in all states.
https://szkolajezdziectwa.pl
https://cztery-kopyta.pl
Learn about the dangers – and the way to mitigate them – at Chubb’s Risk Engineering Center.
With Progressive, you’ll be able to take your boat to any lake or river, plus ocean waters inside seventy five miles of
the coast.