首页 > 代码库 > 从零开始学android<Message消息机制.四十二.>

从零开始学android<Message消息机制.四十二.>

ndroid.os.Message的主要功能是进行消息的封装,并且同时可以指定消息的操作形式。
No.
变量或方法
类型
描述
1
public int what
变量
用于定义此Message属于何种操作
2
public Object obj
变量
用于定义此Message传递的信息数据
3
public int arg1
变量
传递一些整型数据时使用,一般很少使用
4
public int arg2
变量
传递一些整型数据时使用,一般很少使用
5
public Handler getTarget()
普通
取得操作此消息的Handler对象

可以使用 Handler 和Message处理后台耗时操作最后更新到前台UI。



使用Hander与Message下载网络图片

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:src=http://www.mamicode.com/"@drawable/ic_launcher" />>

package com.example.message1;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
	public static final String URL = "http://www.baidu.com/img/baidu_sylogo1.gif";
	public static final int SUCCESS_CODE = 1;
	private Button button;
	private ImageView imageView;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button = (Button) this.findViewById(R.id.button1);
		imageView = (ImageView) this.findViewById(R.id.imageView1);
		
		final ProgressDialog dialog = new ProgressDialog(
				MainActivity.this);
		dialog.setTitle("加载图片");
		dialog.setMessage("正在加载请稍后……");
		dialog.setCancelable(false);

		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(new MyThread()).start();
				dialog.show();
			}
		});
//		前台UI的更新
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
//				取得Bitmap图片
				Bitmap bitmap = (Bitmap) msg.obj;
//				为图片设置资源
				imageView.setImageBitmap(bitmap);
//				判断图片是否获得,并关闭对话框
				if (msg.what == SUCCESS_CODE) {
					dialog.dismiss();
				}
			}

		};
	}
//后台线程
	class MyThread implements Runnable {

		@Override
		public void run() {
			Bitmap bitmap = null;
			// TODO Auto-generated method stub
			try {
				URL url = new URL(URL);//创建Url对象
				InputStream inputStream = url.openStream();//获得输入流
				bitmap = BitmapFactory.decodeStream(inputStream);//将输入流转换为Bitmap对象
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			创建Message对象,返回信息
			Message message = Message.obtain();
			message.obj = bitmap;
			message.what = SUCCESS_CODE;
			handler.sendMessage(message);

		}

	}
}







接下来,我们来从基础开始学习。

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="150dp"
        android:text="获取数据" />

</RelativeLayout>

package com.example.message2;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {<span style="white-space:pre">	</span>private Button button;<span style="white-space:pre">	</span>private TextView textView;<span style="white-space:pre">	</span>private Handler handler;<span style="white-space:pre">	</span>@Override<span style="white-space:pre">	</span>protected void onCreate(Bundle savedInstanceState) {<span style="white-space:pre">		</span>super.onCreate(savedInstanceState);<span style="white-space:pre">		</span>super.setContentView(R.layout.activity_main);<span style="white-space:pre">		</span>button = (Button) this.findViewById(R.id.button1);<span style="white-space:pre">		</span>textView = (TextView) this.findViewById(R.id.info);<span style="white-space:pre">		</span>handler = new Handler() {<span style="white-space:pre">			</span>@Override<span style="white-space:pre">			</span>public void handleMessage(Message msg) {<span style="white-space:pre">				</span>// TODO Auto-generated method stub<span style="white-space:pre">				</span>int what = msg.what;<span style="white-space:pre">				</span>int arg1 = msg.arg1;<span style="white-space:pre">				</span>int arg2 = msg.arg2;<span style="white-space:pre">				</span>Object obj = msg.obj;<span style="white-space:pre">				</span>List<Integer> list = null;<span style="white-space:pre">				</span>Bundle bundle = null;<span style="white-space:pre">				</span>bundle = msg.getData();//接受Bundle数据<span style="white-space:pre">				</span>list =bundle.getIntegerArrayList("num");//解析数据<span style="white-space:pre">				</span>for (Integer num : list) {<span style="white-space:pre">					</span>System.out.print("--list:"+num);<span style="white-space:pre">				</span>}<span style="white-space:pre">				</span>System.out.println("what:" + what + ",arg1:" + arg1 + ",arg2:"<span style="white-space:pre">						</span>+ arg2 + ".obj:" + obj);<span style="white-space:pre">			</span>}<span style="white-space:pre">		</span>};<span style="white-space:pre">		</span>button.setOnClickListener(new View.OnClickListener() {<span style="white-space:pre">			</span>@Override<span style="white-space:pre">			</span>public void onClick(View v) {<span style="white-space:pre">				</span>// TODO Auto-generated method stub<span style="white-space:pre">				</span>new Thread(new MyThread()).start();<span style="white-space:pre">			</span>}<span style="white-space:pre">		</span>});<span style="white-space:pre">	</span>}<span style="white-space:pre">	</span>class MyThread implements Runnable {<span style="white-space:pre">		</span>@Override<span style="white-space:pre">		</span>public void run() {<span style="white-space:pre">			</span>// TODO Auto-generated method stub<span style="white-space:pre">			</span>// Message message=new Message();<span style="white-space:pre">			</span>// message.arg1=1;<span style="white-space:pre">			</span>// message.arg2=2;<span style="white-space:pre">			</span>// message.obj=3;<span style="white-space:pre">			</span>// message.what=4;<span style="white-space:pre">			</span>// handler.sendMessage(message);<span style="white-space:pre">			</span>// 第二种方法<span style="white-space:pre">			</span>// Message message=Message.obtain();<span style="white-space:pre">			</span>// message.what=1;<span style="white-space:pre">			</span>// message.arg1=2;<span style="white-space:pre">			</span>// message.arg2=3;<span style="white-space:pre">			</span>// message.obj=4;<span style="white-space:pre">			</span>// handler.sendMessage(message);<span style="white-space:pre">			</span>// 第三种方法<span style="white-space:pre">			</span>// Message message=Message.obtain(handler);<span style="white-space:pre">			</span>// message.what=1;<span style="white-space:pre">			</span>// message.arg1=2;<span style="white-space:pre">			</span>// message.arg2=3;<span style="white-space:pre">			</span>// message.obj=4;<span style="white-space:pre">			</span>// message.sendToTarget();<span style="white-space:pre">			</span>// 第四种方法<span style="white-space:pre">			</span>// Message message=Message.obtain(handler, 1);<span style="white-space:pre">			</span>// message.arg1=2;<span style="white-space:pre">			</span>// message.arg2=3;<span style="white-space:pre">			</span>// message.obj=4;<span style="white-space:pre">			</span>// message.sendToTarget();<span style="white-space:pre">			</span>// 第五种方法<span style="white-space:pre">			</span>// Message message=Message.obtain(handler, 1, 4);<span style="white-space:pre">			</span>// message.arg1=2;<span style="white-space:pre">			</span>// message.arg2=3;<span style="white-space:pre">			</span>// message.sendToTarget();<span style="white-space:pre">			</span>// 第六种方法<span style="white-space:pre">			</span>// Message message=Message.obtain(handler, 1, 2, 3);<span style="white-space:pre">			</span>// message.obj = 4;<span style="white-space:pre">			</span>// message.sendToTarget();<span style="white-space:pre">			</span>// 第七种方法<span style="white-space:pre">			</span>// Message message=Message.obtain(handler, 1, 2, 3, 4);<span style="white-space:pre">			</span>// message.sendToTarget();<span style="white-space:pre">			</span>// 第八种方法<span style="white-space:pre">			</span>Message message = Message.obtain(handler, 1, 2, 3, 4);<span style="white-space:pre">			</span>Bundle bundle = new Bundle();<span style="white-space:pre">			</span>List<Integer>list=new ArrayList<Integer>();<span style="white-space:pre">			</span>list.add(5);<span style="white-space:pre">			</span>list.add(6);<span style="white-space:pre">			</span>list.add(7);<span style="white-space:pre">			</span>bundle.putIntegerArrayList("num", (ArrayList<Integer>)list);<span style="white-space:pre">			</span>message.setData(bundle);<span style="white-space:pre">			</span>message.sendToTarget();<span style="white-space:pre">		</span>}<span style="white-space:pre">	</span>}}

我们仅给出最后一只方法的演示


打开logcat 在System.out的过滤器中显示









使用Send和psot发送消息




点击获取信息后,将在3秒后在控制台输出






DEMO  使用hander 实现应用程序的第一屏

主要使用pos方法进行延时操作
当然,此操作需要实现准备一张图片,作为背景。

第一屏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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src=http://www.mamicode.com/"@drawable/logo" />>

主界面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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="主界面" />

</LinearLayout>


第一屏JAVA
package com.example.message4;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {
	public static final int SIGHT_TIME = 3000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//设置应用没有标题
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//以上两个设置都必须放在setContentView之前,不然会出现异常
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, Two.class);
				startActivity(intent);
				finish();
			}
		}, SIGHT_TIME);
	}
}


第二屏JAVA文件

package com.example.message4;

import android.app.Activity;
import android.os.Bundle;

public class Two extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.main);

	}
}





3秒后自动进入主界面

当然,实现应用的第一屏效果可以使用多种方法实现,在这里知识其中的一种,读者也可以直接使用线程进行操作。


下节预报:Service 服务

从零开始学android<Message消息机制.四十二.>