2012-07-06 78 views
0

我有一個問題,試圖讓我的android手機.png圖像。 我現在這個地步:如何獲取.png到Android手機(external_sd)

URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png"); 
    InputStream input = url.openStream(); 
    try { 
    String storagePath = Environment.getExternalStorageDirectory(); 
    OutputStream output = new FileOutputStream (storagePath + "/oranjelangbg.png"); 
    try { 
    byte[] buffer = new byte[1000000]; 
     int bytesRead = 0; 
     while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
     output.write(buffer, 0, bytesRead); 
     } 
    } finally { 
     output.close(); 
     } 
    } finally { 
    input.close(); 
} 

但我得到以下錯誤:STRING storagePath = Environment.getExternalStorageDirectory();壓縮機說不能將文件轉換爲字符串。

然後,如果我愚弄了一下,試試這段代碼:

URL url; 

    void setup() { 
    try { 

     URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png"); 
     InputStream input = url.openStream();{ 
     try { 

      String storagePath = Environment.getExternalStorageDirectory().getName(); 
      OutputStream output = new FileOutputStream (storagePath + "/oranjelangbg.png"); 
       try { 


byte[] buffer = new byte[1000000]; 
        int bytesRead = 0; 
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
        output.write(buffer, 0, bytesRead); 
        } 
        } finally { 
      output.close(); 
      } 
      } catch (IOException e) { 
      // TODO Auto-generated catch block 
      throw new RuntimeException(e); 
    } finally { 
     try { 
      input.close(); 
      } catch (IOException e) { 
      // TODO Auto-generated catch block 
      throw new RuntimeException(e); 
    } 
    }  
}  
    } catch (MalformedURLException ex) { 
     throw new RuntimeException(ex); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     throw new RuntimeException(e); 
    } 
    } 
} 

那麼我的Android凍結當我啓動應用程序。

有沒有人有任何想法?

+0

很多很多謝謝你的回覆,我現在必須退出,並且會在星期一回來,然後回覆並查看此信息。 – 2012-07-06 15:31:32

+0

嘗試下載不同線程中的圖像。它會克服凍結問題.. – AAnkit 2012-07-06 15:36:10

+0

非常感謝你們,我想我現在就能得到它,所有的芒果都很好!並幫助我很多! – 2012-07-09 07:48:06

回答

2

除了什麼Tanis.7x指出的那樣,你將需要移動網絡運營脫離UI線程並進入諸如AyncTask之類的東西。否則,您將無法與應用程序進行交互,直到完成下載爲止 - 這可能會導致應用程序無響應的消息和強制關閉。在最近的android版本中,在主線程上進行聯網是一種自動異常,即使它不會導致延遲。

1

查看Environment.getExternalStorageDirectory()的文檔。

它返回一個File(java.io.File),而不是一個String。

我用線沿線的東西:

File storagePath = Environment.getExternalStorageDirectory(); 
File outFile = new File(storagePath, filename + FILE_EXTENSION); 
OutputStream outStream = new FileOutputStream(outFile); 
+0

爲什麼這會降低投票率? – 2012-07-06 15:25:04

+1

@Ankit - 不要downvote準確的部分答案,除非他們聲稱是完整的。我可以輕而易舉地爲您的巨大遺漏而回應您的答案,但不會。 – 2012-07-06 15:31:49

+1

我爲澄清添加了一個代碼示例,但該消息的原始內容仍然相關,應該已經圓滿地回答了問題。 – 2012-07-06 15:33:18

0

嘗試是這樣的..

File storagePath = new File(Environment.getExternalStorageDirectory()+ "/oranjelangb.png"); 
OutputStream output = new FileOutputStream (storagePath.getAbsoluteFile());