Android的多線程下載功能(核心代碼)

public  class  MainActivtiy  extends Activity{android

       private EditText  et_path;dom

       private  LinearLayout  ll_container;ide

       private  int  threadCount=3;this

       private   int   runningThreadCount=3;url

    @override線程

        protectd   void  onCreate(Bundle  saveInstanceState)日誌

    {    //初始化控件code

        setContentView(R.layout.activity_main);xml

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

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

        pds=new  ArrayList<ProgerssBar>();   //這裏定義一個集合,用來裝多個線程

     }    //單擊下載按鈕時,要調用的方法

 public  void  download(View view)

  {

     final  String  path=et_path.getText( ).toString( ).trim( );  //獲取路徑

     for(int  i=0;i<threadCount ;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<threadCount; 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();
               }
          });
 }

  }

}

相關文章
相關標籤/搜索