91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android 使用HttpURLConnection 實現多線程下載

發布時間:2020-07-26 18:59:21 來源:網絡 閱讀:747 作者:uncom2005 欄目:移動開發

工具類代碼:

package com.example.xiaocool.multithreadclient;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


public class DownUtil
{
    // 定義下載資源的路徑
    private String path;
    // 指定所下載的文件的保存位置
    private String targetFile;
    // 定義需要使用多少線程下載資源
    private int threadNum;
    // 定義下載的線程對象
    private DownThread[] threads;
    // 定義下載的文件的總大小
    private int fileSize;

    public DownUtil(String path, String targetFile, int threadNum)
    {
        this.path = path;
        this.threadNum = threadNum;
        // 初始化threads數組
        threads = new DownThread[threadNum];
        this.targetFile = targetFile;
    }

    public void download() throws Exception
    {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
                "Accept",
                "p_w_picpath/gif, p_w_picpath/jpeg, p_w_picpath/pjpeg, p_w_picpath/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        // 得到文件大小
        fileSize = conn.getContentLength();
        conn.disconnect();
        int currentPartSize = fileSize / threadNum + 1;
        RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
        // 設置本地文件的大小
        file.setLength(fileSize);
        file.close();
        for (int i = 0; i < threadNum; i++)
        {
            // 計算每條線程的下載的開始位置
            int startPos = i * currentPartSize;
            // 每個線程使用一個RandomAccessFile進行下載
            RandomAccessFile currentPart = new RandomAccessFile(targetFile,
                    "rw");
            // 定位該線程的下載位置
            currentPart.seek(startPos);
            // 創建下載線程
            threads[i] = new DownThread(startPos, currentPartSize,
                    currentPart);
            // 啟動下載線程
            threads[i].start();
        }
    }

    // 獲取下載的完成百分比
    public double getCompleteRate()
    {
        // 統計多條線程已經下載的總大小
        int sumSize = 0;
        for (int i = 0; i < threadNum; i++)
        {
            sumSize += threads[i].length;
        }
        // 返回已經完成的百分比
        return sumSize * 1.0 / fileSize;
    }

    private class DownThread extends Thread
    {
        // 當前線程的下載位置
        private int startPos;
        // 定義當前線程負責下載的文件大小
        private int currentPartSize;
        // 當前線程需要下載的文件塊
        private RandomAccessFile currentPart;
        // 定義已經該線程已下載的字節數
        public int length;

        public DownThread(int startPos, int currentPartSize,
                          RandomAccessFile currentPart)
        {
            this.startPos = startPos;
            this.currentPartSize = currentPartSize;
            this.currentPart = currentPart;
        }

        @Override
        public void run()
        {
            try
            {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection)url
                        .openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty(
                        "Accept",
                        "p_w_picpath/gif, p_w_picpath/jpeg, p_w_picpath/pjpeg, p_w_picpath/pjpeg, "
                                + "application/x-shockwave-flash, application/xaml+xml, "
                                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                                + "application/x-ms-application, application/vnd.ms-excel, "
                                + "application/vnd.ms-powerpoint, application/msword, */*");
                conn.setRequestProperty("Accept-Language", "zh-CN");
                conn.setRequestProperty("Charset", "UTF-8");
                InputStream inStream = conn.getInputStream();
                // 跳過startPos個字節,表明該線程只下載自己負責哪部分文件。
                inStream.skip(this.startPos);
                byte[] buffer = new byte[1024];
                int hasRead = 0;
                // 讀取網絡數據,并寫入本地文件
                while (length < currentPartSize
                        && (hasRead = inStream.read(buffer)) > 0)
                {
                    currentPart.write(buffer, 0, hasRead);
                    // 累計該線程下載的總大小
                    length += hasRead;
                }
                currentPart.close();
                inStream.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

MainActivity:

package com.example.xiaocool.multithreadclient;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends ActionBarActivity {
    EditText url;
    EditText target;
    Button downBn;
    ProgressBar bar;
    DownUtil downUtil;
    private int mDownStatus;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        url = (EditText) findViewById(R.id.url);
        target = (EditText) findViewById(R.id.target);
        downBn = (Button) findViewById(R.id.down);
        bar = (ProgressBar) findViewById(R.id.bar);
        // 創建一個Handler對象
        final Handler handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                if (msg.what == 0x123)
                {
                    bar.setProgress(mDownStatus);
                }
            }
        };
        downBn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // 初始化DownUtil對象 最后一個參數指定線程數
                downUtil = new DownUtil(url.getText().toString(),
                        target.getText().toString(), 6);
                new Thread()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            // 開始下載
                            downUtil.download();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        // 定義美妙調度獲取一次系統的完成進度
                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask()
                        {
                            @Override
                            public void run()
                            {
                                // 獲取下載任務的完成比例
                                double completeRate = downUtil.getCompleteRate();
                                mDownStatus = (int) (completeRate * 100);
                                handler.sendEmptyMessage(0x123);
                                // 下載完成后取消任務調度
                                if (mDownStatus >= 100)
                                {
                                    timer.cancel();
                                }
                            }
                        }, 0, 100);
                    }
                }.start();
            }
        });
    }
}

Android 使用HttpURLConnection 實現多線程下載

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

简阳市| 桐城市| 夏津县| 桃园县| 栾城县| 东山县| 绥宁县| 桐庐县| 陵水| 荆门市| 太仓市| 安多县| 泰州市| 长宁县| 扎赉特旗| 大英县| 张北县| 莱西市| 呈贡县| 云林县| 宝应县| 乐平市| 五大连池市| 峨眉山市| 广元市| 三台县| 章丘市| 桐庐县| 额尔古纳市| 缙云县| 辽中县| 冀州市| 扶绥县| 博罗县| 宁安市| 苗栗县| 拜泉县| 正安县| 天镇县| 汝阳县| 宕昌县|