Kke*_*ino 5 multithreading android android-asynctask android-drawable
我是一个新手程序员,我正在制作一个Android程序,在给定的URL上显示ImageView上的图像.我的问题是你如何在AsyncTask上使用它?
这些代码适用于最小的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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 2
如果图像不是那么大,您可以使用匿名类来执行异步任务。这会喜欢这样:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
Run Code Online (Sandbox Code Playgroud)
任务类别是
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) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21324 次 |
| 最近记录: |