Android 中使用 AsyncTask 异步读取网络图片

前端之家收集整理的这篇文章主要介绍了Android 中使用 AsyncTask 异步读取网络图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

 1.新建Android工程AsyncLoadPicture

新建布局文件activity_main.xml主界面为一个GridView,还有其子项布局文件gridview_item.xml

2.功能主界面MainActivity.java,主代码如下

package com.example.asyncloadpicture;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.GridView;
/**
* @author ymw
* @data --
*/
public class MainActivity extends Activity {
private GridView gridViewImg;
private ArrayList<ImageEntity> imageList = new ArrayList<ImageEntity>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridViewImg = (GridView) findViewById(R.id.gridViewImg);
initData();
}
private void initData() {
for (int i = ; i < ; i++) {
ImageEntity b = new ImageEntity();
b.setImage(BitmapFactory.decodeResource(getResources(),R.drawable.nopicture));
imageList.add(b);
}
ImageAdapter adapter = new ImageAdapter(getApplicationContext(),imageList);
gridViewImg.setAdapter(adapter);
String[] params = {
"http://images.cnitblog.com/i///.png","p" };
new ImageLoadTask(getApplicationContext(),adapter).execute(params);
}
/** 图片异步加载类 */
public class ImageLoadTask extends AsyncTask<String,Void,Void> {
private ImageAdapter adapter;
public ImageLoadTask(Context context,ImageAdapter adapter) {
this.adapter = adapter;
}
@Override
protected Void doInBackground(String... params) {
String url = params[];// 获取传来的参数,图片uri地址
String p = params[];
for (int i = ; i < adapter.getCount(); i++) {
ImageEntity bean = (ImageEntity) adapter.getItem(i);
Bitmap bitmap = BitmapFactory.decodeStream(Request
.HandlerData(url));
bean.setImage(bitmap);
publishProgress(); // 通知去更新UI
}
return null;
}
public void onProgressUpdate(Void... voids) {
if (isCancelled())
return;
// 更新UI
adapter.notifyDataSetChanged();
}
}
/** 图片实体 */
public class ImageEntity {
private Bitmap image;
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
}
}

3.GridView列表图片适配器代码ImageAdapter.java

package com.example.asyncloadpicture;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.example.asyncloadpicture.MainActivity.ImageEntity;
/**
* 
* @author ymw
* @data -- 图片适配器
*/
public class ImageAdapter extends BaseAdapter {
private Context _context;
private ArrayList<ImageEntity> _list;
public ImageAdapter(Context context,ArrayList<ImageEntity> imageList) {
this._context = context;
this._list = imageList;
}
@Override
public int getCount() {
return _list.size();
}
@Override
public Object getItem(int position) {
return _list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position,View convertView,ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(_context);
convertView = inflater.inflate(R.layout.gridview_item,null);
ImageView imgView = (ImageView) convertView.findViewById(R.id.imgView);
ImageEntity b = _list.get(position);
// 如果有图片则读取,没有则跳过
if (b.getImage() != null) {
imgView.setImageBitmap(b.getImage());
}
return convertView;
}
}

4.请求网络读取图片的类Request.java

package com.example.asyncloadpicture;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.drawable.Drawable;
import android.util.Log;
/**
* 工具类,主要根据url读取图片返回流的方法
* 
* @author ymw
* 
*/
public class Request {
public static InputStream HandlerData(String url) {
InputStream inStream = null;
try {
URL FeedUrl = new URL(url);
URLConnection conn = FeedUrl.openConnection();
conn.setConnectTimeout( * );
inStream = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return inStream;
}
/** 直接返回Drawable对象设置图片 */
public static Drawable loadImageFromNetwork(String imageUrl) {
Drawable drawable = null;
try {
// 可以在这里通过文件名来判断,是否本地有此图片
drawable = Drawable.createFromStream(
new URL(imageUrl).openStream(),"image.jpg");
} catch (IOException e) {
Log.d("test",e.getMessage());
}
if (drawable == null) {
Log.d("test","null drawable");
} else {
Log.d("test","not null drawable");
}
return drawable;
}
}

以上内容给大家介绍了Android 中使用 AsyncTask 异步读取网络图片的相关知识,希望对大家有所帮助!

原文链接:https://www.f2er.com/android/519892.html

猜你在找的Android相关文章