編輯:關於 Android 程式設計
本文提供了完整的 Android 程式碼,實現了從客戶端下載 ZIP 檔案並進行解壓的功能。整份程式碼透過 AsyncTask 異步執行,並搭配 ProgressDialog 展示進度,非常實用,有需要的開發者可以直接參考。
下載任務繼承自 AsyncTask,在背景線程中透過 URLConnection 抓取檔案串流,並以自訂的 ProgressReportingOutputStream 即時回報下載進度:
package com.johnny.testzipanddownload;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;
public class DownLoaderTask extends AsyncTask<Void, Integer, Long> {
private final String TAG = "DownLoaderTask";
private URL mUrl;
private File mFile;
private ProgressDialog mDialog;
private int mProgress = 0;
private ProgressReportingOutputStream mOutputStream;
private Context mContext;
public DownLoaderTask(String url, String out, Context context) {
super();
if (context != null) {
mDialog = new ProgressDialog(context);
mContext = context;
} else {
mDialog = null;
}
try {
mUrl = new URL(url);
String fileName = new File(mUrl.getFile()).getName();
mFile = new File(out, fileName);
Log.d(TAG, "out=" + out + ", name=" + fileName + ",mUrl.getFile()=" + mUrl.getFile());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
if (mDialog != null) {
mDialog.setTitle("Downloading...");
mDialog.setMessage(mFile.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
mDialog.show();
}
}
@Override
protected Long doInBackground(Void... params) {
return download();
}
@Override
protected void onProgressUpdate(Integer... values) {
if (mDialog == null)
return;
if (values.length > 1) {
int contentLength = values[1];
if (contentLength == -1) {
mDialog.setIndeterminate(true);
} else {
mDialog.setMax(contentLength);
}
} else {
mDialog.setProgress(values[0].intValue());
}
}
@Override
protected void onPostExecute(Long result) {
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
if (isCancelled())
return;
((MainActivity) mContext).showUnzipDialog();
}
private long download() {
URLConnection connection = null;
int bytesCopied = 0;
try {
connection = mUrl.openConnection();
int length = connection.getContentLength();
if (mFile.exists() && length == mFile.length()) {
Log.d(TAG, "file " + mFile.getName() + " already exits!!");
return 0l;
}
mOutputStream = new ProgressReportingOutputStream(mFile);
publishProgress(0, length);
bytesCopied = copy(connection.getInputStream(), mOutputStream);
if (bytesCopied != length && length != -1) {
Log.e(TAG, "Download incomplete bytesCopied=" + bytesCopied + ", length" + length);
}
mOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytesCopied;
}
private int copy(InputStream input, OutputStream output) {
byte[] buffer = new byte[1024 * 8];
BufferedInputStream in = new BufferedInputStream(input, 1024 * 8);
BufferedOutputStream out = new BufferedOutputStream(output, 1024 * 8);
int count = 0, n = 0;
try {
while ((n = in.read(buffer, 0, 1024 * 8)) != -1) {
out.write(buffer, 0, n);
count += n;
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return count;
}
private final class ProgressReportingOutputStream extends FileOutputStream {
public ProgressReportingOutputStream(File file) throws FileNotFoundException {
super(file);
}
@Override
public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException {
super.write(buffer, byteOffset, byteCount);
mProgress += byteCount;
publishProgress(mProgress);
}
}
}
下載完成後,接著透過 ZipExtractorTask 進行解壓。它會先計算檔案的總大小作為進度條上限,再逐一走訪每個 ZipEntry,把內容寫入目標目錄:
package com.johnny.testzipanddownload;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;
public class ZipExtractorTask extends AsyncTask<Void, Integer, Long> {
private final String TAG = "ZipExtractorTask";
private final File mInput;
private final File mOutput;
private final ProgressDialog mDialog;
private int mProgress = 0;
private final Context mContext;
private boolean mReplaceAll;
public ZipExtractorTask(String in, String out, Context context, boolean replaceAll) {
super();
mInput = new File(in);
mOutput = new File(out);
if (!mOutput.exists()) {
if (!mOutput.mkdirs()) {
Log.e(TAG, "Failed to make directories:" + mOutput.getAbsolutePath());
}
}
if (context != null) {
mDialog = new ProgressDialog(context);
} else {
mDialog = null;
}
mContext = context;
mReplaceAll = replaceAll;
}
@Override
protected Long doInBackground(Void... params) {
return unzip();
}
@Override
protected void onPostExecute(Long result) {
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
if (isCancelled())
return;
}
@Override
protected void onPreExecute() {
if (mDialog != null) {
mDialog.setTitle("Extracting");
mDialog.setMessage(mInput.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
mDialog.show();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
if (mDialog == null)
return;
if (values.length > 1) {
int max = values[1];
mDialog.setMax(max);
} else
mDialog.setProgress(values[0].intValue());
}
private long unzip() {
long extractedSize = 0L;
Enumeration<ZipEntry> entries;
ZipFile zip = null;
try {
zip = new ZipFile(mInput);
long uncompressedSize = getOriginalSize(zip);
publishProgress(0, (int) uncompressedSize);
entries = (Enumeration<ZipEntry>) zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory()) {
continue;
}
File destination = new File(mOutput, entry.getName());
if (!destination.getParentFile().exists()) {
destination.getParentFile().mkdirs();
}
ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
extractedSize += copy(zip.getInputStream(entry), outStream);
outStream.close();
}
} catch (ZipException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return extractedSize;
}
private long getOriginalSize(ZipFile file) {
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) file.entries();
long originalSize = 0l;
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getSize() >= 0) {
originalSize += entry.getSize();
}
}
return originalSize;
}
private int copy(InputStream input, OutputStream output) {
byte[] buffer = new byte[1024 * 8];
BufferedInputStream in = new BufferedInputStream(input, 1024 * 8);
BufferedOutputStream out = new BufferedOutputStream(output, 1024 * 8);
int count = 0, n = 0;
try {
while ((n = in.read(buffer, 0, 1024 * 8)) != -1) {
out.write(buffer, 0, n);
count += n;
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return count;
}
private final class ProgressReportingOutputStream extends FileOutputStream {
public ProgressReportingOutputStream(File file) throws FileNotFoundException {
super(file);
}
@Override
public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException {
super.write(buffer, byteOffset, byteCount);
mProgress += byteCount;
publishProgress(mProgress);
}
}
}
最後在 MainActivity 中透過對話框串起下載與解壓流程:先詢問是否下載,下載完成後再詢問是否解壓,讓使用者清楚掌握每一步的進度:
package com.johnny.testzipanddownload;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Environment.getExternalStorageDirectory()=" + Environment.getExternalStorageDirectory());
Log.d(TAG, "getCacheDir().getAbsolutePath()=" + getCacheDir().getAbsolutePath());
showDownLoadDialog();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void showDownLoadDialog() {
new AlertDialog.Builder(this).setTitle("確認")
.setMessage("是否下載?")
.setPositiveButton("是", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doDownLoadWork();
}
})
.setNegativeButton("否", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
public void showUnzipDialog() {
new AlertDialog.Builder(this).setTitle("確認")
.setMessage("是否解壓?")
.setPositiveButton("是", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doZipExtractorWork();
}
})
.setNegativeButton("否", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
public void doZipExtractorWork() {
ZipExtractorTask task = new ZipExtractorTask("/storage/emulated/legacy/testzip.zip", "/storage/emulated/legacy/", this, true);
task.execute();
}
private void doDownLoadWork() {
DownLoaderTask task = new DownLoaderTask("https://192.168.9.155/johnny/testzip.zip", "/storage/emulated/legacy/", this);
task.execute();
}
}
以上就是 Android 實現 ZIP 檔案下載與解壓功能的完整程式碼,希望對你有所幫助。透過 AsyncTask 異步處理與 ProgressDialog 進度展示,用戶既能流暢地進行下載解壓,也能清楚看到即時進度。
Android 6.0 權限管理實作:targetSdkVersion ≥ 23 該做的事
當 App 跑在 Android 6.0 以上的手機,且 targetSdkVersion >= 23 時,使用較敏感的權限就必須先取得使用者同意——讀寫 SD 卡
Android 音樂播放器:MediaPlayer、SeekBar 與電話攔截
音樂播放器可整合 MediaPlayer、SeekBar、ListView、廣播接收者與電話狀態監聽。主要功能支援播放、暫停、上下一首、拖動進度、列表排序,並在來電時暫停
Android 入門:TableLayout 三個關鍵欄位屬性詳解(上)
TableLayout 與 TableRow 是一組搭配使用的佈局:TableLayout 置底,TableRow 疊在它上面,而 Button、TextView 等控件
Android 實作可瀏覽與搜尋的聯絡人清單
本文說明如何打造一個「可搜尋的聯絡人清單」Android 應用。使用者既能用導航按鈕逐筆瀏覽所有已儲存的聯絡人,也能依姓名搜尋特定聯絡人,若該筆資料有照片,還會一併顯示。