1 package com.android.settings.intelligence.utils; 2 3 import android.content.AsyncTaskLoader; 4 import android.content.Context; 5 6 /** 7 * This class fills in some boilerplate for AsyncTaskLoader to actually load things. 8 * 9 * Subclasses need to implement {@link AsyncLoader#loadInBackground()} to perform the actual 10 * background task, and {@link AsyncLoader#onDiscardResult(T)} to clean up previously loaded 11 * results. 12 * 13 * This loader is based on the MailAsyncTaskLoader from the AOSP EmailUnified repo. 14 */ 15 public abstract class AsyncLoader<T> extends AsyncTaskLoader<T> { 16 private T mResult; 17 AsyncLoader(final Context context)18 public AsyncLoader(final Context context) { 19 super(context); 20 } 21 22 @Override onStartLoading()23 protected void onStartLoading() { 24 if (mResult != null) { 25 deliverResult(mResult); 26 } 27 28 if (takeContentChanged() || mResult == null) { 29 forceLoad(); 30 } 31 } 32 33 @Override onStopLoading()34 protected void onStopLoading() { 35 cancelLoad(); 36 } 37 38 @Override deliverResult(final T data)39 public void deliverResult(final T data) { 40 if (isReset()) { 41 if (data != null) { 42 onDiscardResult(data); 43 } 44 return; 45 } 46 47 final T oldResult = mResult; 48 mResult = data; 49 50 if (isStarted()) { 51 super.deliverResult(data); 52 } 53 54 if (oldResult != null && oldResult != mResult) { 55 onDiscardResult(oldResult); 56 } 57 } 58 59 @Override onReset()60 protected void onReset() { 61 super.onReset(); 62 63 onStopLoading(); 64 65 if (mResult != null) { 66 onDiscardResult(mResult); 67 } 68 mResult = null; 69 } 70 71 @Override onCanceled(final T data)72 public void onCanceled(final T data) { 73 super.onCanceled(data); 74 75 if (data != null) { 76 onDiscardResult(data); 77 } 78 } 79 80 /** 81 * Called when discarding the load results so subclasses can take care of clean-up or 82 * recycling tasks. This is not called if the same result (by way of pointer equality) is 83 * returned again by a subsequent call to loadInBackground, or if result is null. 84 * 85 * Note that this may be called concurrently with loadInBackground(), and in some circumstances 86 * may be called more than once for a given object. 87 * 88 * @param result The value returned from {@link AsyncLoader#loadInBackground()} which 89 * is to be discarded. 90 */ onDiscardResult(final T result)91 protected abstract void onDiscardResult(final T result); 92 }