Android 文件下载的三种基本方式
生活随笔
收集整理的這篇文章主要介紹了
Android 文件下载的三种基本方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 自己封裝URLConnection 連接請求類
這種方式在Android 剛興起的時候,很少下載封裝框架,就自己封裝了。雖然一般的文件都能下載,但這種方式缺點很多,不穩定或者各種各樣的問題會出現。
public void downloadFile1() {try{//下載路徑,如果路徑無效了,可換成你的下載路徑String url = "http://c.qijingonline.com/test.mkv";String path = Environment.getExternalStorageDirectory().getAbsolutePath();final long startTime = System.currentTimeMillis();Log.i("DOWNLOAD","startTime="+startTime);//下載函數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();//根據響應獲取文件大小if (fileSize <= 0) throw new RuntimeException("無法獲知文件大小 ");if (is == null) throw new RuntimeException("stream is null");File file1 = new File(path);if(!file1.exists()){file1.mkdirs();}//把數據存入路徑+文件名FileOutputStream fos = new FileOutputStream(path+"/"+filename);byte buf[] = new byte[1024];int downLoadFileSize = 0;do{//循環讀取int numread = is.read(buf);if (numread == -1){break;}fos.write(buf, 0, numread);downLoadFileSize += numread;//更新進度條} 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);} }2. Android自定的下載管理
會在notification 顯示下載的進度,同時可以暫停、重新連接等.這種方式其實就是交給了Android系統的另一個app去下載管理。這樣的好處不會消耗該APP的 CPU資源。缺點是:控制起來很不靈活。
private void downloadFile2(){//下載路徑,如果路徑無效了,可換成你的下載路徑String url = "http://c.qijingonline.com/test.mkv";//創建下載任務,downloadUrl就是下載鏈接DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));//指定下載路徑和下載文件名request.setDestinationInExternalPublicDir("", url.substring(url.lastIndexOf("/") + 1));//獲取下載管理器DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);//將下載任務加入下載隊列,否則不會進行下載downloadManager.enqueue(request); }3. 使用第三方 okhttp 網絡請求框架(推薦)
okhttp是一個很有名氣的開源框架,目前已經很多大公司都直接使用它作為網絡請求庫(七牛云SDK, 阿里云SDK)。 且里面集成了很多優勢,包括 okio (一個I/O框架,優化內存與CPU)。
private void downloadFile3(){//下載路徑,如果路徑無效了,可換成你的下載路徑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() {@Overridepublic void onFailure(Call call, IOException e) {// 下載失敗e.printStackTrace();Log.i("DOWNLOAD","download failed");}@Overridepublic 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();}}}}); }在接收數據的時候使用了 okio框架 來做一些I/O處理,okio框架是彌補Java.io 上的不足,節省CPU與內存資源.
demo:
原文連接:點擊這里
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Android 文件下载的三种基本方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的世界如何快速学会速搭(我的世界速搭技
- 下一篇: android qq分组展开,Andro