由于子线程不能进行UI更新的操作,因此安卓提供了一套异步消息处理机制,本文先写出Handler和message的用法,下文介绍AsyncTask. 总结一下HandleMessage的用法 1.首先定义一个常量值作为message的标志符 2.实例化一个handler对象,并重写handleMessage方法,在这里对 message进行处理 3.在触发事件中(比如点击事件)中创建一个线程,在线程里新建 Message对象,指 message的值,最后通过handler的sendMessage(message)方法传入message值,并将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" tools:context="${relativePackage}.${activityClass}" > <Button android:id="@+id/bt_changeText" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Change Text" > </Button> <TextView android:id="@+id/tv_change" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/bt_changeText" android:layout_marginLeft="103dp" android:layout_marginTop="121dp" android:text="@string/hello_world" /> </RelativeLayout>MainActivity部分代码
package com.example.handlerdemo; import android.R.integer; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; 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 OnClickListener{ private Button button; private TextView textView; public static final int UPDATE_TEXT=1; private Handler handler=new Handler(){ public void handleMessage(Message msg){ switch (msg.what) { case UPDATE_TEXT: //進行UI操作 textView.setText("hello Shawn"); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); button.setOnClickListener(this); } private void initView(){ button=(Button)findViewById(R.id.bt_changeText); textView=(TextView)findViewById(R.id.tv_change); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bt_changeText: //創建線程 new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Message message=new Message(); message.what=UPDATE_TEXT;//将UPDATE_TEXT传给what handler.sendMessage(message);//将message对象发送出去 } }).start(); break; default: break; } } }