首页 > 移动平台 > 详细

android 只有主线程能更新UI

时间:2014-02-20 00:00:38      阅读:454      评论:0      收藏:0      [点我收藏+]

  如果新建一个Thread,那么不能在这个Thread中直接更新UI,因为只有主线程才能更新UI。

      解决的办法如下:

     1, 在Activity中声明一个Handller变量,重写HandleMessage(Message msg)函数,在函数内更新UI

     

bubuko.com,布布扣
1 Handler handler= new Handler(){
2     @Override
3     public void handleMessage(Message msg){
4         TextView myTextView=(TextView )findViewById(R.id.MyTextView);
5         myTextView.setText("Button Pressed");
6     }
7     };
bubuko.com,布布扣

       

    2,在新建的Thread线程中,handler.sendEmptyMessage(0); 这样会回调 handler的handleMessage函数

         

bubuko.com,布布扣
Runnable runnable=  new Runnable() {
            public void run() {
                
                long endTime=System.currentTimeMillis()+20*1000;
                while (System.currentTimeMillis()<endTime) 
                {
                    synchronized (this) {
                        try {
                               wait(endTime - System.currentTimeMillis());
                             } catch (Exception e) {
                            }
                        }
                    
                    handler.sendEmptyMessage(0);
                }
            }
        } ;
        
        
        Thread thread=new Thread(runnable);
        thread.start();
bubuko.com,布布扣

 

   

android 只有主线程能更新UI

原文:http://www.cnblogs.com/wudizbb/p/3555896.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!