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
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:
- 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=\'#\'" /span>
- final WeakTarget target = mTarget.get();
- if (target != null) {
- return this.doInBackground=\'#\'" /span>
- } 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
- }
- }
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);
}