package com.example.threadhandlertest;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.view.Menu;import android.widget.TextView;public class ThreadHandlerTest extends Activity {private Handler handler;private TextView tv;private int i = 0;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv = (TextView) findViewById(R.id.textView1);// 得到当前线程的Looper实例,由于当前线程是UI线程也可以通过Looper.getMainLooper()得到Looper looper = Looper.myLooper();// 此处甚至可以不需要设置Looper,因为 Handler默认就使用当前线程的Looperhandler = new MyHandler(looper);new Thread() {@Overridepublic void run() {while (true) {i++;// 创建Message对象,并把i赋给它Message msg = Message.obtain();msg.what = 0;msg.obj = i;handler.sendMessage(msg);try {Thread.sleep(5000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();}// 自定义handlerclass MyHandler extends Handler {public MyHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {// 处理message传过来的信息switch (msg.what) {case 0:tv.setText(msg.obj.toString());break;}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}


更多相关文章

  1. Android AsyncTask实例
  2. android 判断是否在主线程的方法
  3. android解决UI阻塞问题——创建AsyncTask 子线程
  4. 【android-tips】android程序执行adb shell命令(实例源码)
  5. android skia 使用实例
  6. android 开发实例底部导航(1)
  7. Android View之组合控件实例(一)

随机推荐

  1. android:hintText与android:inputType详
  2. android:paddingLeft和android:layout_ma
  3. 最近总结的android疑惑
  4. android 开发环境的搭建
  5. Android(安卓)AOSP基础(五)不会调试系统源
  6. android 相对布局属性
  7. Android的UI书写的四种方法
  8. Controls over the EditText and the IME
  9. android系统定制从听说到入门三
  10. Android(安卓)xml资源文件中@、@android: