参见:http://blog.chinaunix.net/space.php?uid=20787846&do=blog&cuid=2289102
http://winuxxan.blog.51cto.com/2779763/512179
有些人喜欢用Android提供的AsyncTask,但事实上AsyncTask的问题更加严重,Thread只有在run函数不结束时才出现这种内存泄露问题,然而AsyncTask内部的实现机制是运用了ThreadPoolExcutor,该类产生的Thread对象的生命周期是不确定的,是应用程序无法控制的,因此如果AsyncTask作为Activity的内部类,就更容易出现内存泄露的问题。
这种线程导致的内存泄露问题应该如何解决呢?
第一、将线程的内部类,改为静态内部类。
第二、在线程内部采用弱引用保存Context引用。
解决的模型如下:
- public abstract class WeakAsyncTask<Params, Progress, Result, WeakTarget> extends
- AsyncTask<Params, Progress, Result> {
- protected WeakReference<WeakTarget> mTarget;
- public WeakAsyncTask(WeakTarget target) {
- mTarget = new WeakReference<WeakTarget>(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
- }
- }