Android:Handler
Different Ways to update UI in a none-ui thread:
The following is a little demo showing three different ways to update ui in a none-ui thread and the best way i will commend is by a Handler.
package com.slowalker.handlerdemo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.Window; public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); private static final boolean DEBUG = true; private static final int FLAG_INVALIDATE = 0x100; private Ball mBall; /*create a handler.*/ private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg == null) { return; } switch (msg.what) { case FLAG_INVALIDATE: mBall.invalidate(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(mBall = new Ball(this)); //testWay1(); //testWay2(); testWay3(); } /*The first way to update UI in a none-ui thread --- by Handler*/ private void testWay1() { new Thread(new Runnable() { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { Message msg = Message.obtain(); msg.what = FLAG_INVALIDATE; mHandler.sendMessage(msg); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } /*The second way to update UI in a none-ui thread by View.postInvalidate()*/ private void testWay2() { new Thread(new Runnable() { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { /*If you use invalidate(), app will crash.*/ mBall.postInvalidate(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } /*The third way to update UI in a none-ui thread by Handler.post().*/ private void testWay3() { mHandler.post(new Runnable() { @Override public void run() { Message msg = Message.obtain(); msg.what = FLAG_INVALIDATE; mHandler.sendMessageDelayed(msg, 1000); } }); } /*Draw a ball on mobile screen.*/ private class Ball extends View { private final String TAG = Ball.class.getSimpleName(); private float posX = 10; public Ball(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { if (DEBUG) { Log.d(TAG, "onDraw"); } super.onDraw(canvas); posX += 10; if (DEBUG) { Log.d(TAG, "posX = " + posX); } Paint mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.GREEN); canvas.drawCircle(posX, 50, 50, mPaint); } } }