真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Android使用HttpURLConnection實(shí)現(xiàn)多線程下載

工具類代碼:

成都創(chuàng)新互聯(lián)專業(yè)提供綿陽電信機(jī)房機(jī)柜租用服務(wù),為用戶提供五星數(shù)據(jù)中心、電信、雙線接入解決方案,用戶可自行在線購買綿陽電信機(jī)房機(jī)柜租用服務(wù),并享受7*24小時(shí)金牌售后服務(wù)。

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數(shù)組
        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");
        // 設(shè)置本地文件的大小
        file.setLength(fileSize);
        file.close();
        for (int i = 0; i < threadNum; i++)
        {
            // 計(jì)算每條線程的下載的開始位置
            int startPos = i * currentPartSize;
            // 每個(gè)線程使用一個(gè)RandomAccessFile進(jìn)行下載
            RandomAccessFile currentPart = new RandomAccessFile(targetFile,
                    "rw");
            // 定位該線程的下載位置
            currentPart.seek(startPos);
            // 創(chuàng)建下載線程
            threads[i] = new DownThread(startPos, currentPartSize,
                    currentPart);
            // 啟動(dòng)下載線程
            threads[i].start();
        }
    }

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

    private class DownThread extends Thread
    {
        // 當(dāng)前線程的下載位置
        private int startPos;
        // 定義當(dāng)前線程負(fù)責(zé)下載的文件大小
        private int currentPartSize;
        // 當(dāng)前線程需要下載的文件塊
        private RandomAccessFile currentPart;
        // 定義已經(jīng)該線程已下載的字節(jié)數(shù)
        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個(gè)字節(jié),表明該線程只下載自己負(fù)責(zé)哪部分文件。
                inStream.skip(this.startPos);
                byte[] buffer = new byte[1024];
                int hasRead = 0;
                // 讀取網(wǎng)絡(luò)數(shù)據(jù),并寫入本地文件
                while (length < currentPartSize
                        && (hasRead = inStream.read(buffer)) > 0)
                {
                    currentPart.write(buffer, 0, hasRead);
                    // 累計(jì)該線程下載的總大小
                    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);
        // 創(chuàng)建一個(gè)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對象 最后一個(gè)參數(shù)指定線程數(shù)
                downUtil = new DownUtil(url.getText().toString(),
                        target.getText().toString(), 6);
                new Thread()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            // 開始下載
                            downUtil.download();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        // 定義美妙調(diào)度獲取一次系統(tǒng)的完成進(jìn)度
                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask()
                        {
                            @Override
                            public void run()
                            {
                                // 獲取下載任務(wù)的完成比例
                                double completeRate = downUtil.getCompleteRate();
                                mDownStatus = (int) (completeRate * 100);
                                handler.sendEmptyMessage(0x123);
                                // 下載完成后取消任務(wù)調(diào)度
                                if (mDownStatus >= 100)
                                {
                                    timer.cancel();
                                }
                            }
                        }, 0, 100);
                    }
                }.start();
            }
        });
    }
}

Android 使用HttpURLConnection 實(shí)現(xiàn)多線程下載


網(wǎng)站標(biāo)題:Android使用HttpURLConnection實(shí)現(xiàn)多線程下載
文章鏈接:http://weahome.cn/article/ggsggh.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部