1.普通單線程下載文件:
?
直接使用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();
}
?
?
2.普通多線程下載:
?
多線程下載的流程:
1.獲取網(wǎng)絡(luò)連接
2.本地磁盤創(chuàng)建相同大小的空文件
3.計(jì)算每條線程從哪個(gè)部分開始下載政恍,結(jié)束
4.依次創(chuàng)建汪拥,啟動(dòng)多條線程來下載網(wǎng)絡(luò)資源的指定部分
?
?
(1)根據(jù)要訪問的URL路徑去調(diào)用openConnection(),得到HttpConnection對(duì)象,接著調(diào)用getContentLength(),獲得下載的文件長(zhǎng)度篙耗,最后設(shè)置本地文件長(zhǎng)度迫筑。
int filesize=HttpURLConnection.getContentLength();
RandomAccessFile file=new RandomAccessFile("xx.apk","rwd");
file.setLength(filesize);
?
另外:RandomAccessFile:隨機(jī)訪問類,同時(shí)整合了FileOutputStream和FileInputStream宗弯,支持從文件的任何字節(jié)處讀寫數(shù)據(jù)脯燃。而File只支持將文件作為整體來處理,不能讀寫文件蒙保。
?
(2)根據(jù)文件長(zhǎng)度以及線程數(shù)計(jì)算每條線程的下載長(zhǎng)度辕棚,以及每條線程下載的開始位置。
計(jì)算公式:加入N條線程邓厕,下載大小為M個(gè)字節(jié)的文件:
每個(gè)線程下載的數(shù)據(jù)量:M%N==0?M/N:M/N+1
比如:大小為10個(gè)字節(jié)逝嚎,開三條線程,每條線程:
10/3+1=4;下載量;4/4/3
下載開始位置的計(jì)算:
假設(shè)線程id:1,2,3
開始位置:id*下載量
結(jié)束為止:(id+1)*下載量-1(最后一條位置是不用計(jì)算結(jié)束位置的)
(3)保存文件详恼。使用RandomAccessFile類指定從文件的什么位置寫入數(shù)據(jù)补君。
RandomAccessFile file=new RandomAccessFile(“XXX.APK”,“rwd”);
file.seek(2097152);
?
另外在下載時(shí)昧互,怎么指定每條線程挽铁,開始下載的位置呢?
HTTP協(xié)議為我們提供了一個(gè)Range頭硅堆,使用下面的方法指定從什么位置開始下載:
HTTPURLConnection.setRequestProperty(“Range”屿储,“byte=2097152”);
?
public class Downloader {
public void downloader() 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 httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("GET");
//獲得需要下載的文件的長(zhǎng)度
int filelength=httpURLConnection.getContentLength();
//本地創(chuàng)建一個(gè)大小相同的文件夾
RandomAccessFile randomAccessFile=new RandomAccessFile(filename,"rwd");
randomAccessFile.setLength(filelength);
randomAccessFile.close();
httpURLConnection.disconnect();
//設(shè)置線程的下載的數(shù)量
int threadSize=3;
//計(jì)算每條線程下載的數(shù)量
int threadlength = filelength % threadSize == 0 ? filelength/threadSize:filelength+1;
//設(shè)置每條線程從哪個(gè)位置開始下載
for (int i=0;i<threadSize;i++){
int startPoint=i*threadlength;
//從文件的什么位置開始寫入
RandomAccessFile file=new RandomAccessFile(filename,"rwd");
randomAccessFile.seek(startPoint);
//開啟三條線程,開始從startPoint下載文件
new DownLoadThread (i,startPoint,file,threadlength,path).start();
}
int quit = System.in.read();
while('q' != quit)
{
Thread.sleep(2000);
}
}
private class DownLoadThread extends Thread{
private int i;
private int startPoint;
private RandomAccessFile file;
private int threadlength;
private String path;
public DownLoadThread() {
}
public DownLoadThread (int i, int startPoint, RandomAccessFile file, int threadlength, String path) {
this.i=i;
this.file=file;
this.threadlength=threadlength;
this.startPoint=startPoint;
this.path=path;
}
@Override
public void run() {
try {
URL url=new URL(path);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
//指定從什么地方開始下載
conn.setRequestProperty("Range", "bytes="+startPoint+"-");
if(conn.getResponseCode()==206){
InputStream in=conn.getInputStream();
byte[] by=new byte[1024];
int len=-1;
int length=0;
while (length<threadlength&&(len=in.read(by))!=-1){
file.write(by,0,len);
//計(jì)算累計(jì)下載的長(zhǎng)度
length+=len;
}
file.close();
in.close();
System.out.println("線程"+(i+1) + "已下載完成");
}
} catch (java.io.IOException e) {
System.out.println("線程"+(i+1) + "下載出錯(cuò)"+ e);}
}
}
?
?
?
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'的話就退出
?
.使用DownloadManager更新應(yīng)用并覆蓋安裝:
下面的代碼可以直接用,加入到項(xiàng)目后民褂,記得為這個(gè)內(nèi)部廣播注冊(cè)一個(gè)過濾器:
?
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();
}
}
}?
?
多線程斷點(diǎn)下載:
附上一篇講解線程文件下載、多線程下載的鏈接:
http://www.runoob.com/w3cnote/android-tutorial-download2.html