首页 > 代码库 > Android简单的handler处理

Android简单的handler处理

 1 package com.example.androidprojecttest; 2  3 import android.os.Bundle; 4 import android.os.Handler; 5 import android.os.Message; 6 import android.os.Messenger; 7 import android.R.id; 8 import android.app.Activity; 9 import android.content.Intent;10 import android.view.Menu;11 import android.view.View;12 import android.view.View.OnClickListener;13 import android.widget.Button;14 import android.widget.LinearLayout;15 import android.widget.TextView;16 17 public class MainActivity extends Activity {18 19     private TextView tView;20 21     private Handler mHandler = new Handler() {22         @Override23         public void handleMessage(Message msg) {24             // TODO 接收消息并且去更新UI线程上的控件内容25             if (msg.what == 1) {26                 tView.setText(String.valueOf(msg.obj));27             }28             super.handleMessage(msg);29         }30 31     };32 33     @Override34     protected void onCreate(Bundle savedInstanceState) {35         super.onCreate(savedInstanceState);36         setContentView(R.layout.activity_main);37         tView = (TextView) findViewById(R.id.tv);38 39         new Thread() {40             public void run() {41                 try {42                     for (int i = 0; i < 100; i++) {43                         Thread.sleep(500);44                         Message msgMessage=new Message();45                         msgMessage.what=1;46                         msgMessage.obj="更新后的值是:"+i;47                         mHandler.sendMessage(msgMessage);48                     }49                 } catch (Exception e) {50                     e.printStackTrace();51                 }52             }53         }.start();54     }55 56 }