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.
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();
}
}
}
Recommended reading articles about memory leaks
Android memory leaks - full analysis and solutions
Ask the question, you will understand after looking at the following two situations.
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.
The variables within the method are all local variables and will not be held after the method is completed.
Of course you can, there’s nothing wrong with it
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.
It is recommended to use the weak reference method upstairs. The official use of Handler is also the same method
If it makes sense, it can obviously be used like this
But! ! ! Please don't do this, as mentioned above, memory leak