Android四步快速实现断点续传

1.导入依赖

implementation 'com.loopj.android:android-async-http:1.4.9'
2.导入权限



3.布局文件


xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.five.fashion.duandianxuchuan.MainActivity">
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/pb"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_info"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:id="@+id/bt_download"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停"
android:id="@+id/bt_pause"
/>

4.主要代码

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 = "请放一张图片";放图!!!
@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 < threadsize; threadid++) {
                //获取原来指定线程的下载记录
                int existDownloadLength = readDownloadInfo(threadid);
                count = count + existDownloadLength;
            }
            //设置进度条的刻度
            pb.setProgress(count);

            //计算比率
            int result = (count * 100) / filelength;
            tv_info.setText("下载:" + result + "%");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    bt_download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            download(v);
        }
    });
    bt_pause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pause(v);
        }
    });
}
//暂停
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);//一点击变成不可点击
    bt_pause.setEnabled(true);//一点击变成可点击
    new Thread(){//子线程
        public void run() {
            try {
                //获取服务器上文件的大小
                HttpClient client = new DefaultHttpClient();
                HttpHead request = new HttpHead(uri);
                HttpResponse response = client.execute(request);
                //response  只有响应头  没有响应体
                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);

                    //设置进度条的最大值
                    Message msg_setmax = Message.obtain(mHandler, SET_MAX, filelength, 0);
                    msg_setmax.sendToTarget();


                    //处理下载记录文件
                    for(int threadid=0;threadid

}

你可能感兴趣的:(Android四步快速实现断点续传)