Android inner classes memory leak and leak by cont

2019-05-31 18:39发布

问题:

I am using Handler in my splash screen for delaying redirection to the next activity as follows..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entrance);
        screenTimeOut();
    }

    private void screenTimeOut() {
          /* New Handler to start the next screen
         * and close this Entrance after some seconds.*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initTracker();
                /* Create an Intent that will start the Next-Activity. */
                checkLoginStatus();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }

And in another activity am passing context to a class and holding the context inside that as follows on button click ..

 private Tools tools;

 tools = new Tools(DetailsScreen.this, true);

Tools

    private Context _context;
    private Fragment _fragment;
    private Activity activity;
    private String filePath = null;
    private String camImagePath = null;

    public Tools() {
    }

    public Tools(Context _context, boolean flag) {
        this._context = _context;
        this.activity = (Activity) _context;
        initPath();
        if (flag) {
            createImageFile();
        }
    }

Is any one of these will be a reason for leakage ?

And how about using handler as follows..

 private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entrance);
        screenTimeOut();
    }

 private void screenTimeOut() {
          /* New Handler to start the next screen
         * and close this Entrance after some seconds.*/
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initTracker();
                /* Create an Intent that will start the Next-Activity. */
                checkLoginStatus();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

回答1:

  1. Handler and Runnable should not be used in anonymous fashion.
  2. You should avoid passing the whole activity as a parameter to other classes. If context is all that you want use activity.getContext().

More info here:
http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html