Handlers and memory leaks in Android

前端 未结 6 2139
攒了一身酷
攒了一身酷 2020-11-29 18:14

Please have a look at the code below:

public class MyGridFragment extends Fragment{

     Handler myhandler = new Handler() {
    @Override
    public void h         


        
6条回答
  •  清歌不尽
    2020-11-29 18:42

    I run into the same issue and I find that it is one of this topics with many questions and few answeres. My solution is simple and I hope it can help someone:

    /* BEFORE */
    private Handler mHandler= new Handler() {
            @Override public void handleMessage(Message msg) {
            this.doSomething();
        };
    };
    

    We can create a static Handler subclass that simply runs a Runnable. The actual handler instance will know what to do through the runnable that will have access to instance variables.

    /* AFTER */
    static class RunnableHandler extends Handler {
        private Runnable mRunnable;
        public RunnableHandler(Runnable runnable) { 
            mRunnable = runnable;
        }
        @Override public void handleMessage(Message msg) {
            mRunnable.run();
        };
    }
    private RunnableHandler mHandler = new RunnableHandler(new Runnable() {
        @Override public void run() {
            this.doSomething();
        } });
    

    The warning is gone while the funcionality is the same.

提交回复
热议问题