search

Home  >  Q&A  >  body text

android - 静态方法中可以持有Activity对象吗

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

PHP中文网PHP中文网2771 days ago696

reply all(7)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 17:31:34

    Recommended reading articles about memory leaks
    Android memory leaks - full analysis and solutions

    reply
    0
  • 巴扎黑

    巴扎黑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.

    reply
    0
  • PHP中文网

    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.

    reply
    0
  • 黄舟

    黄舟2017-04-17 17:31:34

    Of course you can, there’s nothing wrong with it

    reply
    0
  • 巴扎黑

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

    reply
    0
  • 巴扎黑

    巴扎黑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

    reply
    0
  • 天蓬老师

    天蓬老师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

    reply
    0
  • Cancelreply