简体   繁体   English

android中的上下文内存泄漏

[英]Context memory leaks in android

I have read on the developers blog about Context memory leaks.我在开发人员博客上阅读了有关上下文内存泄漏的信息。

http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

But Im not sure that I have understand it.但我不确定我是否理解它。

Does the method getAppVersion will cause memory leaks because of the context reference? getAppVersion方法是否会因为上下文引用而导致内存泄漏?

public class A
{

public static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

}

public class B extends Activity
{

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.b);

       int version = A.getAppVersion(this);

}

}

What about context memory leaks - agree with what was said before, and here is what helps me to avoid them in the application:上下文内存泄漏怎么样 - 同意之前所说的,以下是帮助我在应用程序中避免它们的方法:

  • Avoid using static variables for views or context-related references.避免对视图或上下文相关引用使用静态变量。
  • Pass a context-related reference to a Singleton class.将上下文相关的引用传递给 Singleton 类。
  • Use applicationContext() instead of activity context or view context when it's possible.尽可能使用 applicationContext() 而不是活动上下文或查看上下文。 For example, for Toasts, Snackbars.例如,对于 Toasts、Snackbars。
  • Use a weak reference of the context-related references when needed.需要时使用上下文相关引用的弱引用。

Here is some more details on these cases https://www.symphony-solutions.eu/fixing-memory-leaks-in-android/以下是有关这些案例的更多详细信息https://www.symphony-solutions.eu/fixing-memory-leaks-in-android/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM