Android内部类内存泄漏和上下文泄漏?

时间:2015-10-26 06:20:33

标签: java android memory-leaks inner-classes android-context

我在启动画面中使用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.*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initTracker();
                /* Create an Intent that will start the Next-Activity. */
                checkLoginStatus();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }

在另一个活动中,我将上下文传递给一个类并按照 按钮单击 中的上下文进行操作。

 private Tools tools;

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

工具

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

这些中的任何一个都是泄漏的原因吗?

如何使用处理程序如下..

 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 个答案:

答案 0 :(得分:1)

  1. HandlerRunnable不应以匿名方式使用。
  2. 您应该避免将整个活动作为参数传递给其他类。如果您只想使用上下文activity.getContext()
  3. 此处更多信息:
    http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html http://www.androiddesignpatterns.com/2013/04/activitys-threads-memory-leaks.html