码迷,mamicode.com
首页 > 移动开发 > 详细

Android Handler,Looper,Message

时间:2015-02-19 09:38:25      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:android

做一个简单的关于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文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button"
        android:text="发送消息"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>



Android Handler,Looper,Message

标签:android

原文地址:http://blog.csdn.net/zhangphil/article/details/43878993

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!