当我们需要工作线程来操作的时候,很多时候会有同步问题,UI更新问题。

Handle机制就是为了解决这个问题而产生的。

android允许每个线程都有自己的消息队列,同时也可以是主线程消息队列。

但是很多时候,我们希望可以快速的创建一个支持自己消息队列的android线程,这个时候HandlerThread就做了很好的封装。

package com.joyfulmath.demo.function;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

public class HandleThreadDemo {
	HandleThread  thread = null;
	Context ctx = null;
	Handler mHandle  = null;
	public HandleThreadDemo(Context context){
		thread = new HandleThread("demo.thread");
		ctx = context;
		mHandle = new Handler(thread.getLooper()){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
			}			
			
			
		};
	}
	
}

 

如你所见,我们只需要自己定义  handleMessage,其他的消息一直在handlerthread的run中运行,这样只要有消息被丢到该方法中即可实现同步!

 

相关文章:

  • 2021-12-04
  • 2021-12-07
  • 2022-12-23
  • 2021-11-24
  • 2021-09-05
  • 2021-08-22
  • 2021-10-22
  • 2021-11-04
猜你喜欢
  • 2022-12-23
  • 2021-11-29
  • 2021-04-03
  • 2022-02-08
  • 2022-12-23
  • 2021-11-07
  • 2021-12-26
相关资源
相似解决方案