Android——Message消息机制
Message是线程之间传递信息的载体,包含了对消息的描述和任意的数据对象。Message中包含了两个额外的 int字段和一个object字段,这样在大部分情况下,使用者就不需要再做内存分配工作了。虽然Message的构造函数是public的,但是最好是使用Message.obtain( )或Handler.obtainMessage( )函数来获取Message对象,因为Message的实现中包含了回收再利用的机制,可以提供效率。
下面来看一个小案例,开启线程发送当前执行进程在页面接收并显示:
执行,会先开启主线程,之后点启动线程,开启新线程执行,页面接收显示进度(循环1-100),线程结束后页面显示执行完毕。
执行完毕后:
代码:
activity_main.xml中定义一个按钮和文本
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动线程"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"/>
</LinearLayout>
MainActivity.java中实现传输消息和接收消息
package com.example.messagedemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable, OnClickListener {
private static final String TAG = "MessageDemo";
private Button button1;
private TextView text;
private Handler handler = new Handler(){ //消息管理器,直接使用匿名类
@Override
public void handleMessage(Message msg) {//覆盖handleMessage方法
switch (msg.what) { //根据收到的消息的what类型处理
case 1:
String str = (String)msg.obj; //接收消息
text.setText(str);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.text);
button1.setOnClickListener(this);
Log.i(TAG, "主线程: "+Thread.currentThread().getId());
}
@Override
public void run() {
Log.i(TAG, "线程:"+Thread.currentThread().getId()+"开始运行");
for(int i = 0; i < 100; i++){
try {
Thread.sleep(100);
Message msg = handler.obtainMessage(); //利用handler发送消息
msg.what = 1;
msg.obj = "子线程执行了:"+i+"%"; //发送当前进程
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消息处理
Message msg = handler.obtainMessage();
msg.what = 1;
msg.obj = "子线程执行完毕";
handler.sendMessage(msg); //发送消息
Log.i(TAG, "线程:"+Thread.currentThread().getId()+"结束运行");
}
//点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
new Thread(this).start();
break;
default:
break;
}
}
}