Android异步更新UI的方式之使用Handler消息传递机制

时间:2015-09-15 11:03:52   收藏:0   阅读:202

由于性能要求,android要求只能在UI线程中更新UI,要想在其他线程中更新UI,给大家介绍一种方式:使用Handler消息传递机制。

 

下面用这种方式更新一个TextView:

package com.example.runonuithreadtest; 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.widget.TextView; 
public class MainActivity extends Activity { 
private TextView tv; 
Handler handler = new Handler() 
{ 
  public void handleMessage(android.os.Message msg) { 
   if(msg.what==0x123) 
   { 
    tv.setText("更新后的TextView"); 
   } 
  }; 
}; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  tv = (TextView) findViewById(R.id.tv); 
  new MyThread().start(); 
} 
class MyThread extends Thread 
{ 
  @Override 
  public void run() { 
   //延迟两秒更新 
   try { 
    Thread.sleep(2000); 
   } catch (InterruptedException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
   } 
   handler.sendEmptyMessage(0x123); 
  } 
} 
} 

当然对APP的性能测试,我比较常用的是这个平台:www.ineice.com

原文:http://www.cnblogs.com/tt110/p/4809417.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!