你的位置:首页 > 软件开发 > 操作系统 > Handler机制(四)

Handler机制(四)

发布时间:2016-08-21 00:00:07
Handler的主要用途有两个:(1)、在将来的某个时刻执行消息或一个runnable,(2)把消息发送到消息队列。 主要依靠post(Runnable)、postAtTime(Runnable, long)、postDelayed(Runnable, long) ...

Handler的主要用途有两个:(1)、在将来的某个时刻执行消息或一个runnable,(2)把消息发送到消息队列。

   主要依靠post(Runnable)、postAtTime(Runnable, long)、postDelayed(Runnable, long)、sendEmptyMessage(int)、sendMessage(Message)、sendMessageAtTime(Message)、sendMessageDelayed(Message, long)这些方法来来完成消息调度。post方法是当到Runable对象到达就**入到消息队列;sendMessage方法允许你把一个包含有信息的Message插入队列,而且它会Handler的handlerMessage(Message)方法中执行(该方法要求在Handler的子类中实现)。

1.构造方法

 /**  默认的构造方法,handler是和当前线程的队列关联在一起,如果队列不存在,那么handler就不能接受消息。   * Default constructor associates this handler with the {@link Looper} for the   * current thread.   * 如果线程没有looper,就会抛出异常   * If this thread does not have a looper, this handler won't be able to receive messages   * so an exception is thrown.   */public Handler() {    this(null, false);  }//传入一个callback接口用于处理handler传递的Message。 public Handler(Callback callback) {    this(callback, false);  }//给变量赋值 public Handler(Callback callback, boolean async) {    if (FIND_POTENTIAL_LEAKS) {      final Class<? extends Handler> klass = getClass();      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&          (klass.getModifiers() & Modifier.STATIC) == 0) {        Log.w(TAG, "The following Handler class should be static or leaks might occur: " +          klass.getCanonicalName());      }    }    mLooper = Looper.myLooper();    if (mLooper == null) {      throw new RuntimeException(        "Can't create handler inside thread that has not called Looper.prepare()");    }    mQueue = mLooper.mQueue;    mCallback = callback;    mAsynchronous = async;  }  public Handler(Looper looper, Callback callback, boolean async) {    mLooper = looper;    mQueue = looper.mQueue;    mCallback = callback;    mAsynchronous = async;  }

原标题:Handler机制(四)

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录