Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 基於Android下載並解壓Zip文件,更新UI簡單幫助類

基於Android下載並解壓Zip文件,更新UI簡單幫助類

編輯:關於Android編程

 

下載文件:

/**
     * 下載文件
     * 
     * @param down_url
     * @param output
     * @param tmpDir
     */
    private void download(String down_url, File output, File tmpDir)
    {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File tmp = null;

        int down_step = 1;// 提示step
        int totalSize = 0;
        int downloadCount = 0;// 已經下載好的大小
        int updateCount = 0;// 已經上傳的文件大小

        try
        {
            tmp = File.createTempFile(download, .tmp, tmpDir);

            URL url = new URL(down_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setConnectTimeout(30 * 1000);
            httpURLConnection.setReadTimeout(30 * 1000);
            // 獲取下載文件的size
            totalSize = httpURLConnection.getContentLength();

            inputStream = new URL(down_url).openStream();
            outputStream = new BufferedOutputStream(new FileOutputStream(tmp));

            byte[] buffer = new byte[BUFFER_SIZE];
            int readsize = 0;

            while ((readsize = inputStream.read(buffer)) != -1)
            {
                outputStream.write(buffer, 0, readsize);
                downloadCount += readsize;// 時時獲取下載到的大小
                // 每次增長1%
                if (updateCount == 0
                        || (downloadCount * 100 / totalSize - down_step) >= updateCount)
                {
                    updateCount += down_step;

                    sendMessage(DOWN_UPDATA, updateCount);
                }
            }

            if (httpURLConnection != null)
            {
                httpURLConnection.disconnect();
            }
            tmp.renameTo(output);
            tmp = null;
        } catch (IOException e)
        {
            sendMessage(DOWN_ERROR, 0);
            throw new RuntimeException(e);
        } finally
        {
            try
            {
                if (tmp != null)
                {
                    tmp.delete();
                    tmp = null;
                }
                if (inputStream != null)
                {
                    inputStream.close();
                    inputStream = null;
                }
                if (outputStream != null)
                {
                    outputStream.close();
                    outputStream = null;
                }
            } catch (Exception e2)
            {
                sendMessage(DOWN_ERROR, 0);
            }

            sendMessage(DOWN_FINISH, 0);
        }
    }

解壓Zip文件

public class ZipUnPack {
    private static final int BUFFER_SIZE = 8192;

    private String _zipFile;
    private String _location;
    private byte[] _buffer;

    /**
     * Constructor.
     * 
     * @param zipFile
     *            Fully-qualified path to .zip file
     * @param location
     *            Fully-qualified path to folder where files should be written.
     *            Path must have a trailing slash.
     */
    public ZipUnPack(String zipFile, String location) {
        _zipFile = zipFile;
        _location = location;
        _buffer = new byte[BUFFER_SIZE];
        dirChecker();
    }


    public Boolean unzip() {
        FileInputStream fin = null;
        ZipInputStream zin = null;
        OutputStream fout = null;

        File outputDir = new File(_location);
        File tmp = null;

        Boolean isSucess = true;
        try {
            fin = new FileInputStream(_zipFile);
            zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                Log.d(Decompress, Unzipping  + ze.getName());

                if (ze.isDirectory()) {
                    dirChecker(ze.getName());
                } else {
                    tmp = File.createTempFile(decomp, .tmp, outputDir);
                    fout = new BufferedOutputStream(new FileOutputStream(tmp));
                    copyStream(zin, fout, _buffer, BUFFER_SIZE);
                    zin.closeEntry();
                    fout.close();
                    fout = null;
                    tmp.renameTo(new File(_location + ze.getName()));
                    tmp = null;
                }
            }
            zin.close();
            zin = null;
        } catch (IOException e) {
            isSucess = false;
            throw new RuntimeException(e);
        } finally {
            if (tmp != null) {
                try {
                    tmp.delete();
                } catch (Exception ignore) {

                }
            }
            if (fout != null) {
                try {
                    fout.close();
                } catch (Exception ignore) {
                    ;
                }
            }
            if (zin != null) {
                try {
                    zin.closeEntry();
                } catch (Exception ignore) {
                    ;
                }
            }
            if (fin != null) {
                try {
                    fin.close();
                } catch (Exception ignore) {
                    ;
                }
            }

            isSucess = true;
        }

        return isSucess;
    }

    private void dirChecker(String dir) {
        File f = new File(_location + dir);

        if (!f.isDirectory()) {
            f.mkdirs();
        }
    }


    /**
     * Copy from one stream to another. Throws IOException in the event of error
     * (for example, SD card is full)
     * 
     * @param is
     *            Input stream.
     * @param os
     *            Output stream.
     * @param buffer
     *            Temporary buffer to use for copy.
     * @param bufferSize
     *            Size of temporary buffer, in bytes.
     */
    private void copyStream(InputStream is, OutputStream os,
            byte[] buffer, int bufferSize) throws IOException {
        try {
            for (;;) {
                int count = is.read(buffer, 0, bufferSize);
                if (count == -1) {
                    break;
                }
                os.write(buffer, 0, count);
            }
        } catch (IOException e) {
            throw e;
        }
    }
}

整個幫助類:

public class ZipDownLoadHelper
{

    private static final int BUFFER_SIZE = 1024;

    private static final int DOWN_BEGIN = 0;
    private static final int DOWN_UPDATA = 1;
    private static final int DOWN_FINISH = 2;
    private static final int DOWN_ERROR = 3;
    private static final int UNPACK_BEGIN = 4;
    private static final int UNPACK_END = 5;
    private static final int UNPACK_ERROR = 6;

    private Context mContext;

    private Thread mDownLoadThread;

    private OnZipDownLoadAndUnpackListener mOnZipDownLoadAndUnpackListener;

    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            if (!Thread.currentThread().isInterrupted())
            {
                switch (msg.what)
                {
                    case DOWN_BEGIN :
                        if (mOnZipDownLoadAndUnpackListener != null)
                        {
                            mOnZipDownLoadAndUnpackListener.onDownLoadStart();
                        }

                        break;
                    case DOWN_UPDATA :
                        int factor = msg.arg1;
                        if (mOnZipDownLoadAndUnpackListener != null)
                        {
                            mOnZipDownLoadAndUnpackListener
                                    .onDownLoading(factor);
                        }

                        break;

                    case DOWN_FINISH :
                        if (mOnZipDownLoadAndUnpackListener != null)
                        {
                            mOnZipDownLoadAndUnpackListener.onDownLoadFinish();
                        }

                        break;
                    case DOWN_ERROR :
                        if (mOnZipDownLoadAndUnpackListener != null)
                        {
                            mOnZipDownLoadAndUnpackListener.onDownLoadError();
                        }

                        break;
                    case UNPACK_BEGIN :
                        if (mOnZipDownLoadAndUnpackListener != null)
                        {
                            mOnZipDownLoadAndUnpackListener.onZipUnpackStart();
                        }
                        break;
                    case UNPACK_END :

                        if (mOnZipDownLoadAndUnpackListener != null)
                        {
                            mOnZipDownLoadAndUnpackListener.onZipUnpackFinish();
                        }

                        break;
                    case UNPACK_ERROR:

                        break;

                    default :
                        break;
                }
            }
        };
    };

    public ZipDownLoadHelper(Context context)
    {
        this.mContext = context;
    }

    /**
     * 開啟線程
     * 
     * @param url
     */
    public void startDownLoadAndZip(final String url)
    {
        mDownLoadThread = new Thread()
        {
            @Override
            public void run()
            {
                sendMessage(DOWN_BEGIN, 0);
                // Temp folder for holding asset during download
                File zipDir = ExternalStorage.getSDCacheDir(mContext, tmp);

                // File path to store .zip file before unzipping
                File zipFile = new File(zipDir.getPath() + /temp.zip);

                // Folder to hold unzipped output
                File outputDir = ExternalStorage.getSDCacheDir(mContext,
                        wms);

                try
                {
                    download(url, zipFile, zipDir);
                    unzipFile(zipFile, outputDir);
                } finally
                {
                    zipFile.delete();
                }
            }
        };
        mDownLoadThread.start();
    }

    @SuppressWarnings(deprecation)
    public void destroyThread()
    {
        mDownLoadThread.stop();
    }

    /**
     * 下載文件
     * 
     * @param down_url
     * @param output
     * @param tmpDir
     */
    private void download(String down_url, File output, File tmpDir)
    {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        File tmp = null;

        int down_step = 1;// 提示step
        int totalSize = 0;
        int downloadCount = 0;// 已經下載好的大小
        int updateCount = 0;// 已經上傳的文件大小

        try
        {
            tmp = File.createTempFile(download, .tmp, tmpDir);

            URL url = new URL(down_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setConnectTimeout(30 * 1000);
            httpURLConnection.setReadTimeout(30 * 1000);
            // 獲取下載文件的size
            totalSize = httpURLConnection.getContentLength();

            inputStream = new URL(down_url).openStream();
            outputStream = new BufferedOutputStream(new FileOutputStream(tmp));

            byte[] buffer = new byte[BUFFER_SIZE];
            int readsize = 0;

            while ((readsize = inputStream.read(buffer)) != -1)
            {
                outputStream.write(buffer, 0, readsize);
                downloadCount += readsize;// 時時獲取下載到的大小
                // 每次增長1%
                if (updateCount == 0
                        || (downloadCount * 100 / totalSize - down_step) >= updateCount)
                {
                    updateCount += down_step;

                    sendMessage(DOWN_UPDATA, updateCount);
                }
            }

            if (httpURLConnection != null)
            {
                httpURLConnection.disconnect();
            }
            tmp.renameTo(output);
            tmp = null;
        } catch (IOException e)
        {
            sendMessage(DOWN_ERROR, 0);
            throw new RuntimeException(e);
        } finally
        {
            try
            {
                if (tmp != null)
                {
                    tmp.delete();
                    tmp = null;
                }
                if (inputStream != null)
                {
                    inputStream.close();
                    inputStream = null;
                }
                if (outputStream != null)
                {
                    outputStream.close();
                    outputStream = null;
                }
            } catch (Exception e2)
            {
                sendMessage(DOWN_ERROR, 0);
            }

            sendMessage(DOWN_FINISH, 0);
        }
    }

    private void sendMessage(int flag, int factor)
    {
        Message msg = new Message();
        switch (flag)
        {

            case DOWN_BEGIN :// 開始
            case DOWN_FINISH :// 完成
            case DOWN_ERROR :// 失敗
            case UNPACK_BEGIN :
            case UNPACK_END :
            case UNPACK_ERROR:

                break;
            case DOWN_UPDATA :// 更新進度條
                msg.arg1 = factor;
                break;

            default :
                break;
        }
        msg.what = flag;
        handler.sendMessage(msg);
    }

    /**
     * 解壓文件
     * 
     * @param zipFile
     * @param destination
     */
    private void unzipFile(File zipFile, File destination)
    {
        sendMessage(UNPACK_BEGIN, 0);
        ZipUnPack decomp = new ZipUnPack(zipFile.getPath(),
                destination.getPath() + File.separator);
        Boolean isOk = decomp.unzip();
        if(!isOk)
        {
            sendMessage(UNPACK_ERROR, 0);
        }
        else
        {
            sendMessage(UNPACK_END, 0);
        }

    }

    /**
     * 綁定監聽
     * 
     * @param listener
     */
    public void setOnZipDownLoadAndUnpackListener(
            OnZipDownLoadAndUnpackListener listener)
    {
        this.mOnZipDownLoadAndUnpackListener = listener;
    }

    public interface OnZipDownLoadAndUnpackListener
    {

        /**
         * 下載開始
         */
        public void onDownLoadStart();

        /**
         * 下載更新
         * 
         * @param factor
         */
        public void onDownLoading(int factor);

        /**
         * 下載失敗
         */
        public void onDownLoadError();

        /**
         * 下載完成
         */
        public void onDownLoadFinish();

        /**
         * 解壓開始
         */
        public void onZipUnpackStart();

        /**
         * 解壓失敗
         */
        public void onZipUnpackError();

        /**
         * 解壓完成
         */
        public void onZipUnpackFinish();
    }

}

沒有認真地檢查,可能有bug,使用的伙伴請自己debug下,並通知我一下,謝謝

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved