Android實(shí)現(xiàn)簡(jiǎn)單斷點(diǎn)續(xù)傳和下載到本地功能
本文實(shí)例為大家分享了Android實(shí)現(xiàn)斷點(diǎn)續(xù)傳和下載的具體代碼,供大家參考,具體內(nèi)容如下
效果展示

導(dǎo)入依賴與權(quán)限
依賴
compile 'com.loopj.android:android-async-http:1.4.9'
權(quán)限
<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
主MainActivity(布局)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.lv.mama.test004.MainActivity"> <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="20dp" android:layout_marginTop="15dp" android:id="@+id/pb" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <TextView android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/pb" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="20dp" android:layout_marginStart="20dp" android:layout_marginTop="13dp" android:id="@+id/tv_info" /> <Button android:text="暫停" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="17dp" android:id="@+id/bt_pause" android:onClick="pause" android:layout_below="@+id/tv_info" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="11dp" android:layout_marginStart="11dp" /> <Button android:text="開始" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="24dp" android:layout_marginEnd="24dp" android:id="@+id/bt_download" android:onClick="download" android:layout_alignBaseline="@+id/bt_pause" android:layout_alignBottom="@+id/bt_pause" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
主MainActivity
public class MainActivity extends AppCompatActivity {
protected static final String TAG = "OtherActivity";
//下載線程的數(shù)量
private final static int threadsize = 3;
protected static final int SET_MAX = 0;
public static final int UPDATE_VIEW = 1;
private ProgressBar pb;
private Button bt_download;
private Button bt_pause;
private TextView tv_info;
//顯示進(jìn)度和更新進(jìn)度
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SET_MAX://設(shè)置進(jìn)度條的最大值
int filelength = msg.arg1;
pb.setMax(filelength);
break;
case UPDATE_VIEW://更新進(jìn)度條 和 下載的比率
int len = msg.arg1;//新下載的長(zhǎng)度
pb.setProgress(pb.getProgress() + len);//設(shè)置進(jìn)度條的刻度
int max = pb.getMax();//獲取進(jìn)度的最大值
int progress = pb.getProgress();//獲取已經(jīng)下載的數(shù)據(jù)量
// 下載:30 總:100
int result = (progress * 100) / max;
tv_info.setText("下載:" + result + "%");
break;
default:
break;
}
}
;
};
String uri = "http://c.hiphotos.baidu.com/image/pic/item/b90e7bec54e736d1e51217c292504fc2d46269f3.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件
pb = (ProgressBar) findViewById(R.id.pb);
tv_info = (TextView) findViewById(R.id.tv_info);
bt_download = (Button) findViewById(R.id.bt_download);
bt_pause = (Button) findViewById(R.id.bt_pause);
//數(shù)據(jù)的回顯
//確定下載的文件
String name = getFileName(uri);
File file = new File(Environment.getExternalStorageDirectory(), name);
if (file.exists()) {//文件存在回顯
//獲取文件的大小
int filelength = (int) file.length();
pb.setMax(filelength);
try {
//統(tǒng)計(jì)原來(lái)所有的下載量
int count = 0;
//讀取下載記錄文件
for (int threadid = 0; threadid < threadsize; threadid++) {
//獲取原來(lái)指定線程的下載記錄
int existDownloadLength = readDownloadInfo(threadid);
count = count + existDownloadLength;
}
//設(shè)置進(jìn)度條的刻度
pb.setProgress(count);
//計(jì)算比率
int result = (count * 100) / filelength;
tv_info.setText("下載:" + result + "%");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//暫停
private boolean flag = false;//是否在下載
public void pause(View v){
flag = false;
bt_download.setEnabled(true);
bt_pause.setEnabled(false);
}
//下載
public void download(View v){
flag = true; //是在下載
bt_download.setEnabled(false);//一點(diǎn)擊變成不可點(diǎn)擊
bt_pause.setEnabled(true);//一點(diǎn)擊變成可點(diǎn)擊
new Thread(){//子線程
public void run() {
try {
//獲取服務(wù)器上文件的大小
HttpClient client = new DefaultHttpClient();
HttpHead request = new HttpHead(uri);
HttpResponse response = client.execute(request);
//response 只有響應(yīng)頭 沒(méi)有響應(yīng)體
if(response.getStatusLine().getStatusCode() == 200){
Header[] headers = response.getHeaders("Content-Length");
String value = headers[0].getValue();
//文件大小
int filelength = Integer.parseInt(value);
Log.i(TAG, "filelength:"+filelength);
//設(shè)置進(jìn)度條的最大值
Message msg_setmax = Message.obtain(mHandler, SET_MAX, filelength, 0);
msg_setmax.sendToTarget();
//處理下載記錄文件
for(int threadid=0;threadid<threadsize;threadid++){
//對(duì)應(yīng)的下載記錄文件
File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
//判斷文件是否存在
if(!file.exists()){
//創(chuàng)建文件
file.createNewFile();
}
}
//在sdcard創(chuàng)建和服務(wù)器大小一樣的文件
String name = getFileName(uri);
File file = new File(Environment.getExternalStorageDirectory(),name);
//隨機(jī)訪問(wèn)文件
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
//設(shè)置文件的大小
raf.setLength(filelength);
//關(guān)閉
raf.close();
//計(jì)算每條線程的下載量
int block = (filelength%threadsize == 0)?(filelength/threadsize):(filelength/threadsize+1);
//開啟三條線程執(zhí)行下載
for(int threadid=0;threadid<threadsize;threadid++){
new DownloadThread(threadid, uri, file, block).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
//線程下載類
private class DownloadThread extends Thread {
private int threadid;//線程的id
private String uri;//下載的地址
private File file;//下載文件
private int block;//下載的塊
private int start;
private int end;
public DownloadThread(int threadid, String uri, File file, int block) {
super();
this.threadid = threadid;
this.uri = uri;
this.file = file;
this.block = block;
//計(jì)算下載的開始位置和結(jié)束位置
start = threadid * block;
end = (threadid + 1) * block - 1;
try {
//讀取該條線程原來(lái)的下載記錄
int existDownloadLength = readDownloadInfo(threadid);
//修改下載的開始位置 從新下載
start = start + existDownloadLength;
} catch (Exception e) {
e.printStackTrace();
}
}
//下載 狀態(tài)碼:200是普通的下載 206是分段下載 Range:范圍
@Override
public void run() {
super.run();
try {
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
//跳轉(zhuǎn)到起始位置
raf.seek(start);
//分段下載
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(uri);
request.addHeader("Range", "bytes:"+start+"-"+end);//添加請(qǐng)求頭
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
InputStream inputStream = response.getEntity().getContent();
//把流寫入到文件
byte[] buffer = new byte[1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1){
//如果暫停下載 點(diǎn)擊暫停 false 就直接return 點(diǎn)擊下載true接著下載
if(!flag){
return;//標(biāo)準(zhǔn)線程結(jié)束
}
//寫數(shù)據(jù)
raf.write(buffer, 0, len);
//讀取原來(lái)下載的數(shù)據(jù)量 這里讀取是為了更新下載記錄
int existDownloadLength = readDownloadInfo(threadid);//原來(lái)下載的數(shù)據(jù)量
//計(jì)算最新的下載
int newDownloadLength = existDownloadLength + len;
//更新下載記錄 從新記錄最新下載位置
updateDownloadInfo(threadid, newDownloadLength);
//更新進(jìn)度條的顯示 下載的百分比
Message update_msg = Message.obtain(mHandler, UPDATE_VIEW, len, 0);
update_msg.sendToTarget();
//模擬 看到進(jìn)度條動(dòng)的效果
SystemClock.sleep(50);
}
inputStream.close();
raf.close();
Log.i(TAG, "第"+threadid+"條線程下載完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 讀取指定線程的下載數(shù)據(jù)量
* @param threadid 線程的id
* @return
* @throws Exception
*/
public int readDownloadInfo(int threadid) throws Exception{
//下載記錄文件
File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
BufferedReader br = new BufferedReader(new FileReader(file));
//讀取一行數(shù)據(jù)
String content = br.readLine();
int downlength = 0;
//如果該文件第一次創(chuàng)建去執(zhí)行讀取操作 文件里面的內(nèi)容是 null
if(!TextUtils.isEmpty(content)){
downlength = Integer.parseInt(content);
}
//關(guān)閉流
br.close();
return downlength;
}
/**
* 更新下載記錄
* @param threadid
* @param newDownloadLength
*/
public void updateDownloadInfo(int threadid,int newDownloadLength) throws Exception{
//下載記錄文件
File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
FileWriter fw = new FileWriter(file);
fw.write(newDownloadLength+"");
fw.close();
}
/**
* 獲取文件的名稱
* @param uri
* @return
*/
private String getFileName(String uri){
return uri.substring(uri.lastIndexOf("/")+1);
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android實(shí)現(xiàn)網(wǎng)絡(luò)多線程斷點(diǎn)續(xù)傳下載功能
- Android多線程斷點(diǎn)續(xù)傳下載功能實(shí)現(xiàn)代碼
- android使用OkHttp實(shí)現(xiàn)下載的進(jìn)度監(jiān)聽和斷點(diǎn)續(xù)傳
- android實(shí)現(xiàn)多線程下載文件(支持暫停、取消、斷點(diǎn)續(xù)傳)
- Android 斷點(diǎn)續(xù)傳原理以及實(shí)現(xiàn)
- Android實(shí)現(xiàn)網(wǎng)絡(luò)多線程斷點(diǎn)續(xù)傳下載實(shí)例
- Android 斷點(diǎn)續(xù)傳的原理剖析與實(shí)例講解
- Android編程開發(fā)實(shí)現(xiàn)多線程斷點(diǎn)續(xù)傳下載器實(shí)例
- Android斷點(diǎn)續(xù)傳下載器JarvisDownloader的示例
相關(guān)文章
Android進(jìn)程保活之提升進(jìn)程優(yōu)先級(jí)
這篇文章主要介紹了Android進(jìn)程?;钪嵘M(jìn)程優(yōu)先級(jí),對(duì)提升優(yōu)先級(jí)感興趣的同學(xué)可以參考下2021-04-04
Android 判斷當(dāng)前語(yǔ)言環(huán)境是否是中文環(huán)境
本文主要介紹了Android 判斷當(dāng)前語(yǔ)言環(huán)境是否是中文環(huán)境的方法。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-04-04
Android編程實(shí)現(xiàn)變化的雙重選擇框功能示例
這篇文章主要介紹了Android編程實(shí)現(xiàn)變化的雙重選擇框功能,結(jié)合實(shí)例形式分析了Android雙重選擇框功能的樣式布局與功能實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10
Android實(shí)現(xiàn)基于滑動(dòng)的SQLite數(shù)據(jù)分頁(yè)加載技術(shù)(附demo源碼下載)
這篇文章主要介紹了Android實(shí)現(xiàn)基于滑動(dòng)的SQLite數(shù)據(jù)分頁(yè)加載技術(shù),涉及Android針對(duì)SQLite數(shù)據(jù)的讀取及查詢結(jié)果的分頁(yè)顯示功能相關(guān)實(shí)現(xiàn)技巧,末尾還附帶demo源碼供讀者下載參考,需要的朋友可以參考下2016-07-07
Kotlin使用flow實(shí)現(xiàn)倒計(jì)時(shí)功能(示例詳解)
這篇文章主要介紹了Kotlin使用flow實(shí)現(xiàn)倒計(jì)時(shí)功能,本文通過(guò)圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-02-02
Android開發(fā)中使用achartengine繪制各種圖表的方法
這篇文章主要介紹了Android開發(fā)中使用achartengine繪制各種圖表的方法,結(jié)合具體實(shí)例形式分析了Android基于圖表生成類庫(kù)achartengine進(jìn)行圖表繪制的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-10-10

