浅析Android Handler机制原理。

首先我们要知道以下几个方面:(基础很重要,要知道的)

第一点:在Android中,只有在UIThread(主线程)才能直接更新界面。

第二点:在Android中,长时间的工作(联网)都需要在workerThread中执行。

第三点:在子线程中获取服务器的数据之后,要马上到主线程中更新界面。那么怎么才能在主线程中更新界面呢。哈哈那么我们只需要在子线程中new一个runOnUiThread()--->

handler。

第三点:我们如何实现主线程和子线程之间的通信呢?

那么我就要用到了传说中的消息机制(handler+Thread)和异步任务(AsyncTask:实际上是对Handler和Thread的封装,内部提供了线程池)了。

我靠相关的API我就不说了,你们自己查吧,我直接说怎么用吧。看下面

Handler的一般的使用步骤:(记住了)

1、创建Handler成员变量对象,并重写handleMessage()方法。

2、在分线程或主线程创建Message对象。

3、使用handler对象发送Message。

4、在handleMessage中处理你发过来的消息。

说了这么多我直接给你们Handler机制的原理图,咱们看图说话


我给的图够详细吧。哈哈哈
接下来我来告诉大家Handler整个消息机制是怎么完成的。。。
我们通常将Handler声明在Activity中,然后复写Handler中handleMessage()方法,当子线程调用handler.sendMessage()方法之后,handleMessage()方法就会在主线程中执行。
这里除了Handler、Message外还有Looper(轮询器)和MessageQueue(消息队列)对象。
在主线程中默认调用了Looper.preper()方法,调用该方法的目的是在Looper中创建MessageQueue成员变量并把Looper对象绑定到当前线程中, 当 调 用 Handler 的sendMessage(对象方法的时候就将 Message 对象添加到了 Looper 创建的 MessageQueue队列中,同时给 Message 指定了 target 对象,其实这个 target 对象就是 Handler 对象。主线程默认执行了 Looper.looper  方法,该方法从 Looper 的成员变量 MessageQueue 中取出 Message,然后调用 Message 的 target 对象的 handleMessage()方法。这样就完成了整个消息机制。
写到这里了,那么重点来了,看demo说话
/*
 * 联网操作的方式:
 * ① Thread + runOnUiThread()
 * ② Thread + Handler + Message
 * ③ AsyncTask 异步任务
 * 
 * 联网操作的过程:
 * 第1步:主线程:显示提示视图
 * 第2步:分线程:联网下载数据
 * 第3步:主线程:更新界面
 * 
 */
public class MainActivity extends Activity {

protected static final int MESSAGE_RESULT_OK = 1;
protected static final int MESSAGE_RESULT_ERROR = 2;
protected static final int MESSAGE_RESULT_NO = 3;
private ListView ll_main_shopinfo;
private ShopInfoAdapter adapter;
private LinearLayout ll_main_loading;//加载的提示视图
private List<ShopInfo> list;

private Handler handler = new Handler(){
//处理消息
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case MESSAGE_RESULT_OK:
ll_main_loading.setVisibility(View.GONE);//移除加载视图

//显示列表
ll_main_shopinfo.setAdapter(adapter);
break;

case MESSAGE_RESULT_ERROR:
Toast.makeText(MainActivity.this, "资源找不到", 0).show();
ll_main_loading.setVisibility(View.GONE);//移除加载视图
break;

case MESSAGE_RESULT_NO:
Toast.makeText(MainActivity.this, "连接失败", 0).show();
ll_main_loading.setVisibility(View.GONE);//移除加载视图
break;
}
}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//初始化操作:
ll_main_shopinfo = (ListView) findViewById(R.id.ll_main_shopinfo);
adapter = new ShopInfoAdapter();
ll_main_loading = (LinearLayout) findViewById(R.id.ll_main_loading);


//联网操作的过程:第1步:主线程:显示提示视图
ll_main_loading.setVisibility(View.VISIBLE);

//联网操作的过程:第2步:分线程:联网下载数据
new Thread(){
public void run() {
String path = "http://192.168.56.1:8989/Web_server/ShopListServlet";
HttpURLConnection conn = null;
ByteArrayOutputStream baos = null;
InputStream is = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");

conn.connect();

int responseCode = conn.getResponseCode();
if(responseCode == 200){
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
baos.write(buffer, 0, len);
}
//从服务器端返回的json数组的字符串
String result = baos.toString();
//使用GSON解析,还原为java对象构成的集合
Gson gson = new Gson();
//初始化list
list = gson.fromJson(result,new TypeToken<List<ShopInfo>>(){}.getType());

//发送消息:
handler.sendEmptyMessage(MESSAGE_RESULT_OK);
}else{
//发送消息:
handler.sendEmptyMessage(MESSAGE_RESULT_ERROR);

}


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//发送消息
handler.sendEmptyMessage(MESSAGE_RESULT_NO);
}finally{
if(conn != null){
conn.disconnect();
}
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(baos != null){
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}


}.start();
}


class ShopInfoAdapter extends BaseAdapter{

private ImageLoader imageLoader;
public ShopInfoAdapter(){
imageLoader = new ImageLoader(MainActivity.this,R.drawable.loading,R.drawable.error);
}

@Override
public int getCount() {

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 0;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = View.inflate(MainActivity.this, R.layout.item_shopinfo, null);
}

ImageView iv_item_icon= (ImageView) convertView.findViewById(R.id.iv_item_icon);
TextView tv_item_name = (TextView) convertView.findViewById(R.id.tv_item_name);
TextView tv_item_price = (TextView) convertView.findViewById(R.id.tv_item_price);

ShopInfo shopInfo = list.get(position);

tv_item_name.setText(shopInfo.getName());
tv_item_price.setText(shopInfo.getPrice() + "");

//暂时不加载图片
//Log.e("TAG", shopInfo.getImagepath());
//加载图片
imageLoader.loadImage(shopInfo.getImagepath(),iv_item_icon);

return convertView;
}

}
}

发布了13 篇原创文章 · 获赞 11 · 访问量 9249

猜你喜欢

转载自blog.csdn.net/wangzizhong201205/article/details/53612341
今日推荐