非主线程中使用Looper

主线程(UI线程)在启动时在其入口函数main中就进行了 Looper.prepare  ..... Looper.loop 操做。所以不须要手动进行。java

可是在非主线程中(通常是本身手动启动的线程) 则须要显示的调用Looper.prepare 和 Looper.loop . 而后才能够在线程中启用相应消息,调用Toast和Dialog或者经过handler相应消息, 缘由是Toast和Dialog中都有handler, 须要经过当前线程的looper和当前线程交互。网络

loop是一个循环,其后的代码不能执行,因此loop通常放在run方法的最后。而prepare在run方法最开始处。ide

另外,网络请求必须放在非主线程中进行,不然报network in main thread exception。函数

Handler mHandler;
Runnable runnable = new Runnable() {
 @Override
 public void run() {
 Looper.prepare();
 
 ...
 
 // handler for other threads to send message
 mHandler = new Handler(){
     public void handleMessage(Message msg) {
            // process incoming messages here
     }
 }
 
//这里的toast提示并不会立刻显示,而是向run方法开头准备的looper消息队列发送消息
 Toast.makeText(context "toast message" + res, Toast.LENGTH_SHORT).show();

 ...

 Looper.loop(); //开始处理消息
 }

 };
相关文章
相关标签/搜索