Android code optimization

1, Handler memory leaks

Produces a memory leak reasons: the static inner classes held by Anonymous using an external class, resulting when the user exits the current Activity, a number of time-consuming operation inside the handler is still running, resulting in activity was also cited handler to do, eventually leading activity and remain in stack, it has not been recovered, leading to memory leaks.

Solution: Internal 1.handler hold weak references of external activity.
        2. The handler instead of static inner classes.
        3. The method of the activity is lost by onDestory mHandler.removeCallBack ().
      (Only 90% solution)

private MyHandler mMyHandler = new MyHandler(this);

private static class MyHandler extends Handler{

   // SoftReference<Activity> 也可以使用软应用 只有在内存不足的时候才会被回收
    private final WeakReference<Activity> mActivity;

    private MyHandler(Activity activity) {
        mActivity = new WeakReference<>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        Activity activity = mActivity.get();
        if (activity != null){
            //做操作
        }
        super.handleMessage(msg);
    }
}

private static final Runnable sRunnable = new Runnable() {
    @Override
    public void run() {
        //做操作
    }
};

 

Published 49 original articles · won praise 2 · Views 8602

Guess you like

Origin blog.csdn.net/yangjunjin/article/details/103281985