Android Handler内存泄漏解决方法


Android Context内存泄漏的情况很多,有兴趣可阅读以下文章:


Android学习系列(36)--App调试内存泄露之Context篇(上)


Android学习系列(37)--App调试内存泄露之Context篇(下)


下面是关于Handler内存泄漏的一种解决方法:

1、将Handler声明为静态类;

2、在Handler中增加一个对Activity的弱引用(WeakReference);

具体实现如下:

public class MyActivity extends Activity {

	private Handler mHandler = null;
	private final static int MSG_SECCESS = 1;
	private final static int MSG_FAILED = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new ActivityHandler(this);
	}

	private static class ActivityHandler extends Handler {
		private WeakReference activityWeakReference = null;

		public ActivityHandler(Activity activity) {
			activityWeakReference = new WeakReference(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			MyActivity activity = (MyActivity) activityWeakReference.get();
			if (activity != null){
				switch(msg.what) {
				case MSG_SECCESS:
					break;
				case MSG_FAILED:
					break;
				default:
					break;
				}
			}
		}
	}

}


你可能感兴趣的:(Android应用开发)