您的位置:首页 > 其它

Handler详解系列(二)——主线程向自身消息队列发消息

2014-10-12 10:53 369 查看
MainActivity如下:

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐