这篇记录 android 消息机制中,MainThread 向 WorkThread 发送消息。( MainThread → WorkThread )
步骤:
1、准备looper对象
2、在子线程中生成handler对象
3、在MainThread发送消息
代码:
layout:
<Button android:id="@+id/buttonId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送消息" />
activity:
package com.away.b_08_handler03; import android.app.Activity; 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; public class MainActivity extends Activity { private Button button; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.buttonId); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("OnClick:" + Thread.currentThread().getName()); Message msg = handler.obtainMessage(); handler.sendMessage(msg); } }); WorkerThread wt = new WorkerThread(); wt.start(); } class WorkerThread extends Thread { @Override public void run() { // 准备Looper对象 Looper.prepare(); // 在Workers Thread当中,生成一个Handler对象,用匿名内部类实现 handler = new Handler() { @Override public void handleMessage(Message msg) { System.out.println("WorkerThread:" + Thread.currentThread().getName()); System.out.println("收到了消息对象!!"); } }; // 调用Looper的loop方法之后,Looper对象将不断地从消息队列当中取出消息对象,然后调用Handler的handleMessage()方法处理该消息对象 // 如果消息队列当中没有对象,则该线程阻塞. Looper.loop(); } } }
效果:
时间: 2024-10-12 23:38:58