本文实例为大家分享了Android快速实现断点续传的具体代码,供大家参考,具体内容如下
1.导入依赖
compile 'com.loopj.android:android-async-http:1.4.9'
2.导入权限
3.布局文件
<&#63;xml version="1.0" encoding="utf-8"&#63;>
4.主要代码
package com.five.fashion.duandianxuchuan; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.loopj.android.http.HttpGet; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.RandomAccessFile; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.HttpResponse; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.client.methods.HttpHead; import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; public class MainActivity extends AppCompatActivity { protected static final String TAG = "OtherActivity"; //下载线程的数量 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; //显示进度和更新进度 private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case SET_MAX://设置进度条的最大值 int filelength = msg.arg1; pb.setMax(filelength); break; case UPDATE_VIEW://更新进度条 和 下载的比率 int len = msg.arg1;//新下载的长度 pb.setProgress(pb.getProgress()+len);//设置进度条的刻度 int max = pb.getMax();//获取进度的最大值 int progress = pb.getProgress();//获取已经下载的数据量 // 下载: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(@Nullable 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); //数据的回显 //确定下载的文件 String name = getFileName(uri); File file = new File(Environment.getExternalStorageDirectory(), name); if (file.exists()){//文件存在回显 //获取文件的大小 int filelength = (int) file.length(); pb.setMax(filelength); try { //统计原来所有的下载量 int count = 0; //读取下载记录文件 for (int threadid = 0; threadid
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。