Android架构分析之Android消息处理机制(一)

作者:刘昊昱 

博客:http://blog.csdn.net/liuhaoyutz

Android版本号:4.4.2 


在这个系列文章中我们将来分析Android消息处理机制。

本文介绍了一个使用Handler的Android应用程序,通过该程序,我们能够了解Handler的基本使用方法。进而在后面的文章中,我们会扩展到Looper、Message、MessageQueue、Runnable等Android对象,对它们的实现进行具体分析,这些对象组成了Android消息处理系统。

在Android应用程序中,假设要运行一个用时比較长的操作。比如訪问网络,为了避免出现No Response错误。我们要将该操作放在一个单独的线程中运行。

可是假设该操作完毕后。须要改动UI界面,则会出现故障。由于除了UI线程,其他线程不能改动UI界面,这样的情况下,能够使用handler。以下我们来看一个样例,程序运行效果例如以下:


点击Button1button后,该程序执行一个用时比較长的操作(我们用sleep10秒钟来模拟该操作),然后在主界面上显示“Button1 is clicked!”。执行效果例如以下:

点击Button2button后,该程序执行一个用时比較长的操作(我们用sleep10秒钟来模拟该操作),然后在主界面上显示“Button2 is clicked!”,执行效果例如以下:

以下我们来看这个程序代码。

主程序TestHandlerActivity.java内容例如以下:

package com.haoyu.testHandler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TestHandlerActivity extends Activity implements OnClickListener{
	TextView textView;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button1 = (Button) findViewById(R.id.button1);    
        Button button2 = (Button) findViewById(R.id.button2);
        textView = (TextView) findViewById(R.id.textView);
        
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);        
    }
    
    public Handler handler =new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if(msg.what == 1)
				textView.setText("Button1 is clicked!");
			else if(msg.what == 2)
				textView.setText("Button2 is clicked!");
			else
				textView.setText("Unknown message!");
		}    	
    };
    
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
	
		if(id == R.id.button1)
		{
			new Thread(new BackgroundTask(handler, 1)).start();
		}
		if(id == R.id.button2)
		{
			new Thread(new BackgroundTask(handler, 2)).start();
		}
	}
}


BackgroundTask.java文件内容例如以下:

package com.haoyu.testHandler;

import android.os.Handler;
import android.os.Message;

public class BackgroundTask implements Runnable {
	Handler mHandler;
	int mFlag;
	
	BackgroundTask(Handler handler, int flag) {
		mHandler = handler;
		mFlag = flag;
	}
	
	@Override
	public void run() {
		Message message = new Message();
		// TODO Auto-generated method stub
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 message.what = mFlag;
		 mHandler.sendMessage(message);
	}
	
}


主布局文件main.xml内容例如以下:

<?

xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >" <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="60dp" android:textSize="20dp" android:gravity="center" android:id="@+id/textView" android:text="@string/prompt" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:orientation="horizontal" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button1" android:id="@+id/button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Button2" android:id="@+id/button2" /> </LinearLayout> </LinearLayout>



原文地址:https://www.cnblogs.com/gccbuaa/p/6747953.html