URLConnection,单线程下载,多线程下载

在UI主线程中是不允许进行耗时操作的,像连接服务器,下载等操作都是耗时操作,不可以在UI主线程中进行,必须在子线程中进行。

URLConnection

URLConnection获得服务器的反应。代码如下:

  try {
            URL url = new URL("http://192.168.0.43:8080/www/MyserverTest");
            URLConnection connection = url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line= reader.readLine();
            reader.read();

            StringBuffer s= new StringBuffer();
            while (line!=null){
                Log.d("",line);
               s.append(line);
                line=reader.readLine();
            }
            Message message =handler.obtainMessage();
            message.what=URL_NET;
            message.obj=s.toString().trim();
            handler.sendMessage(message);
            reader.close();
            is.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意连接服务器是需要声明权限的:

 <uses-permission android:name="android.permission.INTERNET"/>

单线程下载

下载就是获得服务器的资源。
这里我们用AsyncTask机制下载和更新进度条。代码如下:

 class MyAsyncTask extends AsyncTask<String,Integer,String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL("http://192.168.0.43:8080/www/music/sj.mp3");
                URLConnection connection = url.openConnection();
                int length=connection.getContentLength();//获得内容的长度
                InputStream in = connection.getInputStream();
                File file = new File(Environment.getExternalStorageDirectory(),"/sj.mp3");
                if(!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream os = new FileOutputStream(file);
                byte[]array = new byte[1024];
                int sum = 0;
                int index = in.read(array);//返回读取的字节数
                while (index!=-1){
                    sum+=index;
                    os.write(array,0,index);//把数组的值写入对应的文件中
                    publishProgress(sum,length);//传给onProgressUpdate()的参数,使其更新进度条
                    index=in.read(array);
                }
                os.flush();
                os.close();
                in.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBar.setVisibility(View.INVISIBLE);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress((int)(values[0]*100.0/values[1]));
        }
    }

在启动按钮的点击事件中:

   MyAsyncTask myAsyncTask =new MyAsyncTask();
                myAsyncTask.execute("dd");//dd是随便写的。是传给doInBackground()的参数

注意:

Handler机制与AsyncTask都不是在onCreat()机制中进行的。

多线程下载

多线程下载就不可以用AsyncTask机制了。必须用Handler机制。启动多线程,为每一个线程的下载设定开始和结束点。代码如下:
在Activity中按钮的点击事件中:

 new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String path="http://192.168.0.43:8080/www/music/sj.mp3";
                            URL url = new URL(path);
                            URLConnection connection = url.openConnection();
                             length=connection.getContentLength();
                            File file = new File(Environment.getExternalStorageDirectory(),"/sj.mp3");
                            if(!file.exists()){
                                file.createNewFile();
                            }
                             array =new Item_Thread[5];
                            for(int i =0;i<5;i++){
                                if(i==4){

                                  thread=new Item_Thread(length/5*i,length,path,file.getAbsolutePath());
                                    array[4]=thread;
                                }else {
                                    thread= new Item_Thread(length/5*i,length/5*(i+1),path,file.getAbsolutePath());
                                    array[i]=thread;
                                }
                              thread.start();

                            }
                            boolean isfinish=false;
                            while (!isfinish){

                                for(Item_Thread thread : array){
                                    sum+=thread.getSum();
                                }
                                Message message = handler.obtainMessage();
                                message.what=PRO;
                                message.arg1=sum;
                                handler.sendMessage(message);
                                if(length<=sum+10){
                                    isfinish=true;

                                    thread.sleep(1000);
                                }
                            }


                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;

Handler机制的代码:

 Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case PRO:
                    progressBar.setProgress(msg.arg1);
                    if(length<=msg.arg1+10){
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                    break;
            }
        }
    };

在子线程中:

public class Item_Thread extends Thread {

    private long start;
    private long end;
    private String urlpath;
    private  String filePath;
    private  int sum;

    public int getSum() {
        return sum;
    }

    public Item_Thread(long start,long end, String urlpath,String filePath) {
        this.end = end;//下载的结束点
        this.filePath = filePath;//下载到的文件路径
        this.start = start;//下载的开始点
        this.urlpath = urlpath;//下载文件的路径
    }



    @Override
    public void run() {
        try {
            URL url = new URL(urlpath);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Range","bytes="+start+"-"+end);//设置下载的开始点与结束点
            InputStream in = connection.getInputStream();
            File file = new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
            randomAccessFile.seek(start);//设置下载到文件的开始点。
            byte[]array = new byte[1024];
            sum = 0;
            int index = in.read(array);//返回读取的字节数
            while (index!=-1){
                sum+=index;
                randomAccessFile.write(array,0,index);//把数组的值写入对应的文件中

                index=in.read(array);
            }

            randomAccessFile.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

这样就结束了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值