0

我在尝试将 .png 图像发送到我的 Android 手机时遇到问题。我现在这么远:

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 冻结了。

有没有人有任何想法?

4

3 回答 3

2

除了 Tanis.7x 指出的内容之外,您还需要将网络操作移出 UI 线程并移入诸如 AyncTask 之类的东西中。否则,您将无法与应用程序交互,直到它完成下载 - 这可能会导致应用程序无响应消息和强制关闭。在最近的 android 版本中,在主线程上进行联网是一个自动异常,即使它不会导致延迟。

于 2012-07-06T15:32:11.187 回答
1

查看Environment.getExternalStorageDirectory()的文档。

它返回一个文件 (java.io.File),而不是一个字符串。

我使用以下内容:

File storagePath = Environment.getExternalStorageDirectory();
File outFile = new File(storagePath, filename + FILE_EXTENSION);
OutputStream outStream = new FileOutputStream(outFile);
于 2012-07-06T15:22:55.770 回答
0

试试这样的..

 File storagePath = new File(Environment.getExternalStorageDirectory()+ "/oranjelangb.png");
 OutputStream output = new FileOutputStream (storagePath.getAbsoluteFile());
于 2012-07-06T15:25:26.877 回答