This Handler class should be static or leaks might occur: IncomingHandler

前端 未结 7 1912
深忆病人
深忆病人 2020-11-22 07:14

I\'m developing an Android 2.3.3 application with a service. I have this inside that service to communicate with Main activity:

public class UDPListenerServi         


        
7条回答
  •  甜味超标
    2020-11-22 07:30

    Here is a generic example of using a weak reference and static handler class to resolve the problem (as recommended in the Lint documentation):

    public class MyClass{
    
      //static inner class doesn't hold an implicit reference to the outer class
      private static class MyHandler extends Handler {
        //Using a weak reference means you won't prevent garbage collection
        private final WeakReference myClassWeakReference; 
    
        public MyHandler(MyClass myClassInstance) {
          myClassWeakReference = new WeakReference(myClassInstance);
        }
    
        @Override
        public void handleMessage(Message msg) {
          MyClass myClass = myClassWeakReference.get();
          if (myClass != null) {
            ...do work here...
          }
        }
      }
    
      /**
       * An example getter to provide it to some external class
       * or just use 'new MyHandler(this)' if you are using it internally.
       * If you only use it internally you might even want it as final member:
       * private final MyHandler mHandler = new MyHandler(this);
       */
      public Handler getHandler() {
        return new MyHandler(this);
      }
    }
    

提交回复
热议问题