在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;
}
}