3
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.os.AsyncTask; 
import android.util.Log; 

public class IssueDownload extends AsyncTask<IRPack, Void, IRPack> { 
    public static final String TAG = "IssueDownload"; 
    public String path = null; 
    public IRIssue issue = null; 

    @Override 
    protected IRPack doInBackground(IRPack... parms) { 
     InputStream input = null; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     issue = Broker.model.issueDataStore.getIRIssue(parms[0].pubKey); 

     try {  
      File downloadFile = new File(IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey) + "/" + parms[0].currPage + ".zip"); 

      if (!downloadFile.exists()) { 
       path = IRConstant.downloadFile(issue.year, issue.month, issue.day, issue.pubKey, "content", "" 
         + parms[0].currPage); 
       URL url = new URL(path); 

       Log.d (TAG,"input: " + path); 

       connection = (HttpURLConnection) url.openConnection(); 
       connection.connect(); 

       if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) 
        return null; 
       // return "Server returned HTTP " + connection.getResponseCode() 
       // + " " + connection.getResponseMessage(); 

       // download the file 
       input = connection.getInputStream(); 
       output = new FileOutputStream(IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey) + "/" + parms[0].currPage + ".zip"); 

       Log.d (TAG,"output: " + output); 

       byte data[] = new byte[1024]; 
       int count; 
       while ((count = input.read(data)) != -1) { 
        output.write(data, 0, count); 
       } 
      } 
     } catch (Exception e) { 
      // return e.toString(); 
      return null; 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 

     } 
     return parms[0]; 
    } 

    @Override 
    protected void onPostExecute(IRPack pack) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(pack); 
     pack.downloadPackComplete(); // Unzip completed pack 
    } 
} 

В настоящее время я использую этот класс загрузки, проблема в том, что когда я потерял соединение, он просто терпит неудачу и выходит из приложений, пожалуйста, есть ли способ включить попытку и ошибку: повторите попытку, если не удалось, если соединение не будет успешным после повторной попытки 2 раза, затем сделайте тост. СпасибоАсинхронный загрузчик задач не удастся, если соединение потеряно

ответ

0

u сделает вашу собственную логику ударить 2 раза, чтобы загрузить файл, если ваш файл не загружен, потому что когда сеть отключится, загрузка будет остановлена.

1

Первое, что нужно сделать, это проверить связь перед тем, как сделать запрос.

ConnectivityManager connMgr = (ConnectivityManager) 
     getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     // fetch data 
    } else { 
     // display error 
    } 

Второе:

private String downloadUrl(String myurl) throws IOException { 
    InputStream is = null; 
    // Only display the first 500 characters of the retrieved 
    // web page content. 
    int len = 500; 

    try { 
     URL url = new URL(myurl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(10000 /* milliseconds */); 
     conn.setConnectTimeout(15000 /* milliseconds */); 
     conn.setRequestMethod("GET"); 
     conn.setDoInput(true); 
     // Starts the query 
     conn.connect(); 
     int response = conn.getResponseCode(); 
     Log.d(DEBUG_TAG, "The response is: " + response); 
     is = conn.getInputStream(); 

     // Convert the InputStream into a string 
     String contentAsString = readIt(is, len); 
     return contentAsString; 

    // Makes sure that the InputStream is closed after the app is 
    // finished using it. 
    } finally { 
     if (is != null) { 
      is.close(); 
     } 
    } 
} 

сделать часть вашего кода бросить IOException, как показано выше

+0

Спасибо, я с помощью попытке поймать, чтобы сделать предупреждение здравицы, однако, как я могу справиться если пользователь снова подключится? thanks – user782104

+0

Вы можете настроить широковещательный приемник для получения события подключений или вручную написать код для ping-сервера внутри задачи таймера и выполнить свой код там. –

Смежные вопросы