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 に答える