2012-07-06 51 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());