Android 文件下载的三种基本方式
生活随笔
收集整理的這篇文章主要介紹了
Android 文件下载的三种基本方式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 自己封裝URLConnection 連接請(qǐng)求類(lèi)
這種方式在Android 剛興起的時(shí)候,很少下載封裝框架,就自己封裝了。雖然一般的文件都能下載,但這種方式缺點(diǎn)很多,不穩(wěn)定或者各種各樣的問(wèn)題會(huì)出現(xiàn)。
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);} }2. Android自定的下載管理
會(huì)在notification 顯示下載的進(jìn)度,同時(shí)可以暫停、重新連接等.這種方式其實(shí)就是交給了Android系統(tǒng)的另一個(gè)app去下載管理。這樣的好處不會(huì)消耗該APP的 CPU資源。缺點(diǎn)是:控制起來(lái)很不靈活。
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); }3. 使用第三方 okhttp 網(wǎng)絡(luò)請(qǐng)求框架(推薦)
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)。
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() {@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();}}}}); }在接收數(shù)據(jù)的時(shí)候使用了 okio框架 來(lái)做一些I/O處理,okio框架是彌補(bǔ)Java.io 上的不足,節(jié)省CPU與內(nèi)存資源.
demo:
原文連接:點(diǎn)擊這里
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Android 文件下载的三种基本方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 我的世界如何快速学会速搭(我的世界速搭技
- 下一篇: android qq分组展开,Andro