Android Loader使用時,螢幕解鎖後,重複載入
在使用AsyncTaskLoader時,當手機解鎖後,會重複載入資料,代碼如下:
static class CouponShopQueryLoader extendsAsyncTaskLoader> {private int couponId;public CouponShopQueryLoader(Context context, int couponId) {super(context);this.couponId = couponId;}@Overrideprotected void onStartLoading() {forceLoad();}@Overridepublic List loadInBackground() {//查詢資料載入}}
這時候,很奇怪的現象就出來了,每次手機解鎖後,資料都會重複了,重複載入。經查閱CursorLoader源碼後發現,原來還是自己太嫩了,loader使用時,沒有嚴格遵守android官方協助文檔demo的使用方式。經修改後:
static class CouponShopQueryLoader2 extendsAsyncTaskLoader> {private List mData;private int couponId;public CouponShopQueryLoader2(Context context, int couponId) {super(context);this.couponId = couponId;}// final ForceLoadContentObserver mObserver;/* Runs on a worker thread */@Overridepublic List loadInBackground() {mData = ds.queryShopByCoupon(couponId, pageNo, PAGE_SIZE);return mData;}/* Runs on the UI thread */@Overridepublic void deliverResult(List data) {if (isReset()) {return;}if (isStarted()) {super.deliverResult(data);}}/** * Starts an asynchronous load of the contacts list data. When the * result is ready the callbacks will be called on the UI thread. If a * previous load has been completed and is still valid the result may be * passed to the callbacks immediately. * * Must be called from the UI thread */@Overrideprotected void onStartLoading() {if (mData != null) {deliverResult(mData);}if (takeContentChanged() || mData == null) {forceLoad();}}/** * Must be called from the UI thread */@Overrideprotected void onStopLoading() {Log.d(sss, onStopLoading);// Attempt to cancel the current load task if possible.cancelLoad();}@Overridepublic void onCanceled(List cursor) {Log.d(sss, onCanceled);}@Overrideprotected void onReset() {super.onReset();Log.d(sss, onReset);// Ensure the loader is stoppedonStopLoading();mData = null;}}修改後,重複載入的現象解決了,究其原因是沒有重寫
/** * Must be called from the UI thread */@Overrideprotected void onStopLoading() {Log.d(sss, onStopLoading);// Attempt to cancel the current load task if possible.cancelLoad();}
當手機螢幕關閉時,會調用onStopLoading()方法,此時應該將loader取消掉,當螢幕解鎖時,會去執行onStartLoading()方法,在onStartLoading方法中根據資料是否需要重新載入進行判斷。而如果不在onStartLoading進行loader狀態判斷的話,就導致了資料重複載入的問題! ok---解決了!