activity_main.xml:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="#ff999999"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
MainActivity.java:
package com.example.updateui;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REFRESH_ACTION = 1;
private Button mButton;
private TextView mTextView;
private int mCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView1);
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
new Thread() //worker thread
{
@Override
public void run()
{
while ((mCount < 100))
{
MainActivity.this.runOnUiThread(new Runnable() // 工作线程刷新UI
{ //这部分代码将在UI线程执行,实际上是runOnUiThread post Runnable到UI线程执行了
@Override
public void run()
{
mCount++;
mTextView.setText("I'm updated:"
+ mCount);
Log.i(TAG, "Count:" + mCount);
}
});
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
});
}
}
public final void runOnUiThread (Runnable action)
Added in
API level 1
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.
如果当前线程是UI主线程,则直接执行Runnable的代码;否则将Runnable post到UI线程的消息队列。
Parameters
action | the action to run on the UI thread |
---|
Activity.java中:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);//将Runnable Post到消息队列,由内部的mHandler来处理,实际上也是Handler的处理方式
} else {
action.run();//已经在UI线程,直接运行。
}
}