我正在使用字符串數組來保存圖像,我從URL中獲取圖像。我有一個imageview,當它被移動時會改變其中的圖像。現在我想下載並保存SD卡上的任何圖像,並希望它出現在手機庫中的新文件夾中。將字符串數組中的圖像保存到SD卡和手機庫
我使用下面的代碼,但它不工作,它沒有顯示任何錯誤。
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... arg0) {
downloadImagesToSdCard("", "");
return null;
}
private void downloadImagesToSdCard(String downloadUrl, String imageName) {
try {
URL url = new URL(thumb[j]);
/* making a directory in sdcard */
String sdCard = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(sdCard, "test.jpg");
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File(myDir, fname);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadedSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
} catch (IOException io) {
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
,我通過
new ImageDownloadAndSave().execute("");
執行它在我的字符串數組的名稱是「大拇指」,這是保持所有的URL。我究竟做錯了什麼?
您需要將文件添加到'MediaStore'。看看我的答案[這裏](http://stackoverflow.com/a/29947838/4193263)。 – ByteHamster
@ByteHamster應該把它放在一個方法或什麼,我應該如何初始化和執行它? –
使用文件管理器(例如「Astro」)時能看到文件嗎? – ByteHamster