2017-02-18 15 views
3

例如,我正在从服务器下载一个文件,在连接丢失之间,当时我的下载是30%,一段时间后我有一个连接。现在我想从30%开始下载,而不是从0%开始。如何实现这个asynctask android。如何恢复在asynctask离开的下载android

如果有其他方法,请让我知道。

+0

将您的值存储在[共享首选项](https://developer.android.com/reference/android/content/SharedPreferences.html)中,您的问题将得到解决。 –

回答

1

您需要先确定您实际下载的字节数。我建议您在保存文件时使用不同的名称,以便您可以轻松查看是否有未完成的下载。
首先检查你的文件的状态,看看你已经下载了多少。

private long isIncomplete(){ 
     File from = new File(dir,fileName+"-incomplete"); 
     if(from.exists()){ 
      Log.d("status","download is incomplete, filesize:" + from.length()); 
      return from.length(); 
     } 
     return 0; 
} 

然后创建HTTP请求时,你可以告诉从哪一点服务器为您服务的文件,这样就可以恢复下载。

long downloaded = isIncomplete(); 
urlConnection.setRequestProperty("Range", "bytes="+(downloaded)+"-"); 

请参阅this class我写了几年后才完成实现。

更新:我建议你不要为此使用共享首选项。 SSOT指出您只从一个源获取信息,因此不会从下载的文件读取进度。

0

您可以将目标文件路径存储在sharedpreferences中,并且可以执行以下代码。

HttpURLConnection connection = (HttpURLConnection) url.openConnection();//Opening the url 

    File file=new File(DESTINATION_PATH); 
    if(file.exists()){ //check if file exists 
     downloaded = (int) file.length(); 
     connection.setRequestProperty("Range", "bytes="+(file.length())+"-"); 
    } 
else{ 
    connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); 
} 
connection.setDoInput(true); 
connection.setDoOutput(true); 
pBar.setMax(connection.getContentLength()); 
in = new BufferedInputStream(connection.getInputStream()); 
fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true); 
bout = new BufferedOutputStream(fos, 1024); 
byte[] data = new byte[1024]; 
int x = 0; 
while ((x = in.read(data, 0, 1024)) >= 0) { 
    bout.write(data, 0, x); 
    downloaded += x; 
    pBar.setProgress(downloaded); 
} 
+0

你是否试过这个代码 –

+0

它只是我的应用程序代码的划痕。 – Noorul