2014-09-30 14 views

risposta

22

La risposta di Oops era ovvia. Mi dispiace per la domanda stupida. Basta leggere InputStream come al solito.

private class AsyncDownloader extends AsyncTask<Void, Long, Boolean> { 
    private final String URL = "file_url"; 

    @Override 
    protected Boolean doInBackground(Void... params) { 
     OkHttpClient httpClient = new OkHttpClient(); 
     Call call = httpClient.newCall(new Request.Builder().url(URL).get().build()); 
     try { 
      Response response = call.execute(); 
      if (response.code() == 200) { 
       InputStream inputStream = null; 
       try { 
        inputStream = response.body().byteStream(); 
        byte[] buff = new byte[1024 * 4]; 
        long downloaded = 0; 
        long target = response.body().contentLength(); 

        publishProgress(0L, target); 
        while (true) { 
         int readed = inputStream.read(buff); 
         if(readed == -1){ 
          break; 
         } 
         //write buff 
         downloaded += readed; 
         publishProgress(downloaded, target); 
         if (isCancelled()) { 
          return false; 
         } 
        } 
        return downloaded == target; 
       } catch (IOException ignore) { 
        return false; 
       } finally { 
        if (inputStream != null) { 
         inputStream.close(); 
        } 
       } 
      } else { 
       return false; 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return false; 
     } 
    } 

    @Override 
    protected void onProgressUpdate(Long... values) { 
     progressBar.setMax(values[1].intValue()); 
     progressBar.setProgress(values[0].intValue()); 

     textViewProgress.setText(String.format("%d/%d", values[0], values[1])); 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
     textViewStatus.setText(result ? "Downloaded" : "Failed"); 
    } 
} 
+3

non c'è un modo più elegante per fare questo ? Come okHttpClient.newCall (richiesta) .notifyProgress (callback) ... o qualcosa del genere ... – josketres

+0

Ottima risposta ma ancora una domanda ... Vedo che abbiamo un inputstream ... Per passare ad un file facciamo dover ricominciare di nuovo l'intero stream e convertirlo in un file? Puoi mostrare come puoi effettivamente ottenere l'oggetto File che è stato scaricato? –

+0

@MarcusGabilheri stai parlando di questo? http://stackoverflow.com/a/10857407/1979290 –

0

ogni volta nel ciclo while, si pubblica il progress.So è come essere bloccato