編輯:關於 Android 程式設計
OkHttp 出自 Square 之手,優點不必多說。但正因為封裝得太「完美」,一旦想插入自己的邏輯,反而會發現無從下手。
場景很典型:產品要求文件上傳與下載,上傳前給提示,上傳中顯示進度,完成後告知結果。用 OkHttp 做簡單的 GET/POST 毫無問題,可一旦要拿進度,官方 API 裡根本沒有入口。
問題並非我們獨有——Stack Overflow 與 GitHub issue 上早有大量討論,其中幾個方案頗有參考價值。為便於復用,筆者把它整理成了一個庫,命名為 CoreProgress。
進度監聽需要用到 OkHttp 底層依賴 Okio 中的 Source 與 Sink。下載對應響應體 ResponseBody,上傳對應請求體 RequestBody,兩邊的思路完全對稱。
public interface ProgressResponseListener {
void onResponseProgress(long bytesRead, long contentLength, boolean done);
}
public interface ProgressRequestListener {
void onRequestProgress(long bytesWritten, long contentLength, boolean done);
}
思路類似裝飾器模式:內部持有原始 ResponseBody,重寫 contentType、contentLength 直接轉發,重點在 source() 方法——返回一個包裝過的 ForwardingSource,在 read 時累加已讀字節並回調。
public class ProgressResponseBody extends ResponseBody {
private final ResponseBody responseBody;
private final ProgressResponseListener progressListener;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody,
ProgressResponseListener progressListener) {
this.responseBody = responseBody;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() throws IOException {
return responseBody.contentLength();
}
@Override
public BufferedSource source() throws IOException {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// 讀完時 bytesRead 返回 -1
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
progressListener.onResponseProgress(
totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}
完全對稱,只是把 Source 換成 Sink、read 換成 write:
public class ProgressRequestBody extends RequestBody {
private final RequestBody requestBody;
private final ProgressRequestListener progressListener;
private BufferedSink bufferedSink;
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
requestBody.writeTo(bufferedSink);
bufferedSink.flush(); // 必須 flush,否則最後一段數據可能丟失
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength(); // 只取一次,避免重複計算
}
bytesWritten += byteCount;
progressListener.onRequestProgress(
bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
}
上傳很簡單:把原始 RequestBody 與監聽器交給輔助類,拿回包裝後的對象即可。下載則麻煩一些——OkHttp 返回的是 Response,需要借助 攔截器 把包裝後的 ResponseBody 塞回去。
public class ProgressHelper {
/** 克隆 OkHttpClient 並加入響應攔截,用於下載進度回調 */
public static OkHttpClient addProgressResponseListener(
OkHttpClient client, final ProgressResponseListener progressListener) {
OkHttpClient clone = client.clone(); // 不影響原實例
clone.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(
originalResponse.body(), progressListener))
.build();
}
});
return clone;
}
/** 包裝請求體,用於上傳進度回調 */
public static ProgressRequestBody addProgressRequestListener(
RequestBody requestBody, ProgressRequestListener progressRequestListener) {
return new ProgressRequestBody(requestBody, progressRequestListener);
}
}
OkHttp 的所有網絡操作都在子線程,而我們最終要更新進度條。因此需要再包一層,把進度數據封裝成實體類,通過 Handler 投遞到主線程。
public class ProgressModel implements Serializable {
private long currentBytes;
private long contentLength;
private boolean done;
// 構造方法與 getter/setter 省略
}
public abstract class UIProgressRequestListener implements ProgressRequestListener {
private static final int REQUEST_UPDATE = 0x01;
private static class UIHandler extends Handler {
// 弱引用,避免內存洩露
private final WeakReference<UIProgressRequestListener>
mUIProgressRequestListenerWeakReference;
public UIHandler(Looper looper, UIProgressRequestListener listener) {
super(looper);
mUIProgressRequestListenerWeakReference = new WeakReference<>(listener);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REQUEST_UPDATE:
UIProgressRequestListener listener =
mUIProgressRequestListenerWeakReference.get();
if (listener != null) {
ProgressModel model = (ProgressModel) msg.obj;
listener.onUIRequestProgress(model.getCurrentBytes(),
model.getContentLength(), model.isDone());
}
break;
default:
super.handleMessage(msg);
break;
}
}
}
private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);
@Override
public void onRequestProgress(long bytesRead, long contentLength, boolean done) {
Message message = Message.obtain();
message.obj = new ProgressModel(bytesRead, contentLength, done);
message.what = REQUEST_UPDATE;
mHandler.sendMessage(message);
}
/** 由業務方實現真正的 UI 更新邏輯 */
public abstract void onUIRequestProgress(long bytesWrite, long contentLength, boolean done);
}
UIProgressResponseListener 的實現與此幾乎一致,只是接口方法換成 onUIResponseProgress。
庫已發佈到中央倉庫:
dependencies {
compile 'cn.edu.zafu:coreprogress:0.0.1'
}
注意:OkHttp 依賴需自行添加,本庫只把它作為編譯時依賴,並未打包進去。
源碼託管在 https://github.com/lizhangqu/CoreProgress ,使用方法一併附上。
布局中放兩個進度條分別對應上傳與下載:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:id="@+id/upload_progress"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload" />
<ProgressBar
android:id="@+id/download_progress"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download" />
</LinearLayout>
private void download() {
// 非 UI 線程回調,不可直接操作控件
final ProgressResponseListener listener = new ProgressResponseListener() {
@Override
public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
if (contentLength != -1) { // 長度未知時返回 -1
Log.e(TAG, (100 * bytesRead) / contentLength + "% done");
}
}
};
// UI 線程回調,可直接更新進度條
final UIProgressResponseListener uiListener = new UIProgressResponseListener() {
@Override
public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
if (contentLength != -1) {
downloadProgress.setProgress((int) ((100 * bytesRead) / contentLength));
}
}
};
Request request = new Request.Builder()
.url("https://121.41.119.107:81/test/1.doc")
.build();
ProgressHelper.addProgressResponseListener(client, uiListener)
.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Request request, IOException e) { }
@Override public void onResponse(Response response) throws IOException { }
});
}
private void upload() {
File file = new File("/sdcard/1.doc"); // 實際場景請替換路徑
final UIProgressRequestListener uiListener = new UIProgressRequestListener() {
@Override
public void onUIRequestProgress(long bytesWrite, long contentLength, boolean done) {
uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
}
};
// 構造類似 web 表單的請求體
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("hello", "android")
.addFormDataPart("photo", file.getName(), RequestBody.create(null, file))
.addPart(Headers.of("Content-Disposition",
"form-data; name=\"another\";filename=\"another.dex\""),
RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
Request request = new Request.Builder()
.url("https://121.41.119.107:81/test/result.php")
.post(ProgressHelper.addProgressRequestListener(requestBody, uiListener))
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Request request, IOException e) { }
@Override public void onResponse(Response response) throws IOException { }
});
}
有兩個細節值得注意:下載時若文件大小未知,contentLength 會始終返回 -1,此時只能依賴 done 判斷是否完成;已知大小時它返回實際值,兩者結合判斷更穩妥。另外,無論進度如何變化,最終結果仍會通過 onResponse 或 onFailure 回調,完成提示等邏輯應放在那裡。
還需合理配置超時,讀寫大文件時若不設置容易拋異常,示例中數值給得比較寬鬆,實戰按需調整:
private void initClient() {
client.setConnectTimeout(1000, TimeUnit.MINUTES);
client.setReadTimeout(1000, TimeUnit.MINUTES);
client.setWriteTimeout(1000, TimeUnit.MINUTES);
}
服務端配合很簡單,用 PHP 打印 POST 參數與文件信息,再把文件存到 file 目錄:
<?php var_dump($_POST); var_dump($_FILES); move_uploaded_file($_FILES["photo"]["tmp_name"], "./file/" . $_FILES["photo"]["name"]); ?>
運行效果:點擊上傳或下載後,進度條持續更新。


深入解析 Android Activity 生命週期
Activity 是 Android 四大元件之一,也是使用者最直接接觸的介面單元。幾乎所有應用程式都需要透過 Activity 與使用者互動,因此理解它的角色與生命週期
Android 實戰:PreferenceActivity 設置頁面詳解
一、寫在前面 開發應用時,總會需要用戶填一些設定,這就是所謂的「應用設置」。 Android 系統本身的設定頁早已讓使用者養成習慣,如果我們的應用也採用類似形式的設置頁,
Android 安全專項測試之反編譯
apktool 反編譯 APK 使用 apktool d <apk 檔案>,預設會生成與 APK 同名的資料夾,裡面存放反編譯後的檔案: localhos
從零開始的 Android 新專案 10:React Native 與 Redux 入門實解
這一篇我們來聊 React Native 與 Redux。不同於那些一上來就整段整段貼翻譯的教學,本文選擇從最小的例子切入:先讓你明白 React Native 到底是什