Android Loader使用,屏幕解鎖,重複荷載

正在使用AsyncTaskLoader時間。當手機被解鎖,重複加載數據,碼,如如下:html

	static class CouponShopQueryLoader extends
			AsyncTaskLoader<List<CouponStore>> {
		
		private int couponId;
		

		public CouponShopQueryLoader(Context context, int couponId) {
			super(context);
			this.couponId = couponId;
			
		}

		@Override
		protected void onStartLoading() {
			
			forceLoad();
		}

		@Override
		public List<CouponStore> loadInBackground() {
			//查詢數據載入
		}
	}

這時候,很是奇怪的現象就出來了,每次手機解鎖後,數據都會反覆了,反覆載入。經查閱CursorLoader源代碼後發現,原來仍是本身太嫩了,loader使用時。沒有嚴格遵照android官方幫助文檔demo的使用方式。

經改動後:java

	static class CouponShopQueryLoader2 extends
			AsyncTaskLoader<List<CouponStore>> {

		private List<CouponStore> mData;
		private int couponId;

		public CouponShopQueryLoader2(Context context, int couponId) {
			super(context);
			this.couponId = couponId;
			
		}

		// final ForceLoadContentObserver mObserver;

		/* Runs on a worker thread */
		@Override
		public List<CouponStore> loadInBackground() {
			mData = ds.queryShopByCoupon(couponId, pageNo, PAGE_SIZE);
			return mData;
		}

		/* Runs on the UI thread */
		@Override
		public void deliverResult(List<CouponStore> 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
		 */
		@Override
		protected void onStartLoading() {
			if (mData != null) {
				deliverResult(mData);
			}
			if (takeContentChanged() || mData == null) {
				forceLoad();
			}
		}

		/**
		 * Must be called from the UI thread
		 */
		@Override
		protected void onStopLoading() {
			Log.d("sss", "onStopLoading");
			// Attempt to cancel the current load task if possible.
			cancelLoad();
		}

		@Override
		public void onCanceled(List<CouponStore> cursor) {
			Log.d("sss", "onCanceled");
		}

		@Override
		protected void onReset() {
			super.onReset();
			Log.d("sss", "onReset");
			// Ensure the loader is stopped
			onStopLoading();
			mData = null;
		}

	}
改動後。反覆載入的現象攻克了,究其緣由是沒有重寫

	/**
		 * Must be called from the UI thread
		 */
		@Override
		protected void onStopLoading() {
			Log.d("sss", "onStopLoading");
			// Attempt to cancel the current load task if possible.
			cancelLoad();
		}

當手機屏幕關閉時,會調用onStopLoading()方法,此時應該將loader取消掉,當屏幕解鎖時,會去運行onStartLoading()方法,在onStartLoading方法中依據數據是否需要又一次載入進行推斷。而假設不在onStartLoading進行loader狀態推斷的話。就致使了數據反覆載入的問題! ok---攻克了!


提示:在學習android開發中。官方文檔事實上是很是好的,遵照他們的編寫規範,可以使本身少走好多彎路。



android


版權聲明:本文博客原創文章,博客,未經贊成,不得轉載。async

相關文章
相關標籤/搜索