2014-12-30 41 views
0

我從我的android應用下載zip文件。點擊下載按鈕後,活動停止。以下是下載zip文件的代碼。嘗試從url下載zip文件時停止活動

下載代碼:

public void myDownload(View v) { 


      URL url; 
      try { 
       url = new URL("https://github.com/jquery/jquery/archive/master.zip"); 
       try { 
        InputStream in = url.openStream(); 
        FileOutputStream fos = new FileOutputStream(new File("Master.zip")); 
        System.out.println("Reading the file."); 
        int length = -1; 
        byte[] buffer = new byte[1024];// buffer for portion of data from 
        // connection 
        while ((length = in.read(buffer)) > -1) { 
         fos.write(buffer, 0, length); 
        } 
        fos.close(); 
        in.close(); 
        System.out.println("File Downloaded"); 

       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

} 

感謝您的幫助!

+0

請分享日誌 – user1767260

+0

我認爲它的NetworkOnMainThread,更好的是你把這段代碼放在一個單獨的AsyncTask –

回答

0

@ usd123:你是否得到某種例外。根據你的代碼,事情似乎很好。唯一的問題,我猜你可能會連接到主UI線程上導致ANR(活動無響應)的特定URL。根據Android文檔,網絡讀/寫任務不應在主UI線程上執行。他們需要通過異步任務或通過服務來完成。 請閱讀 http://developer.android.com/reference/android/os/StrictMode.html 希望這會有所幫助!

+0

非常感謝。這對我非常有幫助。 – usd123

0

您不應該在主線程中調用Internet /網絡調用。嘗試使用AsyncTask將其從主線程運行並使用Handlers更新UI。

+0

非常感謝。這些信息對我有幫助。 – usd123