android内部培训视频_第四节(1)_异步网络操作

时间:2014-05-14 02:28:28   收藏:0   阅读:537

第四节(1):异步网络操作


 一、结合asyncTask下载网络图片

1.定义下载类,继承自asyncTask,参数分别为:String(url地址),Integer(刻度,本例没有用到),BitMap(下载成功后的图片)

bubuko.com,布布扣
public class downloadImageTask extends AsyncTask<String, Integer, Bitmap> {
/**
         * 在线程开始之前执行
         */
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            dialog.setTitle("提示");
            dialog.setMessage("正在下载数据,请稍候...");
            dialog.show();
        }
/**
         * 异步执行耗时操作
         */
        @Override
        protected Bitmap doInBackground(String... params) {}

/**
         * 执行完成后
         */
        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.dismiss();
            image1.setImageBitmap(result);
        }
}
View Code

2.实现doInBackground

  1) 定义HttpClient和HttpGet

bubuko.com,布布扣
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]); //params[0]为主线程调用时传入的url地址
bubuko.com,布布扣

 2) 利用HttpResponse取得网络返回

bubuko.com,布布扣
try {
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    byte[] data = EntityUtils.toByteArray(entity);
                    bitmap = BitmapFactory
                            .decodeByteArray(data, 0, data.length);
                }
                // 404/500
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_LONG)
                        .show();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
View Code

 

3.主线程调用

bubuko.com,布布扣
// 启用多线程访问网络下载图片
                new downloadImageTask()
                        .execute("http://image.tianjimedia.com/uploadImages/2013/287/IEOV0N9V8RR7_1000x500.jpg");
bubuko.com,布布扣

 

 二、下载网络json数据,并绑定至listview

json内容:

bubuko.com,布布扣
{
users: [
{
face: "001.jpg",
headShip: "软件工程师",
userName: "周瑜"
},
{
face: "002.jpg",
headShip: "开发人员",
userName: "陈风"
},
{
face: "003.jpg",
headShip: "开发人员",
userName: "季炜"
},
{
face: "004.jpg",
headShip: "开发人员",
userName: "小包"
},
{
face: "005.jpg",
headShip: "开发人员",
userName: "小裴"
}
]
}
View Code

1.根据json格式定义User实体

bubuko.com,布布扣
package com.cmcc.utils;

public class User {
    private String userName;
    private String headShip;
    private String face;
    
    public User() {
        super();
    }
    
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getHeadShip() {
        return headShip;
    }
    public void setHeadShip(String headShip) {
        this.headShip = headShip;
    }
    public String getFace() {
        return face;
    }
    public void setFace(String face) {
        this.face = face;
    }
    
    
}
View Code

2.利用asyncTask下载数据

bubuko.com,布布扣
public class getUserTask extends AsyncTask<String, Void, List<User>>{
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            dialog.setTitle("提示");
            dialog.setMessage("正在下载,请稍候...");
            dialog.show();
        }
        @Override
        protected List<User> doInBackground(String... params) {
            // TODO Auto-generated method stub
            List<User> list = new ArrayList<User>();
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(params[0]);
            try {
                HttpResponse response = client.execute(get);
                if(response.getStatusLine().getStatusCode() == 200){
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObj = new JSONObject(json);
                    JSONArray jsonArray = jsonObj.getJSONArray("users");
                    for(int i = 0;i<jsonArray.length();i++){
                        JSONObject obj = jsonArray.getJSONObject(i);
                        User user = new User();
                        user.setUserName(obj.getString("userName"));
                        user.setHeadShip(obj.getString("headShip"));
                        user.setFace(obj.getString("face"));
                        list.add(user);
                    }
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return list;
        }
        @Override
        protected void onPostExecute(List<User> result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dialog.dismiss();
            myAdapter adapter = new myAdapter(result,MainActivity.this); //自定义adapter,详见下面代码
            listview1.setAdapter(adapter);
        }
        
    }
View Code

3.自定义baseAdapter,绑定listView

bubuko.com,布布扣
public class myAdapter extends BaseAdapter{

        List<User> list;
        Context context;
        LayoutInflater inflater;
        public myAdapter(List<User> list,Context context) {
            super();
            this.list = list;
            this.context = context;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(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
            View view;
            if(convertView!=null){
                view = convertView;
            }else{
                view = inflater.inflate(R.layout.user, null);
            }
            final ImageView face = (ImageView) view.findViewById(R.id.face);
            TextView tvUserName = (TextView) view.findViewById(R.id.tvUserName);
            TextView tvHeadShip = (TextView) view.findViewById(R.id.tvHeadShip);
            tvUserName.setText(list.get(position).getUserName());
            tvHeadShip.setText(list.get(position).getHeadShip());
            
            //头像下载,实现类详见后面代码
            String imageUrl = "http://xxx.xxxx.xxxx/resources/face/"+list.get(position).getFace();
            DownloadFace download = new DownloadFace(imageUrl);
            download.loadImageFromUrl(new downloadFaceCallBack() {
                @Override
                public void setDrawble(Drawable drawable) {
                    // TODO Auto-generated method stub
                    face.setImageDrawable(drawable);
                }
            });
            
            return view;
        }
    }
View Code

 

三、ListView中异步下载头像

 下载头像线程类

bubuko.com,布布扣
package com.cmcc.utils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.R.drawable;
import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class DownloadFace {

    String faceUrl;

    public DownloadFace(String faceUrl) {
        super();
        this.faceUrl = faceUrl;
    }

    @SuppressLint("HandlerLeak")
    public void loadImageFromUrl(final downloadFaceCallBack callback) {
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                Drawable drawable = (Drawable) msg.obj;
                callback.setDrawble(drawable);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    Drawable drawable = Drawable.createFromStream(new URL(
                            faceUrl).openStream(), "");
                    Message msg = Message.obtain();
                    msg.obj = drawable;
                    handler.sendMessage(msg);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public interface downloadFaceCallBack {
        public void setDrawble(Drawable drawable);
    }
}
View Code

 

 

百度网盘视频下载地址:http://pan.baidu.com/s/1ntFNJjb

 

android内部培训视频_第四节(1)_异步网络操作,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!