如何从网址使用的AsyncTask设置的图像? [英] How to set image from Url using AsyncTask?

查看:131
本文介绍了如何从网址使用的AsyncTask设置的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手程序员的我正在上的ImageView从给定的URL显示图像的Andr​​oid程序。我的问题是你怎么用这个就AsyncTask的?

在分SDK 2.2这些$ C $政务司司长的工作,但我切换到最小的SDK 3.0,因此需要在AsyncTask的运行。感谢您的帮助! :)

 保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    卫星(); //从主菜单卫星图像

}

// ******卫星网址
私人无效卫星(){
    // TODO自动生成方法存根
    ImageView的imgView =(ImageView的)findViewById(R.id.satellite);
    可绘制绘制= LoadImageFromWeb(http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif);
    imgView.setImageDrawable(绘制);
}

私人绘制对象LoadImageFromWeb(字符串URL){
      尝试{
          InputStream的是=(InputStream的)新的网址(URL).getContent();
          绘制对象D = Drawable.createFromStream(是,SRC名);
          返回D组;
      }赶上(例外五){
          的System.out.println(EXC =+ E);
          返回null;
      }
}
 

解决方案

好了,我不知道为什么Android SDK中不提供对它的支持(但)我延长UrlImageView类ImageView的类异步加载和缓存的支持。我把我下面的类,它是即插即用的code。类的身体在我的帖子的末尾,现在我写的两行如何使用它方便的方法。

另外两种方法,现在支持:

  setImageUrl(网址URL)//通过URL设置位图
cancelLoading(); //告诉这个观点取消待处理的负载
 

如何使用您的基于Java code:

  // [放在你的活动]
UrlImageView urlImg =新UrlImageView(本).setImageUrl(HTTP://abc.png);
...
urlImg.setImageUrl(HTTP://abc2.png); //就像预期
 

如何绑定在你的布局:

 <! - 缩略图 - >
< com.gplushub.android.view.UrlImageView
    机器人:ID =@ + ID /缩略图
    机器人:layout_width =64dp
    机器人:layout_height =64dp
    机器人:layout_gravity =center_vertical
    机器人:layout_marginRight =2DP
    机器人:scaleType =fitXY/>
 

..并再次在您的活动的Java code:

 ((UrlImageView)findViewById(R.id.thumbnail))setImageUrl(HTTP://foo.bar.png)。
 

我用它在列表中有超过100项 - 丢得非常好。在这里,类体,您可以使用它,修改它,扩展它,不管你喜欢:

 包com.gplushub.android.view;

进口java.io.IOException异常;
进口的java.io.InputStream;
进口的java.net.URL;
进口java.net.URLConnection中;

进口android.content.Context;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.graphics.drawable.Drawable;
进口android.net.Uri;
进口android.os.AsyncTask;
进口android.util.AttributeSet;
进口android.util.Log;
进口android.widget.ImageView;

/ **
 *一个{@link ImageView的}从URL支持异步加载。额外
 *原料药:{@link #setImageURL(URL)},{@link #cancelLoading()}。
 *
 * @author ep@gplushub.com /尤金·普利思博士
 *
 * /
公共类UrlImageView扩展ImageView的{
  私有静态类UrlLoadingTask扩展的AsyncTask<网址,虚空,位图> {
    私人最终ImageView的更新视图;
    私人布尔isCancelled = FALSE;
    私人的InputStream urlInputStream;

    私人UrlLoadingTask(ImageView的更新视图){
      this.updateView =更新视图;
    }

    @覆盖
    受保护的位图doInBackground(网址... PARAMS){
      尝试 {
        URLConnection的CON = PARAMS [0] .openConnection();
        //可以多用一些参数,可以即缓存目录等
        con.setUseCaches(真正的);
        this.urlInputStream = con.getInputStream();
        返回BitmapFactory.de codeStream(urlInputStream);
      }赶上(IOException异常E){
        Log.w(UrlImageView.class.getName(),未能从载入图像+参数[0],E);
        返回null;
      } 最后 {
        如果(this.urlInputStream!= NULL){
          尝试 {
            this.urlInputStream.close();
          }赶上(IOException异常E){
            ; // 吞
          } 最后 {
            this.urlInputStream = NULL;
          }
        }
      }
    }

    @覆盖
    保护无效onPostExecute(位图的结果){
      如果(!this.isCancelled){
        //希望调用是线程安全的
        this.updateView.setImageBitmap(结果);
      }
    }

    / *
     *只记得我们被取消,没有同步必要
     * /
    @覆盖
    保护无效onCancelled(){
      this.isCancelled = TRUE;
      尝试 {
        如果(this.urlInputStream!= NULL){
          尝试 {
            this.urlInputStream.close();
          }赶上(IOException异常E){
            ;// 吞
          } 最后 {
            this.urlInputStream = NULL;
          }
        }
      } 最后 {
        super.onCancelled();
      }
    }
  }

  / *
   *跟踪装载任务取消
   * /
  私人的AsyncTask<网址,虚空,位图> currentLoadingTask;
  / *
   *只是同步
   * /
  私有对象loadingMonitor =新的对象();

  公共UrlImageView(上下文的背景下,ATTRS的AttributeSet,诠释defStyle){
    超(背景下,ATTRS,defStyle);
  }

  公共UrlImageView(上下文的背景下,ATTRS的AttributeSet){
    超(背景下,ATTRS);
  }

  公共UrlImageView(上下文的背景下){
    超(上下文);
  }

  @覆盖
  公共无效setImageBitmap(位图BM){
    cancelLoading();
    super.setImageBitmap(BM);
  }

  @覆盖
  公共无效setImageDrawable(绘制对象绘制){
    cancelLoading();
    super.setImageDrawable(绘制);
  }

  @覆盖
  公共无效setImageResource(INT渣油){
    cancelLoading();
    super.setImageResource(渣油);
  }

  @覆盖
  公共无效setImageURI(URI URI){
    cancelLoading();
    super.setImageURI(URI);
  }

  / **
   *负载从给定的URL图像
   *
   * @参数的URL
   * /
  公共无效setImageURL(网址URL){
    同步(loadingMonitor){
      cancelLoading();
      this.currentLoadingTask =新UrlLoadingTask(本).execute(URL);
    }
  }

  / **
   *取消挂起的图片加载
   * /
  公共无效cancelLoading(){
    同步(loadingMonitor){
      如果(this.currentLoadingTask!= NULL){
        this.currentLoadingTask.cancel(真正的);
        this.currentLoadingTask = NULL;
      }
    }
  }
}
 

I'm a newbie programmer an I'm making an android program that displays an image on ImageView from a given url. My problem is how do you use this on the AsyncTask?

These codes work on min SDK 2.2 but I switched to min SDK 3.0 so it needs to run on the AsyncTask. Thank you for your help! :)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    satellite(); //satellite's image from main menu

}

//******satellite url
private void satellite() {
    // TODO Auto-generated method stub
    ImageView imgView =(ImageView)findViewById(R.id.satellite);
    Drawable drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif");
    imgView.setImageDrawable(drawable);        
}

private Drawable LoadImageFromWeb(String url){
      try{
          InputStream is = (InputStream) new URL(url).getContent();
          Drawable d = Drawable.createFromStream(is, "src name");
          return d;
      }catch (Exception e) {
          System.out.println("Exc="+e);
          return null;
      }
}

解决方案

well, I dont know why android SDK does not provide support for it (yet) I extended the ImageView class by UrlImageView class with asynchronous loading and caching support. I put the code of my class below, which is plug and play. The class body is at the end of my post, now I write two lines how to use it the convenient way.

Two more methods now are supported:

setImageUrl(URL url) // sets the bitmap by its URL
cancelLoading();     // tell this view to cancel pending load

How to use your java-code:

// [somewhere in your activity]
UrlImageView urlImg = new UrlImageView(this).setImageUrl("http://abc.png");
...
urlImg.setImageUrl("http://abc2.png"); // works like expected

How to bind in your layouts:

<!-- thumbnail -->
<com.gplushub.android.view.UrlImageView
    android:id="@+id/thumbnail"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:layout_gravity="center_vertical"
    android:layout_marginRight="2dp"
    android:scaleType="fitXY" />

..and again in your activity java code:

((UrlImageView)findViewById(R.id.thumbnail)).setImageUrl("http://foo.bar.png");

I use it in lists with more than 100 entries - flinging very well. Here the class body, you can use it, modify it, extend it, whatever you like:

package com.gplushub.android.view;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

/**
 * an {@link ImageView} supporting asynchronous loading from URL. Additional
 * APIs: {@link #setImageURL(URL)}, {@link #cancelLoading()}.
 * 
 * @author ep@gplushub.com / Eugen Plischke
 * 
 */
public class UrlImageView extends ImageView {
  private static class UrlLoadingTask extends AsyncTask<URL, Void, Bitmap> {
    private final ImageView updateView;
    private boolean         isCancelled = false;
    private InputStream     urlInputStream;

    private UrlLoadingTask(ImageView updateView) {
      this.updateView = updateView;
    }

    @Override
    protected Bitmap doInBackground(URL... params) {
      try {
        URLConnection con = params[0].openConnection();
        // can use some more params, i.e. caching directory etc
        con.setUseCaches(true);
        this.urlInputStream = con.getInputStream();
        return BitmapFactory.decodeStream(urlInputStream);
      } catch (IOException e) {
        Log.w(UrlImageView.class.getName(), "failed to load image from " + params[0], e);
        return null;
      } finally {
        if (this.urlInputStream != null) {
          try {
            this.urlInputStream.close();
          } catch (IOException e) {
            ; // swallow
          } finally {
            this.urlInputStream = null;
          }
        }
      }
    }

    @Override
    protected void onPostExecute(Bitmap result) {
      if (!this.isCancelled) {
        // hope that call is thread-safe
        this.updateView.setImageBitmap(result);
      }
    }

    /*
     * just remember that we were cancelled, no synchronization necessary
     */
    @Override
    protected void onCancelled() {
      this.isCancelled = true;
      try {
        if (this.urlInputStream != null) {
          try {
            this.urlInputStream.close();
          } catch (IOException e) {
            ;// swallow
          } finally {
            this.urlInputStream = null;
          }
        }
      } finally {
        super.onCancelled();
      }
    }
  }

  /*
   * track loading task to cancel it
   */
  private AsyncTask<URL, Void, Bitmap> currentLoadingTask;
  /*
   * just for sync
   */
  private Object                       loadingMonitor = new Object();

  public UrlImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public UrlImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public UrlImageView(Context context) {
    super(context);
  }

  @Override
  public void setImageBitmap(Bitmap bm) {
    cancelLoading();
    super.setImageBitmap(bm);
  }

  @Override
  public void setImageDrawable(Drawable drawable) {
    cancelLoading();
    super.setImageDrawable(drawable);
  }

  @Override
  public void setImageResource(int resId) {
    cancelLoading();
    super.setImageResource(resId);
  }

  @Override
  public void setImageURI(Uri uri) {
    cancelLoading();
    super.setImageURI(uri);
  }

  /**
   * loads image from given url
   * 
   * @param url
   */
  public void setImageURL(URL url) {
    synchronized (loadingMonitor) {
      cancelLoading();
      this.currentLoadingTask = new UrlLoadingTask(this).execute(url);
    }
  }

  /**
   * cancels pending image loading
   */
  public void cancelLoading() {
    synchronized (loadingMonitor) {
      if (this.currentLoadingTask != null) {
        this.currentLoadingTask.cancel(true);
        this.currentLoadingTask = null;
      }
    }
  }
}

这篇关于如何从网址使用的AsyncTask设置的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆