简体   繁体   中英

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

But Im not sure that I have understand it.

Does the method getAppVersion will cause memory leaks because of the context reference?

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.
  • Use applicationContext() instead of activity context or view context when it's possible. For example, for 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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