1、Android消息机制

【1】anr异常 Application not response 应用无响应, 主线程(UI线程)

【2】如果在主线程中进行耗时的操作(比如链接网络,数据拷贝等),需要使用子线程进行操作

【3】只有主线程可以更新UI,所以主线程也叫UI线程

【4】使用消息机制在子线程中来更新UI Handler

1)在主线程中定义handler消息助手

//Lopper 主线程中的消息循环器,主线程创建后Looper就自动创建,不断的监视消息队列,当发现有新的消息时,交给handleMessage处理。

private Handler hendler = new Handler(Looper.getMainLooper()){

//用来接收消息

@Override

public void handleMessage(@NonNull Message msg) {

super.handleMessage(msg);

switch (msg.what){

case 1:

String[] obj = (String[])msg.obj;

这里可以进行更新UI的操作

}

};

2)在子线程中使用handler助手发送消息

//发送消息到Handler

Message mm = Message.obtain();//使用静态方法初始化消息,效率比直接new高,减少对象创建

Message msg = new Message();

msg.what=1;//消息类型,发送多条消息使用

msg.obj = new String[]{"",""};//消息内容

hendler.sendMessage(msg); //消息发送后handleMessage方法就会执行

2、runOnUiThread(action) API

运行一个指定的action在主线程,可以主线程和子线程中使用,主线程中调用,直接执行,如果是子线程发送消息到主线程的消息队列(内部已封装)。不管是主线程或子线程action都是运行在子线程上的。

runOnUiThread(new Runnable(){

public void run(){

//更行UI

}

});

如果仅仅是更新UI这个方法比较好用,其他方式是用Handler发送消息携带数据。

3、其他常用方式

//延时2秒后执行Runnable

new Handler().postDelayed(new Runnable()}{},2000)

4、网络图片展示

开源项目smartimageView