Android更新UI多线程示例—五秒倒计时
Android UI 中提供invalidate()来更新界面,而invalidate()方法是非线程安全,所以需要借助handler实现。
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sv2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#48000000" >
<TextView
android:id="@+id/number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="360px"
android:textColor="#ffffff"
android:gravity="center"
android:paddingTop="180px" />
</LinearLayout>
</ScrollView>
Test.java:
package com.ucrobotics.test;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.TextView;
public class Test extends Activity {
private ScrollView sv2;
private TextView number;
private CountThread countThread = null;
private Handler handler=null;
private int Count_Num = 5;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
try {
number = (TextView) findViewById(R.id.number);
sv2 = (ScrollView) findViewById(R.id.sv2);
sv2.setFillViewport(true); //让子元素填充
sv2.setBackgroundColor(Color.GREEN);
handler = new Handler();
countThread = new CountThread();
countThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private class CountThread extends Thread{
public void run()
{
while(Count_Num > 0) {
handler.post(runnableUi);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 构建Runnable对象,在runnable中更新界面
Runnable runnableUi = new Runnable(){
@Override
public void run() {
number.setText(Count_Num+"");
Count_Num--;
}
};
}
通过示例可以看出,Layout的更新请求需要通过:handler.post(runnableUi) 发送过去。
运行效果就是启动后,屏幕数字从5倒计时到1...