1.普通單線程下載文件:
?
直接使用URLConnection.openStream();打開網絡輸入流,然后將流寫入到文件中。
?
核心方法:
?
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("."));
//打開手機對應的輸出流,輸出到文件中
OutputStream os = context.openFileOutput("Cache_"+System.currentTimeMillis()+end, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int len = 0;
//從輸入六中讀取數據,讀到緩沖區中
while((len = is.read(buffer)) > 0)
{
os.write(buffer,0,len);
}
//關閉輸入輸出流
is.close();
os.close();
}
?
?
2.普通多線程下載:
?
多線程下載的流程:
1.獲取網絡連接
2.本地磁盤創建相同大小的空文件
3.計算每條線程從哪個部分開始下載,結束
4.依次創建,啟動多條線程來下載網絡資源的指定部分
?
?
(1)根據要訪問的URL路徑去調用openConnection(),得到HttpConnection對象,接著調用getContentLength(),獲得下載的文件長度,最后設置本地文件長度。
int filesize=HttpURLConnection.getContentLength();
RandomAccessFile file=new RandomAccessFile("xx.apk","rwd");
file.setLength(filesize);
?
另外:RandomAccessFile:隨機訪問類,同時整合了FileOutputStream和FileInputStream,支持從文件的任何字節處讀寫數據。而File只支持將文件作為整體來處理,不能讀寫文件。
?
(2)根據文件長度以及線程數計算每條線程的下載長度,以及每條線程下載的開始位置。
計算公式:加入N條線程,下載大小為M個字節的文件:
每個線程下載的數據量:M%N==0?M/N:M/N+1
比如:大小為10個字節,開三條線程,每條線程:
10/3+1=4;下載量;4/4/3
下載開始位置的計算:
假設線程id:1,2,3
開始位置:id*下載量
結束為止:(id+1)*下載量-1(最后一條位置是不用計算結束位置的)
(3)保存文件。使用RandomAccessFile類指定從文件的什么位置寫入數據。
RandomAccessFile file=new RandomAccessFile(“XXX.APK”,“rwd”);
file.seek(2097152);
?
另外在下載時,怎么指定每條線程,開始下載的位置呢?
HTTP協議為我們提供了一個Range頭,使用下面的方法指定從什么位置開始下載:
HTTPURLConnection.setRequestProperty(“Range”,“byte=2097152”);
?
public class Downloader {
public void downloader() throws Exception {
//設置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");
//獲得需要下載的文件的長度
int filelength=httpURLConnection.getContentLength();
//本地創建一個大小相同的文件夾
RandomAccessFile randomAccessFile=new RandomAccessFile(filename,"rwd");
randomAccessFile.setLength(filelength);
randomAccessFile.close();
httpURLConnection.disconnect();
//設置線程的下載的數量
int threadSize=3;
//計算每條線程下載的數量
int threadlength = filelength % threadSize == 0 ? filelength/threadSize:filelength+1;
//設置每條線程從哪個位置開始下載
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);
//計算累計下載的長度
length+=len;
}
file.close();
in.close();
System.out.println("線程"+(i+1) + "已下載完成");
}
} catch (java.io.IOException e) {
System.out.println("線程"+(i+1) + "下載出錯"+ e);}
}
}
?
?
?
int filelength = conn.getContentLength(); //獲得下載文件的長度(大小)
RandomAccessFile file = new RandomAccessFile(filename, "rwd"); //該類運行對文件進行讀寫,是多線程下載的核心
nt threadlength = filelength % 3 == 0 ? filelength/3:filelength+1; //計算每個線程要下載的量
conn.setRequestProperty("Range", "bytes="+startposition+"-"); //指定從哪個位置開始讀寫,這個是URLConnection提供的方法
//System.out.println(conn.getResponseCode()); //這個注釋了的代碼是用來查看conn的返回碼的,我們前面用的都是200, 而針對多線程的話,通常是206,必要時我們可以通過調用該方法查看返回碼!
int quit = System.in.read();while('q' != quit){Thread.sleep(2000);} //這段代碼是做延時操作的,因為我們用的是本地下載,可能該方法運行完了,而我們的 線程還沒有開啟,這樣會引發異常,這里的話,讓用戶輸入一個字符,如果是'q'的話就退出
?
.使用DownloadManager更新應用并覆蓋安裝:
下面的代碼可以直接用,加入到項目后,記得為這個內部廣播注冊一個過濾器:
?
public class UpdateAct extends AppCompatActivity {
//這個更新的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);
//我們在meta_data保存了xxx.xxx這樣一個數據,是https開頭的一個鏈接,這里替換成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));
//是否顯示下載對話框
_Request.setShowRunningNotification(true);
_Request.setMimeType("application/com.trinea.download.file");
//將下載請求放入隊列
_DownloadManager.enqueue(_Request);
this.finish();
}
//注冊一個廣播接收器,當下載完畢后會收到一個android.intent.action.DOWNLOAD_COMPLETE
//的廣播,在這里取出隊列里下載任務,進行安裝
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();
}
}
}?
?
多線程斷點下載:
附上一篇講解線程文件下載、多線程下載的鏈接:
http://www.runoob.com/w3cnote/android-tutorial-download2.html