Android Handler,Looper,Message

做一个简单的关于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;@Overrideprotected 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;@Overridepublic void onClick(View v) {mHandler.obtainMessage(MESSAGE_WHAT, count).sendToTarget();button.setText("发送了 " + count);count++;}});new MessageReceiveThread().start();}private class MessageReceiveThread extends Thread {@Overridepublic void run() {Looper.prepare();mHandler = new Handler() {@Overridepublic 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=""android:layout_width="match_parent"android:layout_height="match_parent" ><Buttonandroid:id="@+id/button"android:text="发送消息"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true" /></RelativeLayout>



不要因为生活琐事而烦恼,不要因为儿女情长而忧愁,

Android Handler,Looper,Message

相关文章:

你感兴趣的文章:

标签云: