基于Android下载并解压Zip文件,更新UI简单帮助类

类似于:http://blog.csdn.net/jarlen/article/details/44794031

下载文件:

/**
     * 下载文件
     * 
     * @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下,并通知我一下,谢谢

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。