Android:UI更新方法四:在Worker Thread中runOnUiThread直接刷新UI

activity_main.xml:



    

    

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线程,直接运行。
        }
    }


你可能感兴趣的:(Android基础)