«

Android学习 - Android断点续传核心代码

时间:2024-3-2 16:58     作者:韩俊     分类: Android


在网络应用特别是游戏中很多地方使用了下载的技术,下载过程中很有可能因为各种问题而是下载中断,如果重新下载会很吃力,当然如果你下载的东东很小那就另说了。断电续传就是中断后继续传送数据,关键代码如下:

/**
 * 断点续传
 *
 * @param url
 */
private void duanDianXuChuan(final String url) {
    try {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                getRemoteFile(url);
            }
        };
        new Thread(r).start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 下载远端文件
 *
 * @param urlString
 */
private void getRemoteFile(String urlString) {
    try {
        File file;
        if (mCurSize == 0) {
            file = File.createTempFile(fileNa, fileEx);
            currentTempFilePath = file.getAbsolutePath();
            Log.e("andy", file.getName() + " has exists.");
        } else {
            file = new File(currentTempFilePath);
            FileInputStream fis = new FileInputStream(file);
            mCurSize = fis.available();
            Log.e("andy", file.getName() + " has " + mCurSize + " bytes.");
        }
        URL url = new URL(urlString);
        HttpURLConnection httpConnection = (HttpURLConnection) url
                .openConnection();
        httpConnection.setRequestProperty("User-Agent", "NetFox");
        String sProperty = "bytes=" + mCurSize + "-";
        httpConnection.setRequestProperty("RANGE", sProperty);
        InputStream is = httpConnection.getInputStream();
        Log.e("andy", "mTempFileName = " + mTempFileName);
        /* 将文件写入暂存盘 */
        FileOutputStream fos = new FileOutputStream(file, true);
        byte buf[] = new byte[512];
        do {
            int numread = is.read(buf);
            if (numread <= 0) {
                mHandler.sendEmptyMessageDelayed(this.DOWNLOAD_FINISH, 0);
                break;
            }
            mCurSize += numread;
            mHandler.sendEmptyMessageDelayed(this.UPDATE_DOWNLOAD_PROGRESS,
                    0);
            Log.e("andy", "current size = " + mCurSize);
            fos.write(buf, 0, numread);
        } while (mContinue);
        /* 打开文件进行安装 */
        if (mCurSize == mSize) {
            mCurSize = 0;
            openFile(file);
        }
        try {
            is.close();
        } catch (Exception ex) {
            Log.e("andy", "error: " + ex.getMessage(), ex);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 获得文件长度
 *
 * @param urlString
 * @return
 */
public long getFileSize(String urlString) {
    int nFileLength = -1;
    try {
        URL url = new URL(urlString);
        HttpURLConnection httpConnection = (HttpURLConnection) url
                .openConnection();
        httpConnection.setRequestProperty("User-Agent", "NetFox");
        int responseCode = httpConnection.getResponseCode();
        if (responseCode >= 400) {
            return -2; // -2 represent access is error
        }
        String sHeader;
        for (int i = 1;; i++) {
            sHeader = httpConnection.getHeaderFieldKey(i);
            if (sHeader != null) {
                if (sHeader.equals("content-length")) {
                    nFileLength = Integer.parseInt(httpConnection
                            .getHeaderField(sHeader));
                    break;
                }
            } else
                break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return nFileLength;
}

/**
 * 计算百分比
 *
 * @param p1
 * @param p2
 * @return
 */
public static String percent(double p1, double p2) {
    String str;
    double p3 = p1 / p2;
    NumberFormat nf = NumberFormat.getPercentInstance();
    nf.setMinimumFractionDigits(2);
    str = nf.format(p3);
    Log.e("andy", "percentage = " + str);
    return str;
}

标签: android

热门推荐