静态方法中可以持有Activity对象吗,这么做不好吧
GC的销毁Activity时会不会因为静态方法持有引用而销毁不了啊
大家讲道理2017-04-17 17:31:34
Recommended reading articles about memory leaks
Android memory leaks - full analysis and solutions
巴扎黑2017-04-17 17:31:34
Ask the question, you will understand after looking at the following two situations.
public class A{
public static a(Activity activity){
// do something
}
}
public class B{
private static Activity mActivity;
public static b(Activity activity){
mActivity = activity;
// do something
}
}
The static method a in A passes in an Activity object, and then the method ends, and the life cycle of the activity referenced by the Activity ends. This will not cause leakage, no problem.
The static method b in B passes in an Activity object, and then B’s member variable mActivity receives this reference. This static member variable will always exist in the process, which will cause a memory leak.
PHP中文网2017-04-17 17:31:34
The variables within the method are all local variables and will not be held after the method is completed.
巴扎黑2017-04-17 17:31:34
To add to the answer above, if class B is a static inner class and you must hold a reference to the activity, you can consider weak references.
static class B {
private WeakReference<Activirty> ref;
public void setRef(Activity activity) {
this.ref = new WeakReference<>(activity);
}
public void doSomething(){
if (ref.get() != null){
ref.get().doSomething();
}
}
}
巴扎黑2017-04-17 17:31:34
It is recommended to use the weak reference method upstairs. The official use of Handler is also the same method
天蓬老师2017-04-17 17:31:34
If it makes sense, it can obviously be used like this
But! ! ! Please don't do this, as mentioned above, memory leak