Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
public void fetchImage(final Activity activity, final int cacheTime, final String url, final ImageView iView) {
if (iView != null) {
if (findObject(iView)) {
return;
}
downloaded.add(iView);
}
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
return downloadImage(activity, cacheTime, iUrl[0], iView);
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(new String[] { url });
}
} catch (Exception e) {
e.printStackTrace();
}public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
private String url;
private final WeakReference<ImageView> imageViewReference;
public ImageDownloader(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
// эта функция качает файло
@Override
protected Bitmap doInBackground(String... params) {
url = params[0];
URL myFileUrl = null;
HttpURLConnection conn;
InputStream is;
try {
myFileUrl= new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
try {
conn = (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
return BitmapFactory.decodeStream(is);
catch (Exception e)
{
e.printStackTrace();
is = null;
conn = null;
return null;
}
}
// эта функция показывает скачанный файл в ImageView
@Override
protected void onPostExecute(Bitmap result) {
if (isCancelled()) {
result = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
}
}
}
// Эта функция вызывается для того, чтобы показать пользователю что-то, пока грузится картинка.
// Например песочные часы или лучше прогрессбар
@Override
protected void onPreExecute() {
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageResource(R.drawable.icon);
}
}
}
}
ImageView iv;
ImageDownloader downloader = new ImageDownloader(iv);
downloader.execute(pictureURL);
conn = (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
return BitmapFactory.decodeStream(is);
HttpGet req = null;
req = new HttpGet(url);
HttpClient _client = new DefaultHttpClient();
HttpResponse resp = (HttpResponse) _client.execute(req);
HttpEntity entity = resp.getEntity();
BufferedHttpEntity buffered_entity = new BufferedHttpEntity(entity);
InputStream is = buffered_entity.getContent();
BitmapFactory.decodeStream(is);
Кеширование изображений на SD карте