編輯:關於 Android 程式設計
這次要拆解一個多執行緒下載的完整範例。效果是:點擊「下載」開始抓檔並即時顯示進度,完成後按鈕變成「安裝」,點下去跳安裝提示。與其從頭順著寫,不如倒過來看——先問「為什麼需要線程池」,再一路推到最底層的位元組寫檔。
想一想 360、百度手機助手這類下載工具,為什麼能同時抓好幾個 App?因為下載本質上是多執行緒的。既然要開多條線,就需要一個統一管理它們的工具,而這個工具的核心就是 ThreadPoolExecutor。
ThreadPoolExecutor threadpool = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
execute(new Runnable()) 送進來的工作會先排在這裡。構造時若 corePoolSize < 0、keepAliveTime < 0、maximumPoolSize ≤ 0 或 maximumPoolSize < corePoolSize,都會拋 IllegalArgumentException。
實務上不會只有一個線程池。耗時的網路請求如果和本地 IO 排在同一條隊列,短任務會被拖死。因此常見做法是依任務型別拆成好幾池:
public class ThreadManager {
public static final String DEFAULT_SINGLE_POOL_NAME = "DEFAULT_SINGLE_POOL_NAME";
private static ThreadPoolProxy mLongPool; // 長耗時,通常給網路
private static ThreadPoolProxy mShortPool; // 短耗時,通常給本地 IO / SQL
private static ThreadPoolProxy mDownloadPool; // 下載專用
private static Map<String, ThreadPoolProxy> mMap = new HashMap<>();
public static ThreadPoolProxy getDownloadPool() {
synchronized (mDownloadLock) {
if (mDownloadPool == null) {
mDownloadPool = new ThreadPoolProxy(3, 3, 5L);
}
return mDownloadPool;
}
}
public static ThreadPoolProxy getLongPool() { /* 5, 5, 5L */ }
public static ThreadPoolProxy getShortPool() { /* 2, 2, 5L */ }
/** 單線程池:所有任務依加入順序執行,省去同步開銷 */
public static ThreadPoolProxy getSinglePool() {
return getSinglePool(DEFAULT_SINGLE_POOL_NAME);
}
public static ThreadPoolProxy getSinglePool(String name) {
synchronized (mSingleLock) {
ThreadPoolProxy singlePool = mMap.get(name);
if (singlePool == null) {
singlePool = new ThreadPoolProxy(1, 1, 5L);
mMap.put(name, singlePool);
}
return singlePool;
}
}
public static class ThreadPoolProxy {
private ThreadPoolExecutor mPool;
private final int mCorePoolSize, mMaximumPoolSize;
private final long mKeepAliveTime;
private ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
mCorePoolSize = corePoolSize;
mMaximumPoolSize = maximumPoolSize;
mKeepAliveTime = keepAliveTime;
}
/** 執行任務;若線程池已關閉則重建一個 */
public synchronized void execute(Runnable run) {
if (run == null) return;
if (mPool == null || mPool.isShutdown()) {
mPool = new ThreadPoolExecutor(mCorePoolSize, mMaximumPoolSize,
mKeepAliveTime, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
Executors.defaultThreadFactory(), new AbortPolicy());
}
mPool.execute(run);
}
/** 從隊列中移除尚未執行的任務 */
public synchronized void cancel(Runnable run) {
if (mPool != null && !mPool.isShutdown()) {
mPool.getQueue().remove(run);
}
}
public synchronized boolean contains(Runnable run) {
return mPool != null && !mPool.isShutdown() && mPool.getQueue().contains(run);
}
/** 立即關閉,正在執行的任務會被中斷 */
public void stop() {
if (mPool != null && !mPool.isShutdown()) mPool.shutdownNow();
}
}
}
這個工具類負責三件事:建立線程池、取消池中的任務、查詢池中是否含某任務。
有了池子,下載任務只要實作 Runnable 再交給 ThreadManager.getDownloadPool().execute() 即可。核心邏輯其實非常朴素:從 URL 拿到輸入流,一塊一塊寫進本地檔案。
fos = new FileOutputStream(file, true);
int count = -1;
byte[] buffer = new byte[1024];
while (((count = stream.read(buffer)) != -1)
&& info.getDownloadState() == STATE_DOWNLOADING) {
fos.write(buffer, 0, count);
fos.flush();
info.setCurrentSize(info.getCurrentSize() + count);
notifyDownloadProgressed(info); // 刷新進度
}
這段迴圈有兩個細節值得注意。第一,每次讀完都要檢查狀態是否仍是「下載中」,一旦變成暫停就立刻跳出,這正是暫停能即時生效的原因。第二,每寫入一次就累加 currentSize 並發出通知,UI 才能呈現流暢的進度。
按鈕上到底顯示「下載」「暫停」還是百分比,取決於兩個回呼:notifyDownloadProgressed(info) 與 notifyDownloadStateChanged(info)。它們本質上就是遍歷一份观察者清單:
public interface DownloadObserver {
void onDownloadStateChanged(DownloadInfo info);
void onDownloadProgressed(DownloadInfo info);
}
public void notifyDownloadStateChanged(DownloadInfo info) {
synchronized (mObservers) {
for (DownloadObserver observer : mObservers) {
observer.onDownloadStateChanged(info);
}
}
}
public void registerObserver(DownloadObserver observer) {
synchronized (mObservers) {
if (!mObservers.contains(observer)) mObservers.add(observer);
}
}
那麼誰來實作這個介面?答案是 adapter。因為每一列的版面都是在 getView() 裡組出來的,所以由 adapter 實作 observer 最順手:
public class RecommendAdapter extends BaseAdapter
implements DownloadManager.DownloadObserver {
@Override
public void onDownloadStateChanged(DownloadInfo info) { refreshHolder(info); }
@Override
public void onDownloadProgressed(DownloadInfo info) { refreshHolder(info); }
private void refreshHolder(final DownloadInfo info) {
for (ViewHolder holder : getDisplayedHolders()) {
if (holder.getData().getId() == info.getId()) {
AppUtil.post(new Runnable() {
@Override public void run() {
holder.refreshState(info.getDownloadState(), info.getProgress());
}
});
}
}
}
}
注意 mDisplayedHolders 這個設計:螢幕上看得見的 ViewHolder 才需要更新,螢幕外的沒必要浪費資源。而 refreshState() 就是單純的 switch 對照表:
switch (mState) {
case DownloadManager.STATE_NONE: button.setText(R.string.app_state_download); break;
case DownloadManager.STATE_PAUSED: button.setText(R.string.app_state_paused); break;
case DownloadManager.STATE_ERROR: button.setText(R.string.app_state_error); break;
case DownloadManager.STATE_WAITING: button.setText(R.string.app_state_waiting); break;
case DownloadManager.STATE_DOWNLOADING:button.setText((int)(mProgress * 100) + "%"); break;
case DownloadManager.STATE_DOWNLOADED: button.setText(R.string.app_state_downloaded);break;
}
別忘了在 MainActivity 呼叫 adapter.startObserver(),否則观察者從未進入清單,通知自然發不出去——這是最容易漏掉的一步。
public synchronized void download(AppInfo appInfo) {
DownloadInfo info = mDownloadMap.get(appInfo.getId());
if (info == null) {
info = DownloadInfo.clone(appInfo);
mDownloadMap.put(appInfo.getId(), info);
}
int state = info.getDownloadState();
if (state == STATE_NONE || state == STATE_PAUSED || state == STATE_ERROR) {
// 先標成 WAITING,因為此時只是排進隊列,還沒真正開始
info.setDownloadState(STATE_WAITING);
notifyDownloadStateChanged(info);
DownloadTask task = new DownloadTask(info);
mTaskMap.put(info.getId(), task);
ThreadManager.getDownloadPool().execute(task);
}
}
public synchronized void pause(AppInfo appInfo) {
stopDownload(appInfo);
DownloadInfo info = mDownloadMap.get(appInfo.getId());
if (info != null) {
info.setDownloadState(STATE_PAUSED);
notifyDownloadStateChanged(info);
}
}
public synchronized void install(AppInfo appInfo) {
stopDownload(appInfo);
DownloadInfo info = mDownloadMap.get(appInfo.getId());
if (info != null) {
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setDataAndType(Uri.parse("file://" + info.getPath()),
"application/vnd.android.package-archive");
AppUtil.getContext().startActivity(installIntent);
}
notifyDownloadStateChanged(info);
}
做法一:交給伺服器(真正的斷點續傳)。暫停時記下已下載的位元組數,繼續時帶上 Range 標頭:
httpResult = HttpHelper.download(info.getUrl() + "&range=" + info.getCurrentSize());
伺服器端處理起來也很省事:
String range = req.getParameter("range");
if (range == null) { // 不支援續傳,從頭傳
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count = -1;
while ((count = stream.read(buffer)) != -1) {
out.write(buffer, 0, count);
out.flush();
}
} else { // 跳過前面已傳的位元組
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(Long.valueOf(range));
byte[] buffer = new byte[1024];
int count = -1;
while ((count = raf.read(buffer)) != -1) {
out.write(buffer, 0, count);
out.flush();
}
}
做法二:用戶端自行跳過。這個範例採的是這種,但要知道它的限制:Java 的 InputStream.skip() 並不保證跳過你要的數量,往往只跳過一部分,因此必須自己撰寫迴圈反覆補足。更麻煩的是效能——若檔案 20MB、已下載 15MB,續傳時要把前 15MB 全部讀過丟掉,時間成本極高。
private long skipBytesFromStream(InputStream inputStream, long n) {
long remaining = n;
byte[] skipBuffer = new byte[10000];
while (remaining > 0) {
int nr;
try {
inputStream.skip(10000);
nr = inputStream.read(skipBuffer, 0, (int) Math.min(10000, remaining));
} catch (IOException e) { break; }
if (nr < 0) break;
remaining -= nr;
}
return n - remaining;
}
結論很清楚:這種方式只適合教學與小檔案。線上環境要下載大檔,請務必走伺服器端 Range 支援。
自定義 ListView 實作下拉刷新:兩個檔案搞定流暢動畫
先看效果: 現在的 App 幾乎都少不了下拉刷新,需求多、開源方案自然也多。但真正要用起來卻常常不順:PullToRefreshView 這類庫若把源碼整包搬進專案太繁
Android 中 ListView setOnItemClickListener 點擊無效的原因分析
前言 最近做專案的過程中,使用 ListView 時遇到了設定 item 監聽事件卻不觸發 onItemClick 回呼的問題。我的情況是 item 裡有一個 Butto
Android 動畫系列:動手打造自訂補間動畫與 3D 旋轉效果
從基本補間動畫到自訂動畫Android 的補間動畫由 Animation 類作為抽象基礎,系統已內建縮放、平移、透明度與旋轉等常見形式。但當需求變成三維翻轉、透視移動或更
Android:在 SurfaceView 上繪製圖形
為了在 SurfaceView 上畫圖,我們定義一個 MySurfaceView 類別,該類別繼承 SurfaceView 並實作 SurfaceHolder.Callb