Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 加密 ZIP 解壓實戰:用 zip4j 加上即時進度條

Java 自帶的 zip 套件雖然能處理普通壓縮檔,卻對「有密碼保護」的壓縮檔束手無策。想解決這個問題,zip4j 是目前最省力的選擇。本文在 zip4j 的基礎上,示範如何把解壓過程丟到背景執行緒,並透過 Handler 把百分比進度回送到 UI,讓使用者看得到解壓走到哪裡。

一、帶密碼解壓並回報進度

下面的 Zip4jSp.Unzip 方法同時接受壓縮檔、解壓目標目錄、密碼、字元集、Handler 以及「是否刪除原檔」等參數,解壓在子執行緒中進行,進度則由另一條執行緒定時取樣後回傳。

Zip4jSp.java

/**
  * unzip file to dest dir with password in thread.
  *
  * @param zipFile
  * @param dest
  * @param passwd
  * @param charset
  *            null or empty is utf-8
  * @param Handler
  *            handler in thread
  * @param isDeleteZipFile
  *            true:delete zip file.false:not.
  * @throws ZipException
  */
 public static void Unzip(final File zipFile, String dest, String passwd,
   String charset, final Handler handler, final boolean isDeleteZipFile)
   throws ZipException {
  ZipFile zFile = new ZipFile(zipFile);
  if (TextUtils.isEmpty(charset)) {
   charset = "UTF-8";
  }
  zFile.setFileNameCharset(charset);
  if (!zFile.isValidZipFile()) {
   throw new ZipException(
     "Compressed files are not illegal, may be damaged.");
  }
  File destDir = new File(dest); // Unzip directory
  if (destDir.isDirectory() && !destDir.exists()) {
   destDir.mkdir();
  }
  if (zFile.isEncrypted()) {
   zFile.setPassword(passwd.toCharArray());
  }

  final ProgressMonitor progressMonitor = zFile.getProgressMonitor();

  Thread progressThread = new Thread(new Runnable() {

   @Override
   public void run() {
    Bundle bundle = null;
    Message msg = null;
    try {
     int percentDone = 0;
     if (handler == null) {
      return;
     }
     handler.sendEmptyMessage(CompressStatus.START);
     while (true) {
      Thread.sleep(1000);
      percentDone = progressMonitor.getPercentDone();
      bundle = new Bundle();
      bundle.putInt(CompressKeys.PERCENT, percentDone);
      msg = new Message();
      msg.what = CompressStatus.HANDLING;
      msg.setData(bundle);
      handler.sendMessage(msg);
      if (percentDone >= 100) {
       break;
      }
     }
     handler.sendEmptyMessage(CompressStatus.COMPLETED);
    } catch (InterruptedException e) {
     bundle = new Bundle();
     bundle.putString(CompressKeys.ERROR, e.getMessage());
     msg = new Message();
     msg.what = CompressStatus.ERROR;
     msg.setData(bundle);
     handler.sendMessage(msg);
     e.printStackTrace();
    }
    finally
    {
     if(isDeleteZipFile)
     {
      zipFile.deleteOnExit();
     }
    }
   }
  });

  progressThread.start();
  zFile.setRunInThread(true);
  zFile.extractAll(dest);
 }

二、狀態與訊息鍵值

CompressKeys.java

package com.sparkle.compress;

public class CompressKeys {
 public final static String PERCENT="PERCENT";
 public final static String ERROR="ERROR";
}

CompressStatus.java

package com.sparkle.compress;

public class CompressStatus {
 public final static int START=0;
 public final static int HANDLING=1;
 public final static int COMPLETED=2;
 public final static int ERROR=3;
}

三、在 Activity 中接收進度

MainActivity.java

 private Handler _handler=new Handler(){
  @Override
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case CompressStatus.START:
   {
    setTitle("Start...");
    break;
   }
   case CompressStatus.HANDLING:
   {
    Bundle bundle=msg.getData();
    int percent=bundle.getInt(CompressKeys.PERCENT);
    setTitle(percent+"%");
    break;
   }
   case CompressStatus.ERROR:
   {
    Bundle bundle=msg.getData();
    String error=bundle.getString(CompressKeys.ERROR);
    _info_textView.setText(error);
    break;
   }
   case CompressStatus.COMPLETED:
   {
    setTitle("Completed");
    byte[] data=FileSp.read(tempFilePath);
    try {
     String dataStr=new String(data,"UTF-8");
     _info_textView.setText(dataStr);
    } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
    }
    break;
   }
   default:
    break;
   }
  };
 };

四、五個容易踩到的坑

1. 字元集預設 UTF-8。若壓縮檔內含中文檔名,可依來源系統改為 GBK。

2. 解壓是非同步的。因為呼叫 setRunInThread(true),主執行緒呼叫後會立刻往下執行,後續邏輯不能假設檔案已經解完,必須靠 Handler 的 COMPLETED 訊息收尾。

3. 進度條走獨立執行緒。每 1000 毫秒從 ProgressMonitor 取一次百分比,用 Message 送到 Handler,避免阻塞 UI。

4. 刪除原檔要用 deleteOnExit()。百分比跳到 100 時,資料其實還沒完全落盤,這時若直接 delete(),後續解壓會因為檔案消失而失敗。deleteOnExit() 只在 VM 結束時才刪,App 運作期間 VM 一直在,因此安全;當然,你也可以選擇不刪。

5. Handler 的實作就是上面 MainActivity 的那一段,進度更新標題、完成後讀檔顯示內容。

Copyright © Linux教程網 All Rights Reserved