多線程斷點繼續


參考上篇多線程加權限

=======================================佈局============================================

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下載地址" />



    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/bt_download"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="download"
            android:text="下載" />

        <Button
            android:id="@+id/bt_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="pause"
            android:enabled="false"
            android:text="暫停" />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/pb"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_info"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="下載:0%" />

</LinearLayout>
========================================================邏輯代碼=======================================================

public class OtherActivity 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(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://wx1.sinaimg.cn/mw690/005RzqMsly1fia3omupu1j31900y27wh.jpg";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
//找到控件
        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();
            }
        }



    }
    //暫停
        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<threadsize;threadid++){
                                //對應的下載記錄文件
                                File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
                                //判斷文件是否存在
                                if(!file.exists()){
                                    //創建文件
                                    file.createNewFile();
                                }
                            }


                            //sdcard創建和服務器大小一樣的文件
                            String name = getFileName(uri);
                            File file = new File(Environment.getExternalStorageDirectory(),name);
                            //隨機訪問文件
                            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                            //設置文件的大小
                            raf.setLength(filelength);
                            //關閉
                            raf.close();

                            //計算每條線程的下載量
                            int block = (filelength%threadsize == 0)?(filelength/threadsize):(filelength/threadsize+1);

                            //開啓三條線程執行下載
                            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;
                //計算下載的開始位置和結束位置
                start = threadid * block;
                end = (threadid + 1)*block -1;

                try {
                    //讀取該條線程原來的下載記錄
                    int existDownloadLength = readDownloadInfo(threadid);

                    //修改下載的開始位置
                    start = start + existDownloadLength;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }



            //下載   狀態碼:200是普通的下載      206是分段下載        Range:範圍
            @Override
            public void run() {
                super.run();
                try {
                    RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                    //跳轉到起始位置
                    raf.seek(start);

                    //分段下載
                    HttpClient client = new DefaultHttpClient();
                    HttpGet request = new HttpGet(uri);
                    request.addHeader("Range", "bytes:"+start+"-"+end);//添加請求頭
                    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){
                            //如果暫停下載   就直接return
                            if(!flag){
                                return;//標準線程結束
                            }
                            //寫數據
                            raf.write(buffer, 0, len);

                            //讀取原來下載的數據量
                            int existDownloadLength = readDownloadInfo(threadid);//原來下載的數據量

                            //計算最新的下載
                            int newDownloadLength = existDownloadLength + len;

                            //更新下載記錄
                            updateDownloadInfo(threadid, newDownloadLength);

                            //更新進度條的顯示   下載的百分比
                            Message update_msg = Message.obtain(mHandler, UPDATE_VIEW, len, 0);
                            update_msg.sendToTarget();
                            //模擬  看到進度條動的效果
                            SystemClock.sleep(50);
                        }
                        inputStream.close();
                        raf.close();
                        Log.i(TAG, ""+threadid+"條線程下載完成");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        /**
         * 讀取指定線程的下載數據量
         * @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));
            //讀取一行數據
            String content = br.readLine();

            int downlength = 0;
            //如果該文件第一次創建去執行讀取操作  文件裏面的內容是 null
            if(!TextUtils.isEmpty(content)){
                downlength = Integer.parseInt(content);
            }
            //關閉流
            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);
        }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章