Android如何使用Environment.getExternalStorageDirectory()
如何使用Environment.getExternalStorageDirectory()从SD卡读取/写入图像?或者有更好的方法吗?
我确实使用了源代码来保存图片:
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上时,应用程序无法读取图像(不会生成错误)。只是不显示图像。可能有什么不对?
答案 0 :(得分:0)
在代码中记录以查看
outputFile1.toString();
实际上指出,这是你所期望的吗?
就个人而言,我会使用outputFile1.getAbsolutePath();不是下面的一行:
Drawable imagem = Drawable.createFromPath(outputFile1.toString());