Retrofit2.1.0深入學(xué)習(xí)@GET【第三章】文件下載

1.建立接口和下載工具類

public class ApkDownloadUtil {    
    interface DownloadInterface{        
    String HOST = "http://p.gdown.baidu.com/";        
    //@Streaming:大文件下載防止數(shù)據(jù)寫入到內(nèi)存中OOM,小圖片可以不用       
    @Streaming       
    @GET        
    Call<ResponseBody> downloadFile(@Url String url); 
   }    
    public static void download(String url, Callback<ResponseBody> callback){        
    DownloadInterface downloadInterface = new Retrofit.Builder().baseUrl(DownloadInterface.HOST).build().create(DownloadInterface.class);  
    downloadInterface.downloadFile(url).enqueue(callback);   
     }
}

2.使用工具類下載,以下載愛奇藝為例

public void download() {    
    String url = "f72c2decfb0ea49d5ef0bb1d20e03f09a4f8ef8df26d18e16bf4c80faf5999972b9ae8fc29b39598f15ab0aa7b65017cc9e26e5a1bcb3ae93188d67b1580e3d4938a81bb93b312d83383c6602f7b777d52651f73c5d0e6346d4a838af1d47fa9971c1fba88f03a5ce139fc1f89dae8cc9fe33323aba5f1ff7640f9f38318115af70106f93f099053ae605477502f2e275000f0b9f5e192f67efad1db0f8505d4";    
    ApkDownloadUtil.download(url, new Callback<ResponseBody>() {        
    @Override        
    public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {            
       if (response.isSuccessful()) {                
        //注意這里要另開線程下載,耗時操作不允許在主線程進(jìn)行                
        new Thread(new Runnable() {                    
        @Override                    
        public void run() {                                   
            boolean writtenToDiskSucess = writeToDisk(response.body());                        
            L.d("文件下載是否成功= " + writtenToDiskSucess);                    
         }                
        }).start();            
      } else { 
               L.d( "服務(wù)器連接失敗");           
      }       
    }        
     @Override        
     public void onFailure(Call<ResponseBody> call, Throwable t) {            
      L.e( "error="+t.getMessage());        
      }    
   });
}

3.把下載的文件寫入到手機(jī)中,并顯示下載進(jìn)度

public Handler mHandler = new Handler(){        
@Override   
 public void handleMessage(Message msg) {        
tvMsg.setText("進(jìn)度:"+msg.arg1+"%");    
}};

private boolean writeToDisk(ResponseBody body) {    
try {        

File fileDir = new File(Environment.getExternalStorageDirectory()+File.separator+"Download");       
 if (!fileDir.exists()){            
fileDir.mkdir();        
}        

File filePath = new File(fileDir.getPath()+File.separator+"愛奇藝.apk");    
    
InputStream inputStream = null;        
OutputStream outputStream = null;      
  
try {            
    byte[] fileReader = new byte[4096];            
    long fileSize = body.contentLength();           
    long fileSizeDownloaded = 0;            
    inputStream = body.byteStream();            
    outputStream = new FileOutputStream(filePath);            
    while (true) {                
    int read = inputStream.read(fileReader);               
     if (read == -1)break;                
    outputStream.write(fileReader, 0, read);                
    fileSizeDownloaded += read;                
    //發(fā)送下載的進(jìn)度                
    int progress = (int) ((float)fileSizeDownloaded/(float)fileSize*100);                
    Message msg = Message.obtain();                
    msg.arg1 = progress;                
    mHandler.sendMessage(msg);            
  }            
    outputStream.flush();            
    return true;        
  } catch (IOException e) {            
        return false;       
   } finally {            
  if (inputStream != null) {
            inputStream.close();            
    }            
  if (outputStream != null) { 
           outputStream.close();           
   }        
  }   
   } catch (IOException e) {          
     return false;    
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容