Android Open Source - EnterpriseShow File Downloader






From Project

Back to project page EnterpriseShow.

License

The source code is released under:

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a co...

If you think the Android project EnterpriseShow listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.ruixinyuan.producttrainingfinal.utils.download;
/*  ww w .  ja  v a2 s .  co  m*/
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.widget.Toast;

/*
 *@user vicentliu
 *@time 2013-6-19????10:28:28
 *@package com.ruixinyuan.producttrainingfinal.utils.download
 */
public class FileDownloader {
    private Context mContext;
    private FileService fileService;
    //???????
    private int downloadSize = 0;
    //??????
    private int fileSize = 0;
    //???
    private DownloadThread[] threads;
    //???????
    private File saveFile;
    //????????????
    private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();
    //????????????
    private int block;
    //????
    private String downloadUrl;

    /**
     * ???????
     * @return
     */
    public int getThreadSize() {
        return threads.length;
    }

    /**
     * ?????????
     * @return
     */
    public int getFileSize() {
        return fileSize;
    }
    /**
     * ????????
     * @param size
     */
    protected synchronized void append(int size) {
        downloadSize += size;
    }
    /**
     * ????????????????
     * @param threadId
     * @param pos
     */
    protected synchronized void update(int threadId, int pos) {
        this.data.put(threadId, pos);
        this.fileService.update(this.downloadUrl, this.data);
    }
    /**
     * ???????
     * @param context
     * @param downloadUrl
     * @param fileSaveDir
     * @param threadNum
     */
    public FileDownloader(Context context,String downloadUrl,File fileSaveDir,int threadNum){
        try {
            this.mContext = context;
            this.downloadUrl = downloadUrl;
            this.fileService = new FileService(mContext);
            URL url = new URL(this.downloadUrl);
            if (!fileSaveDir.exists())
                fileSaveDir.mkdirs();
            this.threads = new DownloadThread[threadNum];

            try {
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept",
                        "image/gif, image/jpeg, image/pjpeg,image/pjpeg," +
                        " application/x-shockwave-flash, application/xaml+xml," +
                        " application/vnd.ms-xpsdocument, application/x-ms-xbap," +
                        " application/x-ms-application, application/vnd.ms-excel," +
                        " application/vnd.ms-powerpoint, application/msword newValue");
                conn.setRequestProperty("Accept-Language", "zh-CN");
                conn.setRequestProperty("Referer", downloadUrl);
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0;" +
                                                        " .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30;" +
                                                        " .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.connect();
//                printResponseHeader(conn);

                if (conn.getResponseCode() == 200) {
                    this.fileSize = conn.getContentLength();//????????????????
                    if(this.fileSize <= 0)
                        throw new RuntimeException("Unknown file size");
                    String fileName = getFileName(conn);
                    this.saveFile = new File(fileSaveDir, fileName);
                    //????????
                    Map<Integer, Integer> logData = fileService.getData(downloadUrl);

                    if (logData.size() > 0) { //???????
                        for (Map.Entry<Integer, Integer> entry : logData.entrySet())
                            data.put(entry.getKey(), entry.getValue()); //???????????????????????data?
                    }

                    if (data.size() == threads.length) { //?????????????????
                        for (int i = 0; i < threads.length; i++) {
                            downloadSize += data.get(i+1);
                        }
//                        print("downloaded length" + downloadSize);
                    }
                    //??????????????????
                    this.block = (this.fileSize % this.threads.length) == 0?
                                  this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;
                } else {
                    throw new RuntimeException("server no response");
                }
            } catch (IOException e) {
//                print(e.toString());
                Toast.makeText(mContext, "??????", Toast.LENGTH_LONG).show();
                throw new RuntimeException("don't connection this url");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    /**
     * ?????????
     * @param conn
     * @return
     */
    private String getFileName(HttpURLConnection conn) {
        String fileName = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);
        if (fileName == null || "".equals(fileName.trim())) { //??????????????
            for(int i = 0;;i++){
                String mine = conn.getHeaderField(i);
                if (mine == null)
                    break;
                if ("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())){
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if(m.find()) return m.group(1);
                }
            }
            fileName = UUID.randomUUID() + ".tmp"; //????????????
        }
        return fileName;
    }
    /**
     * ??????
     * @param listener ????????????????????????????????,???????null
     * @return ????????
     * @throws Exception
     */
    public int startDownload(DownloadProgressListener listener) throws Exception {
        try {
            RandomAccessFile randOut = new RandomAccessFile(saveFile, "rw");
            if (this.fileSize > 0)
                randOut.setLength(fileSize);
            randOut.close();
            URL url = new URL(downloadUrl);
            if (data.size() != threads.length) {
                data.clear();
                for (int i = 0;i < threads.length; i++) {
                    data.put(i+1, 0); //????????????????????????0
                }
            }

            for (int i = 0;i < threads.length; i++) { //??????????
                int downLength = data.get(i+1);
                if (downLength < block && downloadSize < fileSize) { //?????????????????????????
                    threads[i] = new DownloadThread(this, url, saveFile, block, data.get(i+1), i+1);
                    threads[i].setPriority(7);
                    threads[i].start();
                } else {
                    threads[i] = null;
                }
            }

            fileService.save(downloadUrl, data);
            boolean notFinish = true; //??????
            while (notFinish) { //?????????????????
                Thread.sleep(900);
                notFinish = false; //?????????????
                for (int i = 0; i < threads.length; i++) {
                    if (threads[i] != null && !threads[i].isFinish()) { //?????????????
                        notFinish = true;
                        if (threads[i].getDownLength() == -1) { //??????,??????
                            threads[i] = new DownloadThread(this, url, saveFile, block, data.get(i+1), i+1);
                            threads[i].setPriority(7);
                            threads[i].start();
                        }
                    }
                }
                if (listener != null)
                    listener.onDownloadSize(downloadSize); //????????????????????
            }
            fileService.delete(downloadUrl);
        } catch (Exception e) {
//            print(e.toString());
            throw new Exception("file download failed");
        }
        return downloadSize;
    }
    
    /**
     * ????http???
     * @param http
     */
//    public static void printResponseHeader(HttpURLConnection http) {
//        Map<String, String> header = getHttpResponseHeader(http);
//        for(Map.Entry<String, String> entry : header.entrySet()) {
//            String key = entry.getKey() != null ? entry.getKey() + ":" : "";
////            print(key + entry.getValue());
//        }
//    }
    /**
     * ????http??????
     * @param http
     * @return
     */
    public static Map<String, String> getHttpResponseHeader(
            HttpURLConnection http) {
        Map<String, String> header = new LinkedHashMap<String, String>();
        for (int i = 0;;i++) {
            String mine = http.getHeaderField(i);
            if (mine == null)
                break;
            header.put(http.getHeaderFieldKey(i), mine);
        }
        return header;
    }
//    private static final String TAG = "FileDownloader";
//    private static void print(String string) {
//        Log.i(TAG, string);
//    }

}




Java Source Code List

com.ruixinyuan.producttrainingfinal.DownloadActivity.java
com.ruixinyuan.producttrainingfinal.GroupActivity.java
com.ruixinyuan.producttrainingfinal.LoginActivity.java
com.ruixinyuan.producttrainingfinal.ProductionDetailActivity.java
com.ruixinyuan.producttrainingfinal.SaleSkillDetailActivity.java
com.ruixinyuan.producttrainingfinal.SplashScreenActivity.java
com.ruixinyuan.producttrainingfinal.TabActivityFour.java
com.ruixinyuan.producttrainingfinal.TabActivityOne.java
com.ruixinyuan.producttrainingfinal.TabActivityThree.java
com.ruixinyuan.producttrainingfinal.TabActivityTwo.java
com.ruixinyuan.producttrainingfinal.adapter.GalleryImgAdapter.java
com.ruixinyuan.producttrainingfinal.adapter.ListViewCommentAdapter.java
com.ruixinyuan.producttrainingfinal.adapter.ListViewProductIntroAdapter.java
com.ruixinyuan.producttrainingfinal.adapter.ListViewQuestionAdapter.java
com.ruixinyuan.producttrainingfinal.adapter.ListViewSaleSkillAdapter.java
com.ruixinyuan.producttrainingfinal.bean.CommentBean.java
com.ruixinyuan.producttrainingfinal.bean.ProductInfoBean.java
com.ruixinyuan.producttrainingfinal.bean.QuestionBean.java
com.ruixinyuan.producttrainingfinal.bean.SaleSkillBean.java
com.ruixinyuan.producttrainingfinal.bean.TabItemBean.java
com.ruixinyuan.producttrainingfinal.bean.UserBean.java
com.ruixinyuan.producttrainingfinal.db.DBConstants.java
com.ruixinyuan.producttrainingfinal.db.DBUtils.java
com.ruixinyuan.producttrainingfinal.db.DownloadDBOpenHelper.java
com.ruixinyuan.producttrainingfinal.db.SQLiteProductHelper.java
com.ruixinyuan.producttrainingfinal.db.SQLiteSalesSkillOpenHelper.java
com.ruixinyuan.producttrainingfinal.db.SQLiteUserHelper.java
com.ruixinyuan.producttrainingfinal.services.MessageService.java
com.ruixinyuan.producttrainingfinal.utils.BitmapUtils.java
com.ruixinyuan.producttrainingfinal.utils.EncryptionAndDecryption.java
com.ruixinyuan.producttrainingfinal.utils.RConstrants.java
com.ruixinyuan.producttrainingfinal.utils.SIMCardInfo.java
com.ruixinyuan.producttrainingfinal.utils.StringUtils.java
com.ruixinyuan.producttrainingfinal.utils.TabHostActivity.java
com.ruixinyuan.producttrainingfinal.utils.TimeUtils.java
com.ruixinyuan.producttrainingfinal.utils.download.DownloadProgressListener.java
com.ruixinyuan.producttrainingfinal.utils.download.DownloadThread.java
com.ruixinyuan.producttrainingfinal.utils.download.FileDownloader.java
com.ruixinyuan.producttrainingfinal.utils.download.FileService.java
com.ruixinyuan.producttrainingfinal.utils.net.APNMatchTools.java
com.ruixinyuan.producttrainingfinal.utils.net.JsonUtils.java
com.ruixinyuan.producttrainingfinal.utils.net.NetUtils.java