第80章、Handle-Message-Looper消息机制之一(从零开始学Android)

  本章着重了解一下Handle、Message、Looper用法。

一、设计界面

  1、布局文件

  打开res/layout/activity_main.xml文件。
  输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnmain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自主线程发送消息给自己" />

    <Button
        android:id="@+id/btnother"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自其它线程发送消息至主线程" />
    
        <TextView
        android:id="@+id/tvmsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    

</LinearLayout>


二、程序文件

  打开“src/com.genwoxue.handlemessageloop/MainActivity.java”文件。
  然后输入以下代码:

package com.genwoxue.handlemessageloop;

import android.app.Activity;  
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.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.TextView;  

public class MainActivity extends Activity{  
	      
		private static long s=0;
	    private String TAG = "HandlerTest";  
	    private ReceiveMessageThread receiveMessageThread =null;  
	    private EventHandler mHandler = null;   
	      
	    private Button btnMain = null;  
	    private Button btnOther = null;  
	    private TextView tvMsg = null; 
	    
	    @Override  
	    public void onCreate(Bundle savedInstanceState) {  
	        super.onCreate(savedInstanceState);  
	        setContentView(R.layout.activity_main);  
	        
	        btnMain = (Button)super.findViewById(R.id.btnmain);  
		    btnOther = (Button)super.findViewById(R.id.btnother);  
		    tvMsg = (TextView)super.findViewById(R.id.tvmsg);  
	        
		    btnMain.setOnClickListener(new OnClickListener(){
	        	@Override 
	        	public void onClick(View v){
	        		 //主线程发送消息给自己   
		            Looper looper = Looper.myLooper();//get the Main looper related with the main thread    
		            //如果不给任何参数的话会用当前线程对应的Looper(这里就是Main Looper)为Handler里面的成员mLooper赋值   
		            mHandler = new EventHandler(looper);  
		            // 清除整个MessageQueue里的消息     
		            mHandler.removeMessages(0);  
		            String obj = "This main thread's message and received by itself!";  
		              
		            Message msg = mHandler.obtainMessage(1,1,1,obj);  
		            // 将Message对象送入到main thread的MessageQueue里面    
		            mHandler.sendMessage(msg);  
	        	}
	        });

	        btnOther.setOnClickListener(new OnClickListener(){
	        	
	        	@Override 
	        	public void onClick(View v){
	        		 //other线程发送消息给主线程   
		            receiveMessageThread = new ReceiveMessageThread();    
		            receiveMessageThread.start();    
	        	}
	        });
	    
	    }  
	      
	    class EventHandler extends Handler{  
	          
	        public EventHandler(Looper looper){  
	            super(looper);  
	        }  
	          
	        public EventHandler(){  
	            super();  
	        }  
	        @Override  
	        public void handleMessage(Message msg) {  
	            super.handleMessage(msg);  
	            Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());  
	            switch(msg.what){  
	            case 1:  
	            	tvMsg.setText((String)msg.obj);  
	                break;  
	         	default:  
	                Log.e(TAG,(String)msg.obj);  
	                break;  
	            }  
	        }  
	          
	    }  
	      
	    //ReceiveMessageThread has his own message queue by execute Looper.prepare();    
	    class ReceiveMessageThread extends Thread {  
	          
	        @Override  
	        public void run(){  
	            Looper.prepare();  
		          
	            	Looper looper = Looper.getMainLooper();    
		            mHandler = new EventHandler(looper);  
		            mHandler.removeMessages(0);  
		            
		            s=s+1;
		            Message msg =new Message();
		            msg.what=1;
		            msg.obj= String.valueOf(s);  
		            // 将Message对象送入到main thread的MessageQueue里面    
		            mHandler.sendMessage(msg); 
		            try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
		            
	             Looper.loop();  
	        }  
	    }  
	      
}  


三、配置文件

  打开“AndroidManifest.xml”文件。

  然后输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.genwoxue.handlemessageloop"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.genwoxue.handlemessageloop.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

  注意:采用默认AndroidManifest.xml即可,无需额外配置。

四、运行结果

   

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋会全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值