问题
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:
There is really no need of a
Context
field in yourActivity
, as you can always get the context usinggetBaseContext()
,getApplicationContext()
, orthis
(since Activity itself is Context).You might have to pass your
Context
to other classes if you want to keep youActivity
class thin. This is perfectly ok as long as the lifecycle of those classes is the same as the lifecycle of yourActivity
. This means, when your Activity is destroyed, no objects should have the reference to the context you passed.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