文档详情

Handler和HandlerThread.docx

发布:2017-07-06约9.48千字共9页下载文档
文本预览下载声明
Handler和HandlerThread1.什么是Handler?SDK中关于Handler的说明如下:A Handler allows you to send and process Message and Runnable objects associated with a threads MessageQueue. Each Handler instance is associated with a single thread and that threads message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. 1.1Handler的作用There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. 1.1.1发送和处理消息下面的代码对于我们来说又是多么的常见:首先在Activity中创建一个继承自Handler的匿名内部类以及这个类的一个对象Private MainHandler mMainHandler = new MainHandler();privateclass MainHandler extends Handler {publicvoid handleMessage(android.os.Message msg) {switch (msg.what) {caseMSG_MAIN_HANDLER_TEST:Log.d(TAG, MainHandler--handleMessage--thread id = + Thread.currentThread().getId());break;}} };这样在Activity的其他地方就可以通过mMainHandler对象发送消息给Handler处理了Message msg = mMainHandler.obtainMessage(MSG_MAIN_HANDLER_TEST);mMainHandler.sendMessage(msg);【疑问】这里的消息是怎样交给handler处理的,另外当有多个消息的时候处理的先后顺序呢?(下面会进行解答)1.1.2处理runnables方法中的代码除了上述的使用Handler发送以及处理消息外,handler还有一个作用就是处理传递给它的action对象,具体使用步骤示例:1、在主线程中定义Handler对象2、构造一个runnable对象,为该对象实现runnable方法。3、在子线程中使用Handler对象post(runnable)对象.handler.post这个函数的作用是把Runnable里面的run方法里面的这段代码发送到消息队列中,等待运行。如果handler是以UI线程消息队列为参数构造的,那么是把run里面的代码发送到UI线程中,等待UI线程运行这段代码。如果handler是以子线程线程消息队列为参数构造的,那么是把run里面的代码发送到子线程中,等待子线程运行这段代码。Runnable 并不一定是新开一个线程,比如下面的代码中就是运行在UI主线程中的:publicclass TestActivity extends Activity implements OnClickListener {/** Called when the activity is first created. */private Button mBtnTest=null;private Handler myHandler=null;@Overridepublicvoid onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.main);mBtnTest=(Button)findView
显示全部
相似文档