android - 静态方法中可以持有Activity对象吗
PHP中文网
PHP中文网 2017-04-17 17:29:34
0
7
702

静态方法中可以持有Activity对象吗,这么做不好吧
GC的销毁Activity时会不会因为静态方法持有引用而销毁不了啊

PHP中文网
PHP中文网

认证0级讲师

reply all(7)
大家讲道理

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.

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.

洪涛

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.

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();
        }
    }
}
巴扎黑

It is recommended to use the weak reference method upstairs. The official use of Handler is also the same method

Peter_Zhu

If it makes sense, it can obviously be used like this

But! ! ! Please don't do this, as mentioned above, memory leak

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template