0

Android 如何使用 Environment.getExternalStorageDirectory()

如何使用 Environment.getExternalStorageDirectory() 从 SD 卡读取/写入图像?或者有更好的方法吗?

我确实使用源下载e保存图像:

    try {

        URL url = new URL(urlBaseImagem + icone);
        URLConnection conection = url.openConnection();
        conection.connect();
        // this will be useful so that you can show a tipical 0-100% progress bar
        int lenghtOfFile = conection.getContentLength();

        //
        // download the file
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream                
        //File sdCard = Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE);
        File sdCard = Environment.getExternalStorageDirectory();

        File directory = new File(sdCard.getAbsolutePath() + "/cardapioweb/rest/");

        if(directory.exists() == false){
            directory.mkdirs();
        }
        File outputFile = new File(directory, icone);

        OutputStream output = new FileOutputStream(outputFile);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            //publishProgress(""+(int)((total*100)/lenghtOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();

        Log.w("CardapioWeb:" , "Imagem " + outputFile.toString() + " salva no sdcard");


    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

我确实使用源来加载 e 显示图像:

File arq = new File(this.sdCard.getAbsolutePath() + "/cardapioweb/rest/" + filialDataCollection.get(position).get(KEY_ICONE));

//verifica se a imagem foi baixada com sucesso
if(arq.exists() == true){
        //deve exibir a imagem do sdcard
        File outputFile1 = new File(this.sdCard.getAbsolutePath() + "/cardapioweb/rest/", filialDataCollection.get(position).get(KEY_ICONE));
        Drawable imagem = Drawable.createFromPath(outputFile1.toString());
        holder.tvWeatherImage.setImageDrawable(imagem);
 }

上面的代码在带有 Eclipse 的模拟器(Android 虚拟设备)上工作得很好!!!!但是当我生成 apk 并安装在我的 Galaxy S4 上时,该应用程序无法读取图像(没有生成错误)。只是不显示图像。有什么问题?

4

1 回答 1

0

在您的代码中输入日志以查看内容

outputFile1.toString();

实际上指向的是,它是你所期望的吗?

就个人而言,我会使用 outputFile1.getAbsolutePath(); 不是下面的行:

Drawable imagem = Drawable.createFromPath(outputFile1.toString());
于 2013-08-28T15:33:41.817 回答