Android Loader使用时,屏幕解锁后,重复加载
在使用AsyncTaskLoader时,当手机解锁后,会重复加载数据,代码如下:
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的使用方式。经修改后:
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开发中,官方文档其实是很好的,遵守他们的编写规范,可以使自己少走好多弯路。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。