欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 文件下載三種基本方式

 更新時(shí)間:2017年06月14日 08:34:57   作者:小小情意  
這篇文章主要介紹了Android 文件下載三種基本方式,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下

一、自己封裝URLConnection 連接請(qǐng)求類

 public void downloadFile1() {
  try{
    //下載路徑,如果路徑無(wú)效了,可換成你的下載路徑
    String url = "http://c.qijingonline.com/test.mkv";
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();

    final long startTime = System.currentTimeMillis();
    Log.i("DOWNLOAD","startTime="+startTime);
    //下載函數(shù)
    String filename=url.substring(url.lastIndexOf("/") + 1);
    //獲取文件名
    URL myURL = new URL(url);
    URLConnection conn = myURL.openConnection();
    conn.connect();
    InputStream is = conn.getInputStream();
    int fileSize = conn.getContentLength();//根據(jù)響應(yīng)獲取文件大小
    if (fileSize <= 0) throw new RuntimeException("無(wú)法獲知文件大小 ");
    if (is == null) throw new RuntimeException("stream is null");
    File file1 = new File(path);
    if(!file1.exists()){
      file1.mkdirs();
    }
    //把數(shù)據(jù)存入路徑+文件名
    FileOutputStream fos = new FileOutputStream(path+"/"+filename);
    byte buf[] = new byte[1024];
    int downLoadFileSize = 0;
    do{
      //循環(huán)讀取
      int numread = is.read(buf);
      if (numread == -1)
      {
        break;
      }
      fos.write(buf, 0, numread);
      downLoadFileSize += numread;
      //更新進(jìn)度條
    } while (true);
    Log.i("DOWNLOAD","download success");
    Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
    is.close();
  } catch (Exception ex) {
    Log.e("DOWNLOAD", "error: " + ex.getMessage(), ex);
  }
}

這種方式在Android 剛興起的時(shí)候,很少下載封裝框架,就自己封裝了。雖然一般的文件都能下載,但這種方式缺點(diǎn)很多,不穩(wěn)定或者各種各樣的問(wèn)題會(huì)出現(xiàn)。 

二、Android自定的下載管理(會(huì)在notification 顯示下載的進(jìn)度,同時(shí)可以暫停、重新連接等)

private void downloadFile2(){
  //下載路徑,如果路徑無(wú)效了,可換成你的下載路徑
  String url = "http://c.qijingonline.com/test.mkv";
  //創(chuàng)建下載任務(wù),downloadUrl就是下載鏈接
  DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
  //指定下載路徑和下載文件名
  request.setDestinationInExternalPublicDir("", url.substring(url.lastIndexOf("/") + 1));
  //獲取下載管理器
  DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
  //將下載任務(wù)加入下載隊(duì)列,否則不會(huì)進(jìn)行下載
  downloadManager.enqueue(request);
}

 這種方式其實(shí)就是交給了Android系統(tǒng)的另一個(gè)app去下載管理。這樣的好處不會(huì)消耗該APP的 CPU資源。缺點(diǎn)是:控制起來(lái)很不靈活。

三、使用第三方 okhttp 網(wǎng)絡(luò)請(qǐng)求框架

private void downloadFile3(){
  //下載路徑,如果路徑無(wú)效了,可換成你的下載路徑
  final String url = "http://c.qijingonline.com/test.mkv";
  final long startTime = System.currentTimeMillis();
  Log.i("DOWNLOAD","startTime="+startTime);
  Request request = new Request.Builder().url(url).build();
  new OkHttpClient().newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
      // 下載失敗
      e.printStackTrace();
      Log.i("DOWNLOAD","download failed");
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
      Sink sink = null;
      BufferedSink bufferedSink = null;
      try {
        String mSDCardPath= Environment.getExternalStorageDirectory().getAbsolutePath();
        File dest = new File(mSDCardPath,  url.substring(url.lastIndexOf("/") + 1));
        sink = Okio.sink(dest);
        bufferedSink = Okio.buffer(sink);
        bufferedSink.writeAll(response.body().source());
        bufferedSink.close();
        Log.i("DOWNLOAD","download success");
        Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
      } catch (Exception e) {
        e.printStackTrace();
        Log.i("DOWNLOAD","download failed");
      } finally {
        if(bufferedSink != null){
          bufferedSink.close();
        }
      }
    }
  });
}

okhttp是一個(gè)很有名氣的開(kāi)源框架,目前已經(jīng)很多大公司都直接使用它作為網(wǎng)絡(luò)請(qǐng)求庫(kù)(七牛云SDK, 阿里云SDK)。 且里面集成了很多優(yōu)勢(shì),包括 okio (一個(gè)I/O框架,優(yōu)化內(nèi)存與CPU)。

以上所述是小編給大家介紹的Android 文件下載三種基本方式,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論