2013-01-10 19 views
0

我現在正在使用LoadImageFromWeb的ImageView上工作,它需要在AsyncTask中。我沒有的AsyncTask代碼只是這樣的:在AsyncTask上加載ImageView更簡單嗎?

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); 

    } 

我一直在使用的AsyncTask但它的不同,因爲它只能使用字符串做了一些其他的項目,我的現在是ImageView的。

我搜索了答案,但他們的方法是如此混亂。他們使用的是這樣的:

public class MainActivity extends Activity { 

ImageView mImgView1; 
static Bitmap bm; 
ProgressDialog pd; 
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg"; 
BitmapFactory.Options bmOptions; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mImgView1 = (ImageView) findViewById(R.id.mImgView1); 
    pd = ProgressDialog.show(MainActivity.this, "Aguarde...", 
      "Carregando..."); 
    new ImageDownload().execute(""); 
} 

public class ImageDownload extends AsyncTask<String, Void, String> { 

    protected String doInBackground(String... params) { 
     // TODO Auto-generated method stub 
     bmOptions = new BitmapFactory.Options(); 
     bmOptions.inSampleSize = 1; 
     loadBitmap(imageUrl, bmOptions); 
     return imageUrl; 
    } 

    protected void onPostExecute(String imageUrl) { 
     pd.dismiss(); 
     if (!imageUrl.equals("")) { 
      mImgView1.setImageBitmap(bm); 
     } else { 
      Toast.makeText(MainActivity.this, 
        "Não foi possível obter resultados", Toast.LENGTH_LONG) 
        .show(); 
     } 
    } 

} 

public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) { 
    InputStream in = null; 
    try { 
     in = OpenHttpConnection(URL); 
     bm = BitmapFactory.decodeStream(in, null, options); 
     in.close(); 
    } catch (IOException e1) { 
    } 
    return bm; 
} 

private static InputStream OpenHttpConnection(String strURL) 
     throws IOException { 
    InputStream inputStream = null; 
    URL url = new URL(strURL); 
    URLConnection conn = url.openConnection(); 

    try { 
     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
      inputStream = httpConn.getInputStream(); 
     } 
    } catch (Exception ex) { 
    } 
    return inputStream; 
} 

}

和這麼多的從我的方法,我在ImageView的使用複雜的(對我來說)。

我的問題是:除了使用第二個代碼之外,是否有更簡單更簡單的方法?我試圖讓它工作,但它沒有。當涉及到圖像時,我不知道如何去做AsyncTask。我很沮喪。

感謝提前的幫助:)

+0

看一看這個[鏈接](https://github.com/thest1/LazyList)其圖像的延遲加載,它可以幫助你解決你的問題 –

回答

0

以下是您導航到LazyLaoding和其他圖像庫加載很多答案,但你爲什麼去太多複雜的方式,你可以用你的簡單的AsyncTask直接去做實現。

只需將您的ImageView參考AsyncTask's Constructor,然後在doInBackground()回報BitmaponPostExecute()使用該Bitmap params只是檢查是否是NULL或不如果不是null,則簡單的設置位圖到您的ImageVIew ..

例子:

protected Bitmap doInBackground(String... params)

protected void onPostExecute(Bitmap bitmap)

0

這裏是一流的圖像加載u可以在烏拉圭回合項目中使用和u只需要調用ImageLoader的,S顯示圖像的方法。

  public class ImageLoader { 

MemoryCache memoryCache=new MemoryCache(); 
FileCache fileCache; 
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); 
ExecutorService executorService; 

public ImageLoader(Context context){ 
    fileCache=new FileCache(context); 
    executorService=Executors.newFixedThreadPool(5); 
} 

final int stub_id = R.drawable.no_image; 
public void DisplayImage(String url, ImageView imageView) 
{ 
    imageViews.put(imageView, url); 
    Bitmap bitmap=memoryCache.get(url); 
    if(bitmap!=null) 
     imageView.setImageBitmap(bitmap); 
    else 
    { 
     queuePhoto(url, imageView); 
     imageView.setImageResource(stub_id); 
    } 
} 

private void queuePhoto(String url, ImageView imageView) 
{ 
    PhotoToLoad p=new PhotoToLoad(url, imageView); 
    executorService.submit(new PhotosLoader(p)); 
} 

private Bitmap getBitmap(String url) 
{ 
    File f=fileCache.getFile(url); 

    //from SD cache 
    Bitmap b = decodeFile(f); 
    if(b!=null) 
     return b; 

    //from web 
    try { 
     Bitmap bitmap=null; 
     URL imageUrl = new URL(url); 
     HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
     conn.setConnectTimeout(30000); 
     conn.setReadTimeout(30000); 
     conn.setInstanceFollowRedirects(true); 
     InputStream is=conn.getInputStream(); 
     OutputStream os = new FileOutputStream(f); 
     Utils.CopyStream(is, os); 
     os.close(); 
     bitmap = decodeFile(f); 
     return bitmap; 
    } catch (Exception ex){ 
     ex.printStackTrace(); 
     return null; 
    } 
} 

//decodes image and scales it to reduce memory consumption 
private Bitmap decodeFile(File f){ 
    try { 
     //decode image size 
     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(new FileInputStream(f),null,o); 

     //Find the correct scale value. It should be the power of 2. 
     final int REQUIRED_SIZE=70; 
     int width_tmp=o.outWidth, height_tmp=o.outHeight; 
     int scale=1; 
     while(true){ 
      if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
       break; 
      width_tmp/=2; 
      height_tmp/=2; 
      scale*=2; 
     } 

     //decode with inSampleSize 
     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize=scale; 
     return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
    } catch (FileNotFoundException e) {} 
    return null; 
} 

//Task for the queue 
private class PhotoToLoad 
{ 
    public String url; 
    public ImageView imageView; 
    public PhotoToLoad(String u, ImageView i){ 
     url=u; 
     imageView=i; 
    } 
} 

class PhotosLoader implements Runnable { 
    PhotoToLoad photoToLoad; 
    PhotosLoader(PhotoToLoad photoToLoad){ 
     this.photoToLoad=photoToLoad; 
    } 


    public void run() { 
     if(imageViewReused(photoToLoad)) 
      return; 
     Bitmap bmp=getBitmap(photoToLoad.url); 
     memoryCache.put(photoToLoad.url, bmp); 
     if(imageViewReused(photoToLoad)) 
      return; 
     BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad); 
     Activity a=(Activity)photoToLoad.imageView.getContext(); 
     a.runOnUiThread(bd); 
    } 
} 

boolean imageViewReused(PhotoToLoad photoToLoad){ 
    String tag=imageViews.get(photoToLoad.imageView); 
    if(tag==null || !tag.equals(photoToLoad.url)) 
     return true; 
    return false; 
} 

//Used to display bitmap in the UI thread 
class BitmapDisplayer implements Runnable 
{ 
    Bitmap bitmap; 
    PhotoToLoad photoToLoad; 
    public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;} 
    public void run() 
    { 
     if(imageViewReused(photoToLoad)) 
      return; 
     if(bitmap!=null) 
      photoToLoad.imageView.setImageBitmap(bitmap); 
     else 
      photoToLoad.imageView.setImageResource(stub_id); 
    } 
} 

public void clearCache() { 
    memoryCache.clear(); 
    fileCache.clear(); 
} 

}