Android开发中难免要更新UI,比如做一个时钟,时间总要动吧?这时间就要更新UI,但很多时间不方便把更新UI的代码放在主线程中,就比如说做一个精确度到毫秒级的时钟,因为精度是毫秒级的,那么更新时间的频率也要是毫秒级的,不然所谓的毫秒级就没什么意义了。这样一来,就要在很短的时间就更新一次UI,如果放在主线程里做,那么主线程的大部分工作是耗在这了,程序就会很卡,所以一般就会放到一个子线程中去做这些事,这样主线程就不卡了。但是,问题是不能直接在子线程中直接更新UI,先来看一下代码。
先建一个TextView :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
然后用它来显示当前时间,精确到毫秒,因为精确到毫秒,所以要频繁地更新UI,因此要开一个线程,不然在主线程里做这么频繁的操作,程序要卡死咯。如果直接在线程里更新UI如下:
public class MainActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
MyThread thread=new MyThread();
thread.start();
}
class MyThread extends Thread{
@Override
public void run() {
while(true){;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
tv.setText(df.format(new Date()));
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
这样会报错,only the original thread that created a view hierarchy can touch its views,不能直接在非主线程里更新,解决方法是用handler,代码如下:
public class MainActivity extends Activity {
TextView tv;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
tv.setText(df.format(new Date()));
}
};
MyThread thread=new MyThread();
thread.start();
}
class MyThread extends Thread{
@Override
public void run() {
while(true){
handler.sendEmptyMessage(0);
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}