朱纯树博客
VPS测评推荐网站
cloudacead cloudacead

Android避免Context引起的内存泄漏

一、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教程网

原文链接:https://www.aidemx.cn/3229.html

赞(1) 打赏
未经允许不得转载:VPS测评推荐网站 - 朱纯树博客 » Android避免Context引起的内存泄漏

评论 88

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #90

    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.

  2. #89
  3. #88

    Title insurance provides a guarantee that title to actual property
    is vested in the purchaser or mortgagee, free and clear of liens or encumbrances.

  4. #87
  5. #86

    Such insurance is often very restricted in the scope of problems
    that are covered by the policy.

  6. #85

    With Progressive, you presumably can take your boat to any lake or river, plus ocean waters inside 75 miles
    of the coast.

  7. #84
  8. #83

    The deductible is a certain quantity the policy-holder must pay
    out-of-pocket before the insurer pays a declare.

  9. #82

    Annual premium for a basic legal responsibility policy excludes
    journey trailer and is not out there in all states.

    tinyurl.com1个月前 (07-03)回复
  10. #81
  11. #80
  12. #79

    Learn about the dangers – and the way to mitigate them – at Chubb’s Risk Engineering Center.

    https://rebrand.ly/2个月前 (06-25)回复
  13. #78

    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.

    is.gd2个月前 (06-25)回复