本文共 1326 字,大约阅读时间需要 4 分钟。
做一个简单的关于Handler,Looper,Message的小演示,代码主界面一个Button按钮,点击发送消息(累计)给线程的Looper循环,然后在LogCat中打印出来:
package zhangphil.looper;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.util.Log;import android.view.View;import android.widget.Button;import android.app.Activity;public class MainActivity extends Activity { private Handler mHandler; private final int MESSAGE_WHAT = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { private int count = 0; @Override public void onClick(View v) { mHandler.obtainMessage(MESSAGE_WHAT, count).sendToTarget(); button.setText("发送了 " + count); count++; } }); new MessageReceiveThread().start(); } private class MessageReceiveThread extends Thread { @Override public void run() { Looper.prepare(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_WHAT: String text = msg.obj + ""; Log.d("收到-->", text); break; } } }; Looper.loop(); } }}
MainActivity.java需要的activity_main.xml文件:
转载地址:http://wvttx.baihongyu.com/