19
七
断点续传核心代码
/**
* 断点续传
* @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;
}