以下是以解析百度API作为一个demo,采用普通的异步处理方式下载图片,稍后会贴出一篇利用封装线程池类来实现
//************************Main_activity*****************************
public class MainActivity extends ActionBarActivity {
private File cache;
public static String city=null;
private EditText ed_city;
private Button butt_search;
private ListView lv;
private static final String basepath ="http://api.map.baidu.com/telematics/v3/weather?location=";
private static final String ak="&output=xml&ak=XXupCGKz1NrHH0DwIwKC74GWspa1bVGS";
private MyAdapter adapter;
//存放解析XML得到的Javabean对象
ArrayList<Weatherforecast> alist=new ArrayList<Weatherforecast>();
//list里面放MAP
ArrayList<Map<String,String>> list=new ArrayList<Map<String,String>>();
//map存放每天的具体数据
Map<String, String> map;
//**********************————handler更新界面————***************************
Handler handle = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
// msg.obj是获取handler发送信息传来的数据
alist= (ArrayList<Weatherforecast>) msg.obj;
System.out.println(alist.size());
for (Weatherforecast person : alist) {
//调用toString查看数据
//Log.i(TAG, person.toString());
//使用map存放数据
map= new HashMap<String, String>();
map.put("date", person.getDate());
map.put("dayPictureUrl", person.getDayPictureUrl());
map.put("nightPictureUrl", person.getNightPictureUrl());
map.put("weather", person.getWeather());
map.put("wind", person.getWind());
map.put("temperature", person.getTemperature());
list.add(map);
}
// 调用方法给ListView绑定数据
BinderListData(list);
};
// 绑定数据
private void BinderListData(ArrayList<Map<String, String>> list) {
// TODO Auto-generated method stub
// 创建adapter对象
adapter = new MyAdapter(MainActivity.this, list,cache);
// 将Adapter绑定到listview中
lv.setAdapter(adapter);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取界面中控件
ed_city = (EditText) this.findViewById(R.id.ed_city);
butt_search = (Button) this.findViewById(R.id.butt_search);
lv = (ListView) findViewById(R.id.lv);
//创建缓存目录,系统一运行就得创建缓存目录的,
cache = new File(Environment.getExternalStorageDirectory(), "cache");
if(!cache.exists()){
cache.mkdirs();
}
//为按钮设置监听********************
butt_search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 获取文本的内容(城市)
final String str_city = ed_city.getText().toString().trim();
if (TextUtils.isEmpty(str_city)) {
Toast.makeText(MainActivity.this, "城市名不能为空", 0).show();
} else {
//放到线程中去执行,以免请求时间过长造成界面无响应
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
//java.net.URLEncoder.encode(str_city)地址要转换成URL编码
URL url = new URL(basepath+java.net.URLEncoder.encode(str_city)+ak);
// 打开连接
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
// 设置请求方式
connect.setRequestMethod("GET");
// 设置连接响应时间
connect.setConnectTimeout(5000);
connect.setReadTimeout(5000);
//请求连接返回的响应编码
int code_type = connect.getResponseCode();
if (code_type == 200) {
InputStream is = connect.getInputStream();
Xmlpullparser pp=new Xmlpullparser();
alist=pp.readxml(is);
is.close();
}
//显示消息,创建Message对象
Message msg=Message.obtain();
msg.obj=alist;
handle.sendMessage(msg);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//清空缓存
File[] files = cache.listFiles();
for(File file :files){
file.delete();
}
cache.delete();
}
}
//**********************自定义个适配器集成baseadapter,并重写里面的方法*********************
public class MyAdapter extends BaseAdapter implements ListAdapter{
private List<Map<String, String>> data;
private static LayoutInflater inflater;
public static File cache;
public MyAdapter(Context context,ArrayList<Map<String, String>> list, File cache){
data=list;
this.cache=cache;
//inflater=(LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// convertView对象就是item的界面对象,只有为空的时候我们才需要重新赋值一次,这样可以提高效率,如果有这个对象的话,系统会自动复用
//R.layout.item就是自定义的item的布局文件
ViewHolder holder=new ViewHolder();
View vi=convertView;
if (convertView==null) {
//找到这个布局文件
vi=inflater.inflate(R.layout.item, null);
//注意findViewById的时候,要使用arg1的这个方法,因为是在它里面进行控件的寻找
holder.date=(TextView) vi.findViewById(R.id.text_word);
holder.weather=(TextView) vi.findViewById(R.id.text_weather);
holder.wind=(TextView) vi.findViewById(R.id.text_wind);
holder.teamplerater=(TextView) vi.findViewById(R.id.text_templerater);
holder.dayPicture=(ImageView) vi.findViewById(R.id.imageV);
holder.nightPicture=(ImageView) vi.findViewById(R.id.imageV1);
// 保存view对象到ViewHolder类中
vi.setTag(holder);
}else{
holder=(ViewHolder) vi.getTag();
}
// 帮数据绑定到控件上
//holder.date.setText(data.get(position).getDate());
holder.date.setText(data.get(position).get("date"));
//holder.weather.setText(data.get(position).getWeather());
holder.weather.setText(data.get(position).get("weather"));
//holder.wind.setText(data.get(position).getWind());
holder.wind.setText(data.get(position).get("wind"));
//holder.teamplerater.setText( data.get(position).getTemperature());
holder.teamplerater.setText( data.get(position).get("temperature"));
/**调用普通异步方式加载图片*/
asyncloadImage(holder.dayPicture,data.get(position).get("dayPictureUrl"));
asyncloadImage(holder.nightPicture,data.get(position).get("nightPictureUrl"));
return vi;
}
/**
* 采用普通方式异步的加载图片
*/
private void asyncloadImage(final ImageView iv_header, final String path) {
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Uri uri = (Uri) msg.obj;
if (iv_header != null && uri != null) {
//绑定图片
iv_header.setImageURI(uri);
}
}
}
};
// 子线程,开启子线程去下载或者去缓存目录找图片,并且返回图片在缓存目录的地址
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
//这个URI是图片下载到本地后的缓存目录中的URI(统一资源标识符)
Uri uri =getImageURI(path, cache);
Message msg = new Message();
msg.what = 1;
msg.obj = uri;
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
/*
* 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
* 这里的path是图片的地址
*/
public Uri getImageURI(String path, File cache) throws Exception {
// 将url的hashCode作为缓存的文件名,String.valueOf()方法转换成字符
String name = String.valueOf(path.hashCode());
File file = new File(cache, name);
// 如果图片存在本地缓存目录,则不去服务器下载
if (file.exists()) {
return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
} else {
// 从网络上获取图片
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
// 返回一个URI对象
return Uri.fromFile(file);
}
}
return null;
}
//视图控件类
class ViewHolder{
TextView date;
TextView weather;
TextView wind;
TextView teamplerater;
ImageView dayPicture;
ImageView nightPicture;
}
}