Android的多线程下载功能(核心代码)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

public  class  MainActivtiy  extends Activity{

       private EditText  et_path;

       private  LinearLayout  ll_container;

       private  int  threadCount=3;

       private   int   runningThreadCount=3;

    @override

        protectd   void  onCreate(Bundle  saveInstanceState)

    {    //初始化控件

        setContentView(R.layout.activity_main);

        et_path=(EditText)findViewById(R.id.et_path);

        ll_container=(LinearLayout) findViewById(R.id.ll_container);

        pds=new  ArrayList();   //这里定义一个集合,用来装多个线程

     }    //单击下载按钮时,要调用的方法

 public  void  download(View view)

  {

     final  String  path=et_path.getText( ).toString( ).trim( );  //获取路径

     for(int  i=0;i

         //加载自己写的子xml, 并放到容器中

         ProgressBar  pb=(ProgressBar) View.inflate(MainActivity.this , R.layout.pb , null);

         ll_container.addView(pd);

        pbs.add(pb);

      }   //4.0以后不能在主线程中联网

  new   Thread()

  { public void  run()

         try    {   

                   URL  url=new  URL(path);

                  HttpURLConnection  con=(HttpURLConnection)url.openConnection();

                  con.setRequestMethod("GET");

                  con.setConnectionTimeout(20000);

                 int  code=con.getResponseCode( );

                 if(code==200)   //请求成功,先不下载,先利用randomAccessFile创建一个一样的文件

                           {  int  length=con.getContentLength( );

                              RandomAccessFile   raf=new  RandomAccessFile("/data/data/cn.my.download/a.exe","rwd");

                              raf.setLength(length);

                              raf.close( );   //计算每个线程下载的大小 ,平均值

                              int blockSize=length/threadCount;

                              for(int  threadId=0; threadId

                                   int  startIndex=threadId* blockSize;

                                   int  endIndex=(threadId+1)*blocksize-1;

                                              if(threadId==threadCount-1)

                                                      {   //最后 一个线程

                                                          endIndex=length-1;

                                                      }

                              }else{

                                    showToast("请求失败");

                               }

                       }catch(Exception  e)

                         { e.printStackTrace ( );

                          showToast("请看日志");

                       }                     

                     }

                 }.start();

  public  void  showToast(String  result)  

       { Toast.makeText(MainActivity.this , result , 0).show( ); }

  public  class DownLoadThrea  extends  Thread

   {

    private  int  threadId;

    private   int  startIndex;

     private  int  endIndex;

     Private   String   path;

    public DownloadThread(int threadId, int startIndex, int endIndex,String path) {
       super();
       this.threadId = threadId;
       this.startIndex = startIndex;
       this.endIndex = endIndex;
       this.path = path;
  }

@override

    public void  run(){

           try{  URL  url=new  URL(path);

                    HttpURLConnection  con=(HttpURLConnection)url.openConnection( );

                    con.setRequestMethod("GET");

                    con.setConnectionTimeout(2000);

                   conn.setRequestProperty("Range","bytes=" + startIndex + "-" + endIndex);

                     int  code=con.getResponseCode( );

                    if(code=206)

                      RandomAccessFile raf = new RandomAccessFile("data/data/cn.my.myandroid_download/aa.exe","rwd");
                 raf.seek(startIndex);
                 InputStream is = conn.getInputStream();
                 int len = 0;
                 int max = endIndex - startIndex;
                 int currentSize = 0;
                 byte[] bys = new byte[1024];
                 while((len = is.read(bys)) != -1) {
                  raf.write(bys,0,len); 
      //每下载一个字节就更新进度条一次
      //设置进度条的最大值
              pbs.get(threadId).setMax(max);
        //设置当前进度
              currentSize += len;   
              pbs.get(threadId).setProgress(currentSize);
     }
             is.close();
             raf.close();     
             synchronized(MainActivity.class) {
                      runningThreadCount--;
                      if(runningThreadCount <= 0) {
                       showToast("下载完成");
              }
     }
     
    }else { showToast("请求失败,原因" + code);  }
   } catch (Exception e) {
        e.printStackTrace();
        showToast("请求失败,请查看日志猫");
   }
  }catch(Exception  e){

               e.printStaceTrace();

             }

      }

            public void showToast(final String result) {
              runOnUiThread(new Runnable() {   
               @Override
               public void run() {
                Toast.makeText(MainActivity.this, result, 0).show();
               }
          });
 }

  }

}

转载于:https://my.oschina.net/u/1792000/blog/403639

你可能感兴趣的:(Android的多线程下载功能(核心代码))