首页 > 代码库 > android Handler消息通信

android Handler消息通信

 1 package com.example.testhandler; 2  3 import android.os.Bundle; 4 import android.os.Handler; 5 import android.os.Message; 6 import android.app.Activity; 7 import android.view.Menu; 8 import android.widget.TextView; 9 10 public class MainActivity extends Activity {11 12     Handler handler = null;13     String textString = null;14     TextView textView;15     @Override16     protected void onCreate(Bundle savedInstanceState) {17         super.onCreate(savedInstanceState);18         setContentView(R.layout.activity_main);19         textView = (TextView) findViewById(R.id.text);20         Runnable task = new Runnable() {21             22             @Override23             public void run() {24                 textString = "Hello World!";25                 Message msg = new Message();26                 msg.what = 0x123;27                 handler.sendMessage(msg);28             }29         };30         handler = new Handler(){31 32             @Override33             public void handleMessage(Message msg) {34                 //super.handleMessage(msg);35                 if (msg.what == 0x123) {36                     textView.setText(textString);37                 }38             }39             40         };41         42         new Thread(task).start();43         44     }45 46     @Override47     public boolean onCreateOptionsMenu(Menu menu) {48         // Inflate the menu; this adds items to the action bar if it is present.49         getMenuInflater().inflate(R.menu.main, menu);50         return true;51     }52 53 }

 

android Handler消息通信