AsyncTask的深度优化(内存泄露)

AsyncTask底层虽然是封装了线程和handler,但是不可避免的出现了内存泄露的问题。

直接上代码:

package com.bmsh.router.http;

import java.lang.ref.WeakReference;

import com.bmsh.router.inteface.RouterMsgCallback;

import android.os.AsyncTask;

public abstract class WeakAsyncTask
		extends AsyncTask {
	protected WeakReference mTarget;
	public WeakAsyncTask(WeakTarget target) {
		mTarget = new WeakReference(target);
	}

	/** {@inheritDoc} */
	@Override
	protected final void onPreExecute() {
		final WeakTarget target = mTarget.get();
		if (target != null) {
			this.onPreExecute(target);
		}
	}

	/** {@inheritDoc} */
	@Override
	protected final Result doInBackground(Params... params) {
		final WeakTarget target = mTarget.get();
		if (target != null) {
			return this.doInBackground(target, params);
		} else {
			return null;
		}
	}

	/** {@inheritDoc} */
	@Override
	protected final void onPostExecute(Result result) {
		final WeakTarget target = mTarget.get();
		if (target != null) {
			this.onPostExecute(target, result);
		}
	}

	protected void onPreExecute(WeakTarget target) {
		// No default action
	}

	protected abstract Result doInBackground(WeakTarget target,
			Params... params);

	protected void onPostExecute(WeakTarget target, Result result) {
		// No default action
	}
}

自己写的task类来继承这个类即可

你可能感兴趣的:(Android,网络)