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

Android 圖片上傳實戰:進度條更新與隨時中止上傳

編輯:關於 Android 程式設計

本文承接上一篇,重點放在兩件實務上常被忽略的事:如何在後台上傳圖片時即時更新進度,以及如何讓使用者隨時中止整個上傳過程。

一、用 AsyncTask 包一層

在 Activity 中把上傳動作放進背景任務,避免阻塞主執行緒:

private class UploadPhotoTask extends AsyncTask<String, Void, Boolean> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return HttpUploadedFile.getInstance()
                .doUploadPhoto(getApplicationContext(), mUploadFilePathName, mHandler);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        mIsUploading = false;
        showProgressBar(false);
        if (result) {
            Toast.makeText(UploadPhotoActivity.this, R.string.upload_photo_fail, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(UploadPhotoActivity.this, R.string.upload_photo_fail, Toast.LENGTH_SHORT).show();
        }
    }
}

二、用 Handler 接收進度回報

上傳模組在每次寫出資料後發一則訊息,Activity 這邊用 Handler 接收並刷新進度條寬度:

/** 接收上傳模組的進度通知 */
private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case HttpUploadedFile.POST_PROGRESS_NOTIFY:
                int completePercent = msg.arg1;
                HandleUploadProgress(completePercent);
                break;
            default:
                break;
        }
    }
};

/** 處理上傳進度通知 */
private void HandleUploadProgress(int completePercent) {
    View containerView = findViewById(R.id.photo_upload_progress_bar_container);
    int maxLen = containerView.getWidth(); // 進度條父容器的寬度
    int barLen = (completePercent * maxLen) / 100;

    View barView = findViewById(R.id.photo_upload_progress_bar);
    LayoutParams params = new LayoutParams();
    params.height = LayoutParams.FILL_PARENT;
    params.width = barLen;
    barView.setLayoutParams(params); // 更新進度條寬度
}

/** 顯示或隱藏進度條 */
private void showProgressBar(boolean show) {
    View view = findViewById(R.id.photo_upload_progress_layout);
    if (show) {
        view.setVisibility(View.VISIBLE);
        View bar = view.findViewById(R.id.photo_upload_progress_bar);
        LayoutParams params = new LayoutParams();
        params.height = LayoutParams.FILL_PARENT;
        params.width = 3;
        bar.setLayoutParams(params);
    } else {
        view.setVisibility(View.GONE);
    }
}

三、上傳模組本體

關鍵設計有幾個:以單例形式提供服務、用 bIsStop 旗標控制中止、以 objAbort 搭配 wait/notify 讓 cancel 呼叫能等到上傳迴圈真正結束。

public class HttpUploadedFile {

    /** 單一實例 */
    private static HttpUploadedFile instance = null;

    private HttpUploadedFile() {}

    /** 工廠方法 */
    public static synchronized HttpUploadedFile getInstance() {
        if (instance == null) {
            instance = new HttpUploadedFile();
        }
        return instance;
    }

    String url = "https://2.novelread.sinaapp.com/framework-sae/index.php?c=main&a=getPostBody";

    private int lastErrCode = 0;   // 最近一次錯誤碼
    byte[] tmpBuf = new byte[BUF_LEN];
    byte[] tmpBuf2 = new byte[BUF_LEN * 2];

    public static final int POST_PROGRESS_NOTIFY = 101;

    HttpURLConnection connection = null;

    public static final int HTTP_ARGUMENT_ERR = -1001;   // 參數錯誤
    public static final int HTTP_RESPONSE_EMPTY = -1002; // 回應為空
    public static final int HTTP_URL_ERR = -1003;        // URL 格式錯誤
    public static final int HTTP_GZIP_ERR = -1004;       // 解壓縮失敗
    public static final int HTTP_CANCELED = -1005;       // 已取消
    public static final int HTTP_EXCEPTION = -1006;      // 發生異常

    private boolean bIsStop = false;
    protected Object objAbort = new Object();
    private Handler mHandler = null;

    public static final int TIMEOUT = 30000; // 逾時 30 秒
    private static final int BUF_LEN = 512;  // 緩衝區長度

    public boolean doUploadPhoto(Context context, String filePathName, Handler handler) {
        boolean ret = false;
        File file = new File(filePathName);
        if (!file.exists()) {
            return false;
        }
        FileInputStream fs = null;
        if (file != null) {
            try {
                fs = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (file == null || fs == null) {
            return false;
        }
        mHandler = handler;
        ret = postWithoutResponse(context, url, fs, (int) file.length());
        if (fs != null) {
            try {
                fs.close();
                fs = null;
            } catch (Exception e) {
                // ignore
            }
        }
        return ret;
    }
}

核心的 POST 邏輯如下,注意 iStreamLen 是檔案大小,單位為位元組:

public Boolean postWithoutResponse(Context context, final String strUrl,
                                    InputStream dataStream, int iStreamLen) {
    if (TextUtils.isEmpty(strUrl) || dataStream == null || iStreamLen <= 0) {
        lastErrCode = HTTP_ARGUMENT_ERR;
        return false;
    }

    URL postUrl = null;
    try {
        postUrl = new URL(strUrl);
    } catch (MalformedURLException ex) {
        Log.e("HttpUtil", "get MalformedURL", ex);
        lastErrCode = HTTP_URL_ERR;
        return false;
    }

    bIsStop = false;
    InputStream input = null;
    DataOutputStream ds = null;
    ByteArrayOutputStream byteOutStream = null;
    HttpURLConnection conn = null;
    byte[] outData = null;

    try {
        if (bIsStop) {
            lastErrCode = HTTP_CANCELED;
            return false;
        }

        conn = getConnection(context, postUrl);
        connection = conn;
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(TIMEOUT * 3);
        conn.setReadTimeout(TIMEOUT * 3);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        conn.setRequestProperty("Content-Length", String.valueOf(iStreamLen));

        if (bIsStop) {
            lastErrCode = HTTP_CANCELED;
            return false;
        }

        // 判斷是否為 WiFi
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        boolean bWifiEnable = (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED);

        ds = new DataOutputStream(conn.getOutputStream());
        int len = 0;
        int postLen = 0;
        int nMaxProgress = bWifiEnable ? 80 : 40;

        // 若 bIsStop 為 true,寫入伺服器的迴圈會立即中止
        while (!bIsStop && ((len = dataStream.read(tmpBuf2)) != -1)) {
            ds.write(tmpBuf2, 0, len);
            ds.flush();

            // 使用 GPRS 時稍微等待,讓進度條更平滑
            if (!bWifiEnable) {
                Thread.sleep(30);
            }

            postLen += len;
            if (mHandler != null) {
                Message msg = new Message();
                msg.what = POST_PROGRESS_NOTIFY;
                msg.arg1 = (postLen * nMaxProgress) / iStreamLen;
                mHandler.sendMessage(msg);
            }
        }

        if (bIsStop) {
            lastErrCode = HTTP_CANCELED;
            return false;
        }
        ds.flush();

        // 非 WiFi 環境下,用剩下的比例模擬後段進度
        if (!bWifiEnable) {
            postLen = 0;
            while (postLen < iStreamLen) {
                Thread.sleep(30);
                postLen += tmpBuf2.length;
                if (mHandler != null) {
                    Message msg = new Message();
                    msg.what = POST_PROGRESS_NOTIFY;
                    msg.arg1 = (postLen * 35) / iStreamLen + 50;
                    mHandler.sendMessage(msg);
                }
            }
        }

        // 等待伺服器回應
        InputStream is = conn.getInputStream();
        int ch;
        StringBuffer res = new StringBuffer();
        while ((ch = is.read()) != -1) {
            res.append((char) ch);
        }

        if (mHandler != null) {
            Message msg = new Message();
            msg.what = POST_PROGRESS_NOTIFY;
            msg.arg1 = 90;
            mHandler.sendMessage(msg);
        }
        return true;

    } catch (Exception ex) {
        Log.e("HttpUtil", "post", ex);
        if (bIsStop) {
            lastErrCode = HTTP_CANCELED;
        } else {
            lastErrCode = HTTP_EXCEPTION;
        }
        return false;

    } finally {
        try {
            outData = null;
            if (input != null) {
                input.close();
                input = null;
            }
            try {
                ds.close();
                ds = null;
            } catch (Exception e) {
                // ignore
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            if (byteOutStream != null) {
                byteOutStream.close();
                byteOutStream = null;
            }
            if (bIsStop) {
                // 中止完成後通知 cancel 方法
                synchronized (objAbort) {
                    objAbort.notify();
                }
            }
            if (mHandler != null) {
                Message msg = new Message();
                msg.what = POST_PROGRESS_NOTIFY;
                msg.arg1 = 100;
                mHandler.sendMessage(msg);
            }
        } catch (Exception ex) {
            Log.e("HttpUtil", "post finally", ex);
        }
    }
}

四、如何優雅地中止

使用者按下取消鍵時呼叫 cancel()。這裡的關鍵是:wait 必須等到 postWithoutResponse 走到 finally 區塊、真正釋放連線之後,才能讓 cancel 返回。

public synchronized void cancel() {
    try {
        // 使用者點擊 cancel,設定旗標
        bIsStop = true;
        if (connection != null) {
            connection.disconnect();
            connection = null;
        }
        synchronized (objAbort) {
            // 只有 postWithoutResponse 執行到 finally 才會通知,
            // 這個函式才能順利返回
            objAbort.wait(50);
        }
    } catch (Exception ex) {
        Log.v("HttpUtil", "canel", ex);
    }
}

private HttpURLConnection getConnection(Context context, URL url) throws Exception {
    String[] apnInfo = null;
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int wifiState = wifiManager.getWifiState();
    HttpURLConnection conn = null;
    conn = (HttpURLConnection) url.openConnection(); // 取得 HTTP 連線
    return conn;
}

完整程式碼可見:https://download.csdn.net/detail/baidu_nod/7735511

小結一下這套做法的三個要點:進度靠 Handler 跨執行緒回傳、中止靠旗標即時中斷寫入迴圈、收尾靠 wait/notify 確保資源被正確釋放。三者缺一,都會出現進度條卡住或連線洩漏的問題。

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