日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

Android 文件下载的三种基本方式

發(fā)布時(shí)間:2024/10/12 Android 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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:

public void downloadFile(){final String url = "http://c.qijingonline.com/test.mkv";final long startTime = System.currentTimeMillis();Log.i("DOWNLOAD","startTime="+startTime);OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(url).build();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 {InputStream is = null;byte[] buf = new byte[2048];int len = 0;FileOutputStream fos = null;// 儲(chǔ)存下載文件的目錄String savePath = Environment.getExternalStorageDirectory().getAbsolutePath();try {is = response.body().byteStream();long total = response.body().contentLength();File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));fos = new FileOutputStream(file);long sum = 0;while ((len = is.read(buf)) != -1) {fos.write(buf, 0, len);sum += len;int progress = (int) (sum * 1.0f / total * 100);// 下載中 // listener.onDownloading(progress);}fos.flush();// 下載完成 // listener.onDownloadSuccess();Log.i("DOWNLOAD","download success");Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));} catch (Exception e) {e.printStackTrace(); // listener.onDownloadFailed();Log.i("DOWNLOAD","download failed");} finally {try {if (is != null)is.close();} catch (IOException e) {}try {if (fos != null)fos.close();} catch (IOException e) {}}}});}

原文連接:點(diǎn)擊這里

與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖

總結(jié)

以上是生活随笔為你收集整理的Android 文件下载的三种基本方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。