做一个简单的关于Handler,Looper,Message的小演示,代码主界面一个Button按钮,点击发送消息(累计)给线程的Looper循环,然后在LogCat中打印出来:
package zhangphil.looper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
private Handler mHandler;
private final int MESSAGE_WHAT = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
private int count = 0;
@Override
public void onClick(View v) {
mHandler.obtainMessage(MESSAGE_WHAT, count).sendToTarget();
button.setText("发送了 " + count);
count++;
}
});
new MessageReceiveThread().start();
}
private class MessageReceiveThread extends Thread {
@Override
public void run() {
Looper.prepare();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WHAT:
String text = msg.obj + "";
Log.d("收到-->", text);
break;
}
}
};
Looper.loop();
}
}
}
MainActivity.java需要的activity_main.xml文件:
<RelativeLayout xmlns:android="http:///apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button"
android:text="发送消息"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>