各位高手,我用android做一个远程图片下载的功能,在网上找的资料,但是资料中有个downloadBitmap(params[0])的方法没有,请问有哪位能提供下这个方法吗?或者给个能用的下载图片代码也行。在线等,很急呀,有结果马上结贴。谢谢了!代码如下public class ImageDownloader {
public void download(String url, ImageView imageView) {
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(url);
}
}
class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private String url;
private final WeakReference<ImageView> imageViewReference; //使用WeakReference解决内存问题
public BitmapDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) { //实际的下载线程,内部其实是concurrent线程,所以不会阻塞
return downloadBitmap(params[0]);//这个方法没有啊。。 }
@Override
protected void onPostExecute(Bitmap bitmap) { //下载完后执行的
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap); //下载完设置imageview为刚才下载的bitmap对象
}
}
}
}
public void download(String url, ImageView imageView) {
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(url);
}
}
class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private String url;
private final WeakReference<ImageView> imageViewReference; //使用WeakReference解决内存问题
public BitmapDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) { //实际的下载线程,内部其实是concurrent线程,所以不会阻塞
return downloadBitmap(params[0]);//这个方法没有啊。。 }
@Override
protected void onPostExecute(Bitmap bitmap) { //下载完后执行的
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap); //下载完设置imageview为刚才下载的bitmap对象
}
}
}
}
private Bitmap downloadBitmap(String taskUrl){
InputStream stream = null;
URL imageUrl;
Bitmap bmp = null; try {
imageUrl = new URL(taskUrl);
try {
stream = imageUrl.openStream();
bmp = BitmapFactory.decodeStream(stream);
try {
if(bmp != null){
//一般来说这里可以把图片放入haspmap,避免重复下载
} else {
//Log.v(tag, msg)
}
} catch (NullPointerException e) {
//Log.v(tag, msg)
}
} catch (IOException e) {
} finally {
try {
if(stream != null){
stream.close();
}
} catch (IOException e) {}
} } catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
//一般来说这里可以把图片放入haspmap,避免重复下载写错了哈,是放入HashMap(用WeakHashMap冒似要安全些)。