Handler详解系列(二)——主线程向自身消息队列发消息
2014-10-12 10:53
369 查看
MainActivity如下:
main.xml如下:
package cc.c; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.app.Activity; /** * Demo描述: * 在主线程中给主线程自己的消息队列发送消息. * * 平常最常用的套路是这样的: * 1 主线中实例化mHandler * 2 在子线程中使用该mHandler向主线程的消息队列发送消息 * * 该示例中在主线程中给主线程自己的消息队列发送消息. * 步骤: * 1 利用getMainLooper()实例化一个Handler * 2 在主线程中发送消息. * * 正因为在初始化一个Handler时候使用的是主线程的Looper(即getMainLooper()) * 那么消息当然是发到了主线程的消息队列.认识到这一点是很重要的. * * 该实例本身没有什么实际使用意义,主要是为了进一步认识Handler的机制. * */ public class MainActivity extends Activity { private TextView mTextView; private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { mTextView = (TextView) findViewById(R.id.textView); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { HandlerTest handlerTest = new HandlerTest(getMainLooper()); Message message = new Message(); message.obj = "Hi~"; handlerTest.sendMessage(message); } }); } private class HandlerTest extends Handler { private HandlerTest(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); mTextView.setText("在主线程中,收到主线程自己的Handler发来消息:" + msg.obj); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:layout_centerHorizontal="true" android:layout_marginTop="70dip" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click" android:layout_centerInParent="true" /> </RelativeLayout>
相关文章推荐
- Handler详解系列(二)——主线程向自身消息队列发消息
- Handler详解系列(三)——在子线程中给主线程的消息队列发送消息
- Handler详解系列(三)——在子线程中给主线程的消息队列发送消息
- Handler详解系列(四)——利用Handler在主线程与子线程之间互发消息,handler详解
- Handler详解系列(四)——利用Handler在主线程与子线程之间互发消息
- Handler详解系列(四)——利用Handler在主线程与子线程之间互发消息
- Handler详解系列——利用Handler在主线程与子线程之间互发消息,handler详解
- Handler详解系列(四)——利用Handler在主线程与子线程之间互发消息,handler详解
- 【VxWorks系列】任务间同步与通信之消息队列
- COM+系列——实战演练MSMQ(消息队列)(二)
- 进程间通信系列 之 消息队列应用实例
- Handler详解系列(一)——Handler异步消息机制详解(附图)
- Handler详解系列(一)——Handler异步消息机制详解(附图)
- Enterprise Library Step By Step系列(十四):创建基于消息队列(MSMQ)的异步日志
- 消息队列 RabbitMQ系列 第四篇:发布/订阅 Publish/Subscribe
- 分布式消息队列kafka系列介绍 — 核心API介绍及实例
- UNIX/Linux进程间通信IPC系列(四)消息队列
- 大数据系列教程_分布式消息队列kafka
- 【本文已迁移到“程序员文摘” http://programmerdigest.cn/category/lajp】LAJP系列教程-第二部分-HelloWorld(Linux 消息队列)
- 当主线程队列,如果处理一个消息超过5秒,android 就会抛出一个 ANP(无响应)的消息