Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AsyncTaskLoader 資料重複加載問題:螢幕解鎖後為何又跑一次?

編輯:關於 Android 程式設計

使用 AsyncTaskLoader 時,只要手機螢幕關閉再解鎖,清單資料就會重複載入一次。這個現象看起來莫名其妙,但原因其實很單純:Loader 的生命週期回呼沒有被正確實作。

問題重現

原本的寫法如下,onStartLoading() 直接無條件呼叫 forceLoad():

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 的官方實作

翻過 CursorLoader 的源碼後才發現,問題出在自己沒有照官方範例的思維去寫。正確的版本需要多維護一份「已載入的資料」,並在停止與重置時妥善處理狀態:

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;
    }

    /* 在背景執行緒中執行 */
    @Override
    public List<CouponStore> loadInBackground() {
        mData = ds.queryShopByCoupon(couponId, pageNo, PAGE_SIZE);
        return mData;
    }

    /* 在 UI 執行緒中執行 */
    @Override
    public void deliverResult(List<CouponStore> data) {
        if (isReset()) {
            return;
        }
        if (isStarted()) {
            super.deliverResult(data);
        }
    }

    /* 必須在 UI 執行緒呼叫 */
    @Override
    protected void onStartLoading() {
        if (mData != null) {
            deliverResult(mData);
        }
        if (takeContentChanged() || mData == null) {
            forceLoad();
        }
    }

    @Override
    protected void onStopLoading() {
        cancelLoad();
    }

    @Override
    public void onCanceled(List<CouponStore> data) {
    }

    @Override
    protected void onReset() {
        super.onReset();
        onStopLoading();
        mData = null;
    }
}

關鍵在 onStopLoading()

改完之後重複載入的問題就消失了。真正的原因在於少了這一段:

@Override
protected void onStopLoading() {
    // 嘗試取消當前的載入工作
    cancelLoad();
}

流程是這樣的:螢幕關閉時系統會呼叫 onStopLoading(),此時應該主動取消進行中的載入;螢幕解鎖時則會走到 onStartLoading(),在這裡判斷手上已有的資料是否仍然有效,只有真的需要時才觸發 forceLoad()。

如果 onStartLoading() 少了這層狀態判斷,等於每次回到前台都重新打一次後端,重複載入自然無可避免。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved