Preventing memory leaks in Android

亡梦爱人 提交于 2020-06-17 09:39:54

问题


Is it wise to get a reference to a Context object in every Activity where I need a Context by getting the Application context? I have learned that it can create memory leaks to throw around your Activity's context object but when you create complex Activities it seems that a Context object is almost always necessary. I was previously declaring a Context variable at the top of the Activity class and initializing it with the "this" keyword in onCreate. I already know this can be poor form, but is it ok to initialize the Context object in onCreate calling getApplicationContext()? In other words does this help solve my problem.

Also, is it better practice to limit the use of static variables? If I'm not mistaken, if I call a static method, or reference a static variable from a different Activity, won't that keep the other Activity in memory too?


回答1:


I think you need to understand the differences between Application Context and Activity Context, please refer to the answer here.

But is it ok to initialise the Context object in onCreate calling getApplicationContext()? In other words does this help solve my problem.

Why do you need to initialise a context object? Activity itself is already a context. For example:

    Intent intent = new Intent(this, MainActivity.class);

You don't need to initialise a context from application context as the activity context has more capabilities. Please refer to this link.

Also, is it better practice to limit the use of static variables? If I'm not mistaken, if I call a static method, or reference a static variable from a different Activity, won't that keep the other Activity in memory too?

For sending a data from one activity to another activity, you might need parcelable object and bundle, or Event Bus to decouple both sender/receiver activity.

For static method, you might need to group them under a Utility class.




回答2:


  1. There is really no need of a Context field in your Activity, as you can always get the context using getBaseContext(), getApplicationContext(), or this (since Activity itself is Context).

  2. You might have to pass your Context to other classes if you want to keep you Activity class thin. This is perfectly ok as long as the lifecycle of those classes is the same as the lifecycle of your Activity. This means, when your Activity is destroyed, no objects should have the reference to the context you passed.

  3. Static methods are extremely good as long as they don't refer to static fields. Use static methods if they don't have a state. Static fields are dangerous for a lot of reasons. So use them only for the right scenarios.



来源:https://stackoverflow.com/questions/47192737/preventing-memory-leaks-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!