多線程JAVA代碼移植到android

來源:互聯網
上載者:User

標籤:android   多線程   

public class MainActivity extends Activity {
    protected static final int DOWN = 0;
    protected static final int SEER = 1;
    private Context context;
    private EditText ed;
    private ProgressBar pb;
    public static int threadcount=3;
    public static int runnling=3;
    public int  cureatProcess=0;//當前進度
    private Handler handler =new Handler(){
        public void handleMessage(android.os.Message msg) {
         switch (msg.what) {
        case  DOWN:
            Toast.makeText(getApplicationContext(), "下載錯誤", 0).show();
            break;

        case SEER:
            Toast.makeText(getApplicationContext(), "下載失敗", 0).show();
            break;
        }
            
            
        };
        
        
        
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed=(EditText)findViewById(R.id.ed_path);
        pb=(ProgressBar)findViewById(R.id.pb);
    }

    
    public void paly(View view){
        final String path=ed.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(getApplicationContext(), "請輸入地址", 0).show();
            return;
            
        }
        new Thread(){
            public void run(){
                
                //String path="http://down9.869v.com/setup_445.exe";
                 try {
                    URL url=new URL(path);
                             HttpURLConnection con= (HttpURLConnection) url.openConnection();
                              con.setReadTimeout(6000);
                              con.setRequestMethod("GET");
                           int code= con.getResponseCode();
                           if(code==200){
                              int length= con.getContentLength();//已經設定了請求的位置//返回的是當前位置對應檔案的輸入資料流
                              pb.setMax(length);//擷取進度條最大值
                              RandomAccessFile raf=new RandomAccessFile((/"sdscard"/+"421.exe", "rwd");//記錄當前線程下載的資料長度
                              raf.close();
                              
                              //System.out.print("檔案長度:"+length);
                               int bolak =length/threadcount;
                               for(int threadID=1;threadID<=threadcount;threadID++){
                                   int starIndex=(threadID-1)*bolak;
                                   int endIndex=threadID*bolak-1;
                                   if(threadID==threadcount){
                                       endIndex=length;
                                    
                                       
                                   }
                                   System.out.println("線程"+threadID+"下載---->"+starIndex+"----->"+endIndex);
                                   new MyThread(path, threadID, starIndex, endIndex).start();
                               }
                           }else{
                               System.out.print("讀取長度失敗");
                               Message msg=new Message();
                               handler.sendMessage(msg);
                               msg.what=SEER;
                           }
                } catch (Exception e) {
            e.printStackTrace();
            Message msg=new Message();
            handler.sendMessage(msg);
            msg.what=DOWN;
            
                }
                
            }
            
            
            
        }.start();
        
        
        
    }
     public  class MyThread extends Thread{
           public MyThread(String path, int threadID, int starIndex, int endIndex) {
            super();
            this.path = path;
            this.threadID = threadID;
            this.starIndex = starIndex;
            this.endIndex = endIndex;
        }
        private String path;  
           private int threadID;
           private int starIndex;
           private int endIndex;
        
        
        
    
      public void run(){
           
        try {
            //檢查是否在記錄下載長度的檔案 如果存在讀取這個檔案的資料
           File tempFile =new File(context.MODE_PRIVATE+threadID+".txt");
            if(tempFile.exists()&&tempFile.length()>0){
            FileInputStream fis=new FileInputStream(tempFile);
            byte[] tpem=new byte[1024];
            int leng =fis.read(tpem);
            String dowmlod =new String(tpem,0,leng);
            int downlodalenInt= Integer.parseInt(dowmlod);
            int alreadyDown =downlodalenInt-starIndex;
            cureatProcess+=alreadyDown;//計算上次斷點已經下載的值
            starIndex=downlodalenInt;//修改下載的真實開始位置
            fis.close();
            }    
            
            URL url=new URL(path);
           HttpURLConnection con =(HttpURLConnection) url.openConnection();
           con.setRequestMethod("GET");
           con.setRequestProperty("Range", "byte="+starIndex+"-"+endIndex);
           System.out.println("線程真實下載位置"+threadID+"下載----"+starIndex);
           con.setReadTimeout(8000);
           
           int code=con.getResponseCode();
           System.out.println("code"+code);
           InputStream is= con.getInputStream();
           RandomAccessFile raf=new RandomAccessFile((/"sdscard"/+"421.exe", "rwd");
           raf.seek(starIndex);
           int len=0;
           byte[]buffer=new byte[1024];
           int total=0;
           while((len=is.read(buffer))!=-1){
             RandomAccessFile flie =new RandomAccessFile((/"sdscard"/+threadID+".txt ","rwd");
             raf.write(buffer,0,len);
               total+=len;
               System.out.println("線程"+threadID+"total:"+total);
              flie.write((total+starIndex+"").getBytes());//記錄下載的位置
              flie.close();
              synchronized (MainActivity.this) {
                cureatProcess+=len;//記錄當前總進度
                pb.setProgress(cureatProcess);
                   
            }
           }
           is.close();
           raf.close();
           System.out.println("線程ID"+threadID+"下載完畢......");
        } catch (Exception e) {
            
            e.printStackTrace();
        }finally{
            threadFins();
            
        }
          
      }




    private synchronized void threadFins() {
        runnling--;
        if(runnling==0){
            for(int i=1 ;i<=3;i++){
                File file=new File(/"sdscard"/+i+".txt");
                file.delete();
                
            }
            System.out.println("檔案下載半壁刪除所有下載記錄");
        }
    }
      }
    
    
}

多線程JAVA代碼移植到android

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.