AsyncTask inner class

The life cycle of the Thread object generated by the AsyncTask class is uncertain and cannot be controlled by the application. Therefore, if AsyncTask is used as an internal class of Activity, it is more prone to memory leaks. The solution to this problem was found on the Internet by Xiao Ma and recorded in the txt, as follows: 
6.1: Change the internal class of the thread to a static internal class.
6.2: Use weak references to save Context references within the thread

The sample code is as follows:

 
  
  
  1. public abstract class WeakAsyncTask<Params, Progress, Result, WeakTarget> extends 
  2.             AsyncTask<Params, Progress, Result> { 
  3.         protected WeakReference<WeakTarget> mTarget;   
  4.  
  5.         public WeakAsyncTask(WeakTarget target) { 
  6.             mTarget = new WeakReference<WeakTarget>(target); 
  7.         }   
  8.  
  9.         /** {@inheritDoc} */ 
  10.         @Override 
  11.         protected final void onPreExecute() { 
  12.             final WeakTarget target = mTarget.get(); 
  13.             if (target != null) { 
  14.                 this.onPreExecute(target); 
  15.             } 
  16.         }   
  17.  
  18.         /** {@inheritDoc} */ 
  19.         @Override 
  20.         protected final Result doInBackground=\'#\'" /span>
  21.             final WeakTarget target = mTarget.get(); 
  22.             if (target != null) { 
  23.                 return this.doInBackground=\'#\'" /span>
  24.             } else { 
  25.                 return null
  26.             } 
  27.         }   
  28.  
  29.         /** {@inheritDoc} */ 
  30.         @Override 
  31.         protected final void onPostExecute(Result result) { 
  32.             final WeakTarget target = mTarget.get(); 
  33.             if (target != null) { 
  34.                 this.onPostExecute(target, result); 
  35.             } 
  36.         }   
  37.  
  38.         protected void onPreExecute(WeakTarget target) { 
  39.             // No default action 
  40.         }   
  41.  
  42.         protected abstract Result doInBackground(WeakTarget target, Params... params);   
  43.  
  44.         protected void onPostExecute(WeakTarget target, Result result) { 
  45.             // No default action 
  46.         } 
  47.  
  1.     } 
public abstract class WeakReferenceHandler<T> extends Handler {
    private WeakReference<T> mReference;
 
    public WeakReferenceHandler(T reference) {
        mReference = new WeakReference<T>(reference);
    }
 
    @Override
    public void handleMessage(Message msg) {
        if (mReference.get() == null)
            return;
        handleMessage(mReference.get(), msg);
    }
 
    protected abstract void handleMessage(T reference, Message msg);
}
 


Guess you like

Origin blog.csdn.net/fuweiping/article/details/19030275