Tôi cũng gặp phải sự cố tương tự và đã giải quyết vấn đề này với vấn đề này. Hãy thử điều này
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(img_URL);
/* 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();
}
}
}
Tuyên bố hoạt động mạng của bạn trong AsyncTask vì nó sẽ tải nó dưới dạng tác vụ nền. Không tải hoạt động mạng trên luồng chính. Sau đó một trong hai nút bấm hoặc theo quan điểm cuộc gọi nội dung lớp này như
new ImageDownloadAndSave().execute("");
Và đừng quên thêm quyền nework như:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Hy vọng điều này có thể giúp một người nào đó :-)
Và bạn nhận được lỗi nào? – Cristian
Bạn đã thử tải một hình ảnh hiện có bằng cách sử dụng createFromPath? – Ankit
Đó là trong một tuyên bố try-catch, thiết lập nó để null nếu nó không thành công. Tôi chưa thử nghiệm một hình ảnh khác. Tôi đang sử dụng Trình mô phỏng – Jamie