在线程中实现
public void run() {
super.run();
try {
URL url = new URL(str);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
max=urlConnection.getContentLength();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File file = new File(path);
if(file.exists()){
start= (int) file.length();
}
Log.d("ytx", "start"+start+"end"+max);
try {
URL url = new URL(str);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Range","bytes="+start+"-"+max);
urlConnection.connect();
if(urlConnection.getResponseCode()==206){
Log.d("ytx", "run: 第二次");
InputStream inputStream = urlConnection.getInputStream();
RandomAccessFile randomAccessFile= new RandomAccessFile(path,"rw");
randomAccessFile.seek(start);
byte[] bytes=new byte[1024];
int len=0;
int count=start;
while((len=inputStream.read(bytes))!=-1){
randomAccessFile.write(bytes,0,len);
count+=len;
Message obtain = Message.obtain();
obtain.what=103;
obtain.obj=count*100/max;
handler.sendMessage(obtain);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}