W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
又是一個(gè)深坑,初學(xué)者慎入...本節(jié)將從普通的單線程下載 -> 普通多線程下載 -> -> 以及一個(gè)很實(shí)用的例子:利用Android那只DownloadManager更新apk 并覆蓋安裝的實(shí)現(xiàn)代碼!好的,這樣看上去,本節(jié)還是蠻有趣的,開始本節(jié)內(nèi)容! PS:我們把整個(gè)完整的多線程斷點(diǎn)續(xù)傳放到下一節(jié)中!
直接使用URLConnection.openStream()打開網(wǎng)絡(luò)輸入流,然后將流寫入到文件中!
核心方法:
public static void downLoad(String path,Context context)throws Exception { URL url = new URL(path); InputStream is = url.openStream(); //截取最后的文件名 String end = path.substring(path.lastIndexOf(".")); //打開手機(jī)對(duì)應(yīng)的輸出流,輸出到文件中 OutputStream os = context.openFileOutput("Cache_"+System.currentTimeMillis()+end, Context.MODE_PRIVATE); byte[] buffer = new byte[1024]; int len = 0; //從輸入六中讀取數(shù)據(jù),讀到緩沖區(qū)中 while((len = is.read(buffer)) > 0) { os.write(buffer,0,len); } //關(guān)閉輸入輸出流 is.close(); os.close(); }
運(yùn)行結(jié)果:
我們都知道使用多線程下載文件可以更快地完成文件的下載,但是為什么呢?
答:因?yàn)閾屨嫉姆?wù)器資源多,假設(shè)服務(wù)器最多服務(wù)100個(gè)用戶,服務(wù)器中的一個(gè)線程 對(duì)應(yīng)一個(gè)用戶100條線程在計(jì)算機(jī)中并發(fā)執(zhí)行,由CPU劃分時(shí)間片輪流執(zhí)行,加入a有99條線程 下載文件,那么相當(dāng)于占用了99個(gè)用戶資源,自然就有用較快的下載速度
PS:當(dāng)然不是線程越多就越好,開啟過多線程的話,app需要維護(hù)和同步每條線程的開銷, 這些開銷反而會(huì)導(dǎo)致下載速度的降低,另外還和你的網(wǎng)速有關(guān)!
多線程下載的流程:
獲取網(wǎng)絡(luò)連接本地磁盤創(chuàng)建相同大小的空文件計(jì)算每條線程需從文件哪個(gè)部分開始下載,結(jié)束依次創(chuàng)建,啟動(dòng)多條線程來下載網(wǎng)絡(luò)資源的指定部分
PS:這里直接創(chuàng)建一個(gè)Java項(xiàng)目,然后在JUnit里運(yùn)行指定方法即可,
核心代碼如下:
public class Downloader { //添加@Test標(biāo)記是表示該方法是Junit測(cè)試的方法,就可以直接運(yùn)行該方法了 @Test public void download() throws Exception { //設(shè)置URL的地址和下載后的文件名 String filename = "meitu.exe"; String path = "http://10.13.20.32:8080/Test/XiuXiu_Green.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); //獲得需要下載的文件的長(zhǎng)度(大小) int filelength = conn.getContentLength(); System.out.println("要下載的文件長(zhǎng)度"+filelength); //生成一個(gè)大小相同的本地文件 RandomAccessFile file = new RandomAccessFile(filename, "rwd"); file.setLength(filelength); file.close(); conn.disconnect(); //設(shè)置有多少條線程下載 int threadsize = 3; //計(jì)算每個(gè)線程下載的量 int threadlength = filelength % 3 == 0 ? filelength/3:filelength+1; for(int i = 0;i < threadsize;i++) { //設(shè)置每條線程從哪個(gè)位置開始下載 int startposition = i * threadlength; //從文件的什么位置開始寫入數(shù)據(jù) RandomAccessFile threadfile = new RandomAccessFile(filename, "rwd"); threadfile.seek(startposition); //啟動(dòng)三條線程分別從startposition位置開始下載文件 new DownLoadThread(i,startposition,threadfile,threadlength,path).start(); } int quit = System.in.read(); while('q' != quit) { Thread.sleep(2000); } } private class DownLoadThread extends Thread { private int threadid; private int startposition; private RandomAccessFile threadfile; private int threadlength; private String path; public DownLoadThread(int threadid, int startposition, RandomAccessFile threadfile, int threadlength, String path) { this.threadid = threadid; this.startposition = startposition; this.threadfile = threadfile; this.threadlength = threadlength; this.path = path; } public DownLoadThread() {} @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); //指定從什么位置開始下載 conn.setRequestProperty("Range", "bytes="+startposition+"-"); //System.out.println(conn.getResponseCode()); if(conn.getResponseCode() == 206) { InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; int len = -1; int length = 0; while(length < threadlength && (len = is.read(buffer)) != -1) { threadfile.write(buffer,0,len); //計(jì)算累計(jì)下載的長(zhǎng)度 length += len; } threadfile.close(); is.close(); System.out.println("線程"+(threadid+1) + "已下載完成"); } }catch(Exception ex){System.out.println("線程"+(threadid+1) + "下載出錯(cuò)"+ ex);} } } }
運(yùn)行截圖:
如圖,使用多線程完成了對(duì)文件的下載!雙擊exe文件可運(yùn)行,說明文件并沒有損壞!
注意事項(xiàng):
- int filelength = conn.getContentLength(); //獲得下載文件的長(zhǎng)度(大小)
- RandomAccessFile file = new RandomAccessFile(filename, "rwd"); //該類運(yùn)行對(duì)文件進(jìn)行讀寫,是多線程下載的核心
- nt threadlength = filelength % 3 == 0 ? filelength/3:filelength+1; //計(jì)算每個(gè)線程要下載的量
- conn.setRequestProperty("Range", "bytes="+startposition+"-"); //指定從哪個(gè)位置開始讀寫,這個(gè)是URLConnection提供的方法
- //System.out.println(conn.getResponseCode()); //這個(gè)注釋了的代碼是用來查看conn的返回碼的,我們前面用的都是200, 而針對(duì)多線程的話,通常是206,必要時(shí)我們可以通過調(diào)用該方法查看返回碼!
- int quit = System.in.read();while('q' != quit){Thread.sleep(2000);} //這段代碼是做延時(shí)操作的,因?yàn)槲覀冇玫氖潜镜叵螺d,可能該方法運(yùn)行完了,而我們的 線程還沒有開啟,這樣會(huì)引發(fā)異常,這里的話,讓用戶輸入一個(gè)字符,如果是'q'的話就退出
下面的代碼可以直接用,加入到項(xiàng)目后,記得為這個(gè)內(nèi)部廣播注冊(cè)一個(gè)過濾器:
AndroidManifest.xml
:
import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; /** * Created by Jay on 2015/9/9 0009. */ public class UpdateAct extends AppCompatActivity { //這個(gè)更新的APK的版本部分,我們是這樣命名的:xxx_v1.0.0_xxxxxxxxx.apk //這里我們用的是git提交版本的前九位作為表示 private static final String FILE_NAME = "ABCDEFGHI"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String endpoint = ""; try { //這部分是獲取AndroidManifest.xml里的配置信息的,包名,以及Meta_data里保存的東西 ApplicationInfo info = getPackageManager().getApplicationInfo( getPackageName(), PackageManager.GET_META_DATA); //我們?cè)趍eta_data保存了xxx.xxx這樣一個(gè)數(shù)據(jù),是https開頭的一個(gè)鏈接,這里替換成http endpoint = info.metaData.getString("xxxx.xxxx").replace("https", "http"); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //下面的都是拼接apk更新下載url的,path是保存的文件夾路徑 final String _Path = this.getIntent().getStringExtra("path"); final String _Url = endpoint + _Path; final DownloadManager _DownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request _Request = new DownloadManager.Request( Uri.parse(_Url)); _Request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, FILE_NAME + ".apk"); _Request.setTitle(this.getString(R.string.app_name)); //是否顯示下載對(duì)話框 _Request.setShowRunningNotification(true); _Request.setMimeType("application/com.trinea.download.file"); //將下載請(qǐng)求放入隊(duì)列 _DownloadManager.enqueue(_Request); this.finish(); } //注冊(cè)一個(gè)廣播接收器,當(dāng)下載完畢后會(huì)收到一個(gè)android.intent.action.DOWNLOAD_COMPLETE //的廣播,在這里取出隊(duì)列里下載任務(wù),進(jìn)行安裝 public static class Receiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { final DownloadManager _DownloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); final long _DownloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, 0); final DownloadManager.Query _Query = new DownloadManager.Query(); _Query.setFilterById(_DownloadId); final Cursor _Cursor = _DownloadManager.query(_Query); if (_Cursor.moveToFirst()) { final int _Status = _Cursor.getInt(_Cursor .getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)); final String _Name = _Cursor.getString(_Cursor .getColumnIndexOrThrow("local_filename")); if (_Status == DownloadManager.STATUS_SUCCESSFUL && _Name.indexOf(FILE_NAME) != 0) { Intent _Intent = new Intent(Intent.ACTION_VIEW); _Intent.setDataAndType( Uri.parse(_Cursor.getString(_Cursor .getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI))), "application/vnd.android.package-archive"); _Intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(_Intent); } } _Cursor.close(); } } }
普通單線程下載文件:DownLoadDemo1.zip 普通多線程下載文件:J2SEMulDownLoader.zip
好的,本節(jié)給大家介紹了普通單線程以及多線程下載文件,還有利用Android自帶DownManager來 下載更新APK,然后覆蓋的實(shí)現(xiàn)!相信會(huì)對(duì)大家的實(shí)際開發(fā)帶來便利,好的,就說這么多,謝
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: