Looper之一

来源:互联网 发布:h5页面软件下载 编辑:程序博客网 时间:2024/05/09 09:21

一、Class  Overview

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, callprepare() in the thread that is to run the loop, and thenloop() to have it process messages until the loop is stopped.

Most interaction with a message loop is through theHandler class.

This is a typical example of the implementation of a Looper thread, using the separation ofprepare() andloop() to create an initial Handler to communicate with the Looper.

  class LooperThread extends Thread {      public Handler mHandler;      public void run() {          Looper.prepare();          mHandler = new Handler() {              public void handleMessage(Message msg) {                  // process incoming messages here              }          };          Looper.loop();      }  }

二、什么时候用Looper?
  
当你的线程想拥有自己的MessageQueue的时候先Looper.prepare(),然后Looper.loop();
参照源码:
 public static final void prepare() {        if (sThreadLocal.get() != null) {            throw new RuntimeException("Only one Looper may be created per thread");        }        sThreadLocal.set(new Looper());    }
这段代码就是通过ThreadLocal来产生一个Looper对象做为线程局部变量,然后调用Looper.loop()则是取出Looper对象中的MessageQueue进行消息循环了,这样形成了这个线程的消息队列。
一般情况下只会有主线程会调用prepare方法(ActivityThread的main函数)。
使线程拥有自己的消息列队,主线程拥有自己的消息列队,一般线程创建时没有自己的消息列队,消息处理时就在主线程中完成,如果线程中使用Looper.prepare()和Looper.loop()创建了消息队列就可以让消息处理在该线程中完成
 
三、从API可以看出一下几点
     1、有一个Main  Looper这个Looper寄存在主线程中
     2、我们自定义的线程是没有Looper对象的,当我们调用Looper.prepare()方法时,是给当前线程设置一个Looper对象。
     3、使用Loop.loop()来开始运行此Looper中的消息队列
     4、使用quit()退出loop(),就是退出对此线程的Looper中的消息队列的执行。

四、开发过程中遇到的情况

    

btnConfirm.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    progressDialog = ProgressDialog.show(
      EverydayCheckActivity.this, "提示", "正在上传排查信息");
    alertDialog = new AlertDialog.Builder(
      EverydayCheckActivity.this)
      .setTitle("提示")
      .setMessage("排查信息上传成功,是否下发通知单!")
      .setPositiveButton("确定",
        new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog,
           int which) {
          Intent intent = new Intent();
          intent.setClass(
            EverydayCheckActivity.this,
            NotificationTableActivity.class);
          // EverydayCheckActivity.this
          // .startActivity(intent);
          Toast.makeText(
            EverydayCheckActivity.this,
            "下发通知单成功", 3000).show();
         }
        }).setNegativeButton("取消", null).create();
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
     @Override
     public void run() {
      progressDialog.dismiss();
      Looper.prepare();
      alertDialog.show();
      Looper.loop();
     }
    }, 3000);
   }
  });

dismiss不通过消息机制实现,而show通过消息机制实现