gpt4 book ai didi

android - 如何使用 AsyncTask 从 Url 设置图像?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:33:00 25 4
gpt4 key购买 nike

我是一名新手程序员,我正在制作一个 android 程序,该程序在 ImageView 上显示来自给定 url 的图像。我的问题是如何在 AsyncTask 上使用它?

这些代码适用于 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;
}
}

最佳答案

好吧,我不知道为什么 android SDK 不提供对它的支持(但是)我通过 UrlImageView 类扩展了 ImageView 类,支持异步加载和缓存。我把我类的代码放在下面,即插即用。类主体在我的帖子末尾,现在我写两行如何方便地使用它。

现在支持另外两种方法:

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

如何在布局中绑定(bind):

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

..然后在您的 Activity 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 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;
}
}
}
}

关于android - 如何使用 AsyncTask 从 Url 设置图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14332296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com