更改UI线程的第二种方式,通过传递消息给UI线程,让UI线程更改
主要用到的几个类
Message,Hander.Looper
Message
Message获得的方式Message.obtain()、Hander.obtainMessage()、new Meessage()
具有getData()和setData()方法
有五个属性
arg1 如果只需在Message中存放少量的整形数据,使用arg1和arg2比使用setData()节省资源
arg2同上
obj 可以存放任意的数据,使用存放简单数据,其效率也比setdata()高
replyTO指定一个Messenger,可以在其中发送该Message的回复信息(没用过)
what 用来匹配Message的标识符
setData和getData()可以用Bundle 对象来封装数据
Hander
用来发送和接收信息,他有许多方法
Looper
每个线程都唯一对应一个Loop,不管是UI 线程还是非UI线程,只要有looper,其他线程都可以想这个线程发送消息,系统再启动主线程时,会主动给她创建个looper,其余线程需调用Looper.prepare()建立本线程的Loop的对象
另一个方法Loop()让Looper开始工作,从消息队列里取消息,处理消息
Class
package com.example.change_ui2;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.R.integer;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class Main extends Activity {
private int count=0;
private TextView tv;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {//消息匹配
case 6:
tv.setText("count等于"+msg.arg1);
break;
default:
break;
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.tv_id);
new Thread(new Runnable() {
public void run() {
while (true) {
count++;
//将新结果通过Hander对象发送给UI线程
Message message=Message.obtain();
message.what =6;//标识符
message.arg1=count;
handler.sendMessage(message);//发送
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
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=".Main" >
<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>