Android断点续传实现

来源:互联网 发布:数据库完整性有哪些 编辑:程序博客网 时间:2024/05/16 11:45
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(); } } 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(); } } 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; } 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; } 


转自:http://blog.sina.com.cn/s/blog_9996c67e01018uq7.html 

原创粉丝点击