实现异步多线程下载文件

来源:互联网 发布:矩阵化为行最简形 编辑:程序博客网 时间:2024/05/17 07:02

我是基于一名大神的思路写的,如果想看更多内容,下面大神的blog地址
http://blog.csdn.net/shimiso/article/details/6763664

xml文件

<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">    <ProgressBar        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/progressbar1"        style="?android:attr/progressBarStyleHorizontal"/>    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="textview1"        android:id="@+id/textview1"/>    <ProgressBar        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/progressbar2"        style="?android:attr/progressBarStyleHorizontal"/>    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="textview1"        android:id="@+id/textview2"/></LinearLayout>

Activity

public class MainActivity extends AppCompatActivity {    private TextView textView1,textView2;    private ProgressBar progressBar1,progressBar2;    //文件存储地址    private String downLoadingpath= Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator;    //下载地址    private String downloadingFile1="http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3";    private String downloadingFile2="http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3";    //声明已经读过的长度变量    private int hasRead=0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView1= (TextView) findViewById(R.id.textview1);        textView2= (TextView) findViewById(R.id.textview2);        progressBar1= (ProgressBar) findViewById(R.id.progressbar1);        progressBar2= (ProgressBar) findViewById(R.id.progressbar2);        downLoad(downloadingFile1,downLoadingpath,progressBar1,textView1);        downLoad(downloadingFile2,downLoadingpath,progressBar2,textView2);    }    private void downLoad(String url,String targetPath,ProgressBar pb,TextView textView)    {            DownloadThread downloadThread=new DownloadThread(url,targetPath,pb,textView);        downloadThread.start();    }    //自定义Handler类处理线程消息    public class MyHandler extends Handler{        private ProgressBar pb;        private TextView textView;        public MyHandler(ProgressBar pb, TextView textView) {            this.pb = pb;            this.textView = textView;        }        @Override        public void handleMessage(Message msg) {            this.pb.setProgress(msg.arg1);            this.textView.setText(msg.arg1+"%");            super.handleMessage(msg);        }    }    public  class DownloadThread extends Thread{        String url="";        private String targetPath="";        private int hasDownLoad=0;        private int len=-1;        private byte buffer[]=new byte[4*1024];        private int size=0;        //下载速度        private int rate=0;        private MyHandler myHandler=null;        private Message msg=null;        private ProgressBar pb=null;        private TextView textView=null;        public DownloadThread(String url, String targetPath, ProgressBar pb, TextView textView) {            this.url = url;            this.targetPath = targetPath;            this.pb = pb;            this.textView = textView;            myHandler=new MyHandler(this.pb,this.textView);        }        @Override        public void run() {            String targetFileName=this.targetPath                    +this.url.substring(this.url.lastIndexOf("/")                    +1,this.url.length());            File downloadFile=new File(targetFileName);            if (!downloadFile.exists())            {                try {                    downloadFile.createNewFile();                } catch (IOException e) {                    e.printStackTrace();                }            }            try {                URL fileUrl=new URL(this.url);                HttpURLConnection conn= (HttpURLConnection) fileUrl.openConnection();                //获取文件大小                size=conn.getContentLength();                InputStream is=conn.getInputStream();                OutputStream os=new FileOutputStream(targetFileName);                while ((len=is.read(buffer))!=-1)                {                    os.write(buffer);                    hasDownLoad+=len;                    rate=(hasDownLoad*100/size);                    msg=new Message();                    msg.arg1=rate;                    myHandler.sendMessage(msg);                    Log.e("rate----------",rate+"%");                }                } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {            }        }    }}

这是最基础的写法,基于handler更新UI,使用httpurlconnection下载文件内容,然后进行文件保存操作。
这里写图片描述

就截取了一部分下载过程。

0 0
原创粉丝点击