4

我是一个新手程序员,我正在制作一个Android程序,该程序在给定的URL上显示ImageView上的图像。我的问题是你如何在AsyncTask上使用它?如何使用AsyncTask从Url设置图片?

这些代码适用于min SDK 2.2,但我切换到min SDK 3.0,因此需要在AsyncTask上运行。感谢您的帮助! :)

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; 
     } 
} 
+0

Tol,SDK 2.2? SDK 3.0?你的意思是Froyo和蜂窝? – 2013-01-15 06:35:52

+0

是的。因为在上面的3.0中,当我从互联网获取数据时,我需要运行一个单独的线程。在2.2中没有这个问题。所以我遇到这个问题 –

回答

2

如果图像不是那么大,您可以使用匿名类作为异步任务。这将是这样的:

ImageView mChart = (ImageView) findViewById(R.id.imageview); 
String URL = "http://www...anything ..."; 

mChart.setTag(URL); 
new DownloadImageTask.execute(mChart); 

,任务类是

public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> { 
    ImageView imageView = null; 
    @Override 
    protected Bitmap doInBackground(ImageView... imageViews) { 
     this.imageView = imageViews[0]; 
     return download_Image((String)imageView.getTag()); 
    } 

    @Override 
    protected void onPostExecute(Bitmap result) { 
     imageView.setImageBitmap(result); 
    } 

    private Bitmap download_Image(String url) { 
     ... 
    } 
0

下面是Aynctask实施 让您绘制对象作为Aynctask级全球的代码。

Class MyDownloader extends AsyncTask<Void,Void,String>{ 

    Drawable drawable;  
    @Override 
    public String doInBackground(Void... args){ 

     drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif"); 
     return null; // here you can pass any string on response as on error or on success 

    } 

    public void onPostExecute(String result){ 

     if(drawable!=null){ 

      imgView.setImageDrawable(drawable); 

     } 

    } 

} 

现在创建这个类的对象,并执行它

private void satellite() { 
    // TODO Auto-generated method stub 
    ImageView imgView =(ImageView)findViewById(R.id.satellite); 
    new MyDownloader.execute(); 

} 

这里是很好的例子,链接,缓存图像看看这个链接,例如

https://github.com/novoda/ImageLoader

+0

我在'new MyDownloader.execute();'上得到一个错误;'它说: MyDownloader无法解析为类型。 并且还我改变 '类MyDownloader延伸的AsyncTask <空隙,空隙,字符串> {' 到: '公共类MyDownloader延伸的AsyncTask <空隙,空隙,字符串> {' ,因为它显示了'Class'错误部分。 我在做对吧? –

0

你是对的当你做任何网络操作后Android 2.2(Froyo)必须使用Asynctask

这是最好的example了解AsyncTask

1

试试这个代码,让你的绘制变量全球和改变你的卫星功能是这样的:

private void satellite() { 
     // TODO Auto-generated method stub 
     ImageView imgView =(ImageView)findViewById(R.id.satellite); 
     new yourTask().execute(); 
} 

然后创建的AsyncTask类是这样的:

private class yourTask extends AsyncTask<Integer, Void, Integer> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     //show a progress bar 
    } 

    @Override 
    protected String doInBackground(Integer... params) { 
     drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif"); 
     return 0; 
    }  

    @Override 
    protected void onPostExecute(Integer result) { 
     super.onPostExecute(result); 
     imgView.setImageDrawable(drawable); 
    } 
} 
3

好吧,我不知道为什么Android SDK不提供它的支持(但)我扩展了ImageView类的UrlImageView类与异步加载和缓存支持。我把我的课程的代码放在下面,这是即插即用的。课程主体在我的文章末尾,现在我写了两行如何以便捷的方式使用它。

两种方法,现在支持:

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

如何使用您的java代码:

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

如何在您的布局绑定:

<!-- 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" /> 

..和再次在您的活动Java代码:

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

我在超过100个条目的列表中使用它 - 扔得很好。在这里,类体,您可以使用它,修改它,扩展它,不管你喜欢:

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 [email protected]/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; 
     } 
    } 
    } 
} 
+0

感谢您安排精美的代码,我将使用它并对其进行一些修改。谢谢 – Diljeet

+0

我发布了自己的自定义implmentation作为其他用户的新答案,我们可以使用正常的ImageView加载图像而不是UrlImageView。它还支持像onComplete和onCancel这样的操作 – Diljeet

0

基于从comeGetSome我创造了我自己实现的答案,与正常的ImageView类的工作,而不是创建一个新的类UrlImageView,也提供了新的选择一样 - 加载完成或取消,只要你想

现在加载图像,像这样的任何三个的LoadImage方法

 UrlImageLoader urlImageLoader=new UrlImageLoader(); 
     ImageView imageView=new ImageView(context); 
     //load and set the image to ImageView 
     urlImageLoader.loadImage(imageView, "http://www......com/.....jpg"); 
     //for loading a image only - load image and do any thing with the bitmap 
     urlImageLoader.loadImage("http://www......com/.....jpg", new UrlImageLoader.OnLoadingCompleteListener() { 

      @Override 
      public void onComplete(ImageView imageView, Bitmap bmp) { 
       // do anything with the Bitmap 
       // here imageView will be null 
      } 
      @Override 
      public void onCancel(ImageView imageView) { 

      } 
     }); 
     urlImageLoader.loadImage(imageView, "http://www......com/.....jpg", new UrlImageLoader.OnLoadingCompleteListener() { 

      @Override 
      public void onComplete(ImageView imageView, Bitmap bmp) { 
       // do anything with the Bitmap 
       // here imageView is not null 
       imageView.setImageBitmap(bmp); 
      } 
      @Override 
      public void onCancel(ImageView imageView) { 

      } 
     }); 

创建一个类加载的时候做什么UrlImageLoader

/*special thanks to stackoverflow.com user comeGetSome for UrlImageLoadingTask code 
* question - http://stackoverflow.com/questions/14332296/how-to-set-image-from-url-using-asynctask/15797963 
* comeGetSome - http://stackoverflow.com/users/1005652/comegetsome 
*/ 
package com.GameG.SealTheBox; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLConnection; 
import java.util.ArrayList; 

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.ImageView; 

public class UrlImageLoader { 
    public static interface OnLoadingCompleteListener { 
     public void onComplete(ImageView imageView, Bitmap bmp); 
     public void onCancel(ImageView imageView); 
    } 
    ArrayList<UrlImageLoadingTask> loadingList=new ArrayList<UrlImageLoadingTask>(); 
    /** 
    * Loads a image from url and calls onComplete() when finished<br> 
    * @Note you should manually set the loaded image to ImageView in the onComplete() 
    * @param imageView 
    * @param url 
    * @param onComplete 
    */ 
    public void loadImage(ImageView imageView, String url, OnLoadingCompleteListener onComplete){ 
     try { 
      URL url2=new URL(url); 
      if(imageView!=null){ 
       for(int i=0;i<loadingList.size();i++){ 
        UrlImageLoadingTask tmptask=loadingList.get(i); 
        if(tmptask.updateView!=null && tmptask.updateView.equals(imageView)){ 
         tmptask.cancel(true); 
         break; 
        } 
       } 
      } 
      UrlImageLoadingTask loadtask=new UrlImageLoadingTask(imageView,onComplete,url); 
      loadtask.execute(url2); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Loads a image from url and calls onComplete() when finished 
    * @param url 
    * @param onComplete 
    */ 
    public void loadImage(String url, OnLoadingCompleteListener onComplete){ 
     loadImage(null,url,onComplete); 
    } 
    /** 
    * Loads a image from url and sets the loaded image to ImageView 
    * @param imageView 
    * @param url 
    */ 
    public void loadImage(ImageView imageView, String url){ 
     loadImage(imageView,url,null); 
    } 
    /** 
    * Cancel loading of a ImageView 
    */ 
    public void cancel(ImageView imageView){ 
     for(int i=0;i<loadingList.size();i++){ 
      UrlImageLoadingTask tmptask=loadingList.get(i); 
      if(tmptask.updateView.equals(imageView)){ 
       loadingList.remove(i); 
       tmptask.cancel(true); 
       break; 
      } 
     } 
    } 
    /** 
    * Cancel loading of a Url 
    */ 
    public void cancel(String url){ 
     for(int i=0;i<loadingList.size();i++){ 
      UrlImageLoadingTask tmptask=loadingList.get(i); 
      if(tmptask.url.equals(url)){ 
       loadingList.remove(i); 
       tmptask.cancel(true); 
       break; 
      } 
     } 
    } 
    /** 
    * Cancel all loading tasks 
    */ 
    public void cancelAll(){ 
     while(loadingList.size()>0){ 
      UrlImageLoadingTask tmptask=loadingList.get(0); 
      loadingList.remove(tmptask); 
      tmptask.cancel(true); 
     } 
    } 

    private class UrlImageLoadingTask extends AsyncTask<URL, Void, Bitmap> { 
     public ImageView updateView=null; 
     public String url; 
     private boolean   isCancelled = false; 
     private InputStream  urlInputStream; 
     private OnLoadingCompleteListener onComplete=null; 

     private UrlImageLoadingTask(ImageView updateView, OnLoadingCompleteListener onComplete, String url) { 
      this.updateView=updateView; 
      this.onComplete=onComplete; 
      this.url=url; 
     } 

     @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 
       if(onComplete==null){ 
        if(updateView!=null) 
        this.updateView.setImageBitmap(result); 
       }else{ 
        onComplete.onComplete(updateView, result); 
       } 
      } 
      loadingList.remove(this); 
     } 

     /* 
     * 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(); 
      if(onComplete!=null) 
       onComplete.onCancel(updateView); 
      loadingList.remove(this); 
      } 
     } 
     } 

} 
0

只需创建一个新的类“DownloadImageTask”像以下之一,并把它放在你有你活动同一文件夹中。

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.util.Log; 
import android.widget.ImageView; 
import android.os.AsyncTask; 
import java.io.*; 


public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { 
    ImageView bmImage; 

    public DownloadImageTask(ImageView bmImage) { 
     this.bmImage = bmImage; 
    } 

    protected Bitmap doInBackground(String... urls) { 
     String urldisplay = urls[0]; 
     Bitmap myImage = null; 
     try { 
      InputStream in = new java.net.URL(urldisplay).openStream(); 
      myImage = BitmapFactory.decodeStream(in); 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return myImage; 
    } 

    protected void onPostExecute(Bitmap result) { 
     bmImage.setImageBitmap(result); 
    } 
} 

此插件线箱之后类的活动

import android.graphics.Bitmap; 
import android.os.AsyncTask; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.util.Log; 
import android.widget.ImageView; 


public class HomeScreen extends ActionBarActivity { 

    private final String TAG = "test1"; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     Log.d(TAG, "onCreate"); 
     setContentView(R.layout.activity_home_screen); 
     InitHomeScreen(); 
    } 

    protected void InitHomeScreen() 
    { 
     String imageUrl = "http://s20.postimg.org/4t9w2pdct/logo_android_png.png"; 
     Log.d(TAG, "Get an Image"); 
     // Get an Image 
     try{ 
      AsyncTask<String, Void, Bitmap> execute = new DownloadImageTask((ImageView) findViewById(R.id.imageView)) 
        .execute(imageUrl); 
       // R.id.imageView -> Here imageView is id of your ImageView 
     } 
     catch(Exception ex) 
     { 
     } 
    } 

    // Other code... 

不要忘记允许访问互联网到你的Android应用程序。

检查您的清单文件。

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.dmitry.myapplication1" > 

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".HomeScreen" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest>