溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

下載任務(wù)中的網(wǎng)絡(luò)異常處理

發(fā)布時間:2020-06-19 05:04:02 來源:網(wǎng)絡(luò) 閱讀:650 作者:truesea 欄目:開發(fā)技術(shù)

下載過程中的錯誤處理邏輯是:

1. 在DownThread的run方法發(fā)現(xiàn)異常,調(diào)用sendMessage(int type, int data)創(chuàng)建消息添加到隊列中。

@Override
public void run() {
    InputStream is = null;
    HttpURLConnection conn = null;
    try {
        file.seek(start);
        URL connUrl = new URL(url);
        conn = (HttpURLConnection) connUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(DownTask.connectTimeout);
        conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
        int responseCode = conn.getResponseCode();
        Logger.d(TAG, "下載資源的字節(jié)范圍:" + start + "-" + end);
        if (start > end) {
            sendMessage(DownMessage.MSG_SUCCESS, 0);
            return;
        }
        if (responseCode == HttpURLConnection.HTTP_PARTIAL || responseCode == HttpURLConnection.HTTP_OK) {
            is = new BufferedInputStream(conn.getInputStream(), 8192);
            byte[] buffer = new byte[204800];// 20K緩存
            int len = 0;
            while ((len = is.read(buffer)) != -1 && running) {
                file.write(buffer, 0, len);
                sendMessage(DownMessage.MSG_UPDATE, len);
            }
            sendMessage(DownMessage.MSG_SUCCESS, 0);
        } else {
            sendMessage(DownMessage.MSG_ERROR, 10);
        }
    } catch (IOException ex) {
        try {
            sendMessage(DownMessage.MSG_ERROR, 0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ex.printStackTrace();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    } finally {
        try {
            sendMessage(DownMessage.MSG_STOP, 0);
        } catch (InterruptedException e1) {
        }
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
            }
        }
        file = null;
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        is = null;
        if (conn != null)
            conn.disconnect();
        conn = null;
        release();
    }
}

2. 在DownTask的run方法之while循環(huán)中取出隊列中的消息并且進(jìn)行處理。不同類別的消息分別進(jìn)行不同處理,消息類別有:MSG_SUCCESS, MSG_ERROR, MSG_UPDATE, MSG_STOP等。

DownMessage msg;
running = true;
while (running) {
    msg = queue.take();
    switch (msg.type) {
    case DownMessage.MSG_SUCCESS:
        running = false;
        if (downListener != null)
            downListener.onDownFinish();
        break;
    case DownMessage.MSG_UPDATE:
        if (downListener != null) {
            downListener.onDownUpdate(msg.data);
        }
        break;
    case DownMessage.MSG_ERROR:
        running = false;
        if (downThread != null) {
            downThread.canleDown();
        }
        notifyDownError(ERROR_UNKNOWN);
        break;
    case DownMessage.MSG_STOP:
        running = false;
        if (downListener != null) {
            downListener.onDownPause();
        }
        break;
    }
    recyle(msg);

downListener.onDownError因大量使用,所以在提取出來,放在notifyDownError方法中。

/**
 * 下載出錯
 *
 * @param type
 */
private void notifyDownError(int type) {
    if (downListener != null)
        downListener.onDownError(type);
}


3. 在DownService中實現(xiàn)OnDownListener接口,在接口方法中調(diào)用句柄Handler對象來處理不同類別的消息,處理操作包括更新數(shù)據(jù)庫表,展現(xiàn)Toast提示等。

在啟動一個下載任務(wù)時,實現(xiàn)OnDownListener接口。

/**
 * 啟動一個下載任務(wù)。
 *
 * @param down
 * @param downTask
 */
public void launchDownloadTask(final Down down, DownTask downTask) {
    downListener = new OnDownListener() {
        @Override
        public void onDownUpdate(int len) {
            downHandler.obtainMessage(UPDATE_DOWN, len, 0, down).sendToTarget();
        }
        @Override
        public void onDownStart(int total) {
            if (down.getLength() < 1) {
                down.setLength(total);
                down.setLengthStr(Formatter.formatFileSize(DownService.this, total));
            }
        }
        @Override
        public void onDownFinish() {
            downHandler.obtainMessage(DOWN_FINISH, down).sendToTarget();
        }
        @Override
        public void onDownError(int type) {
            handler.obtainMessage(DOWN_FAIL, type, 0, down).sendToTarget();
        }
        @Override
        public void onDownPause() {
            downHandler.obtainMessage(PAUSE_DOWN, down).sendToTarget();
        }
    };
    downTask.setOnDownListener(downListener);
    executorService.execute(downTask);
}

例如,處理WIFI斷開產(chǎn)生的IO異常邏輯:

wifi斷開導(dǎo)致IO異常,創(chuàng)建MSG_ERROR消息,添加到隊列中。從隊列中取出MSG_ERROR消息并處理:取消DownThread線程,設(shè)置running為false以結(jié)束while循環(huán),在OnDownListener接口實現(xiàn)類中,調(diào)用Handler對象更新數(shù)據(jù)庫表等。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI