在Activity主线程中实例化Handler,不需要定义Looper,因为主线程中有一个默认的Looper对象。而在子线程中实例化Handler,必须要定义Looper循环消息队列和消息队列循环结束。下面我们来一起看一下在主线程中实例化Handler'方式。
整体思路:在xml文件中放置一个Button控件和TextView控件,在activity中,定义一个MyThread类实现Runnable接口,在这个类中重写run方法,在这个方法中定义一个message,赋值数据,并使用handler发送,定义一个MyHandler继承Handler,在这个类的handleMessage方法中接收消息的数据,并绑定到TextView控件上,在Button的点击事件中,开启一个新的线程来启动MyHandler类。
activity_main.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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="116dp"
android:text="发送消息" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
/>
</RelativeLayout>
MainActivity.java文件:
package com.example.android_handler_looper;
//
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView textView;
private MyHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
textView=(TextView)findViewById(R.id.textView1);
// 第一种方式
// Looper looper=Looper.myLooper();
// handler=new MyHandler(looper);
// 第二种方式 在Activity中有一个默认的Looper对象,来处理子线程中发送的消息
handler=new MyHandler();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//启动线程
new Thread(new MyThread()).start();
}
});
}
public class MyThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
Message msg=Message.obtain();
msg.obj="jack";
handler.sendMessage(msg);
}
}
// 定义一个类
public class MyHandler extends Handler{
public MyHandler(){
}
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
textView.setText("接收消息:"+msg.obj);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}