Http://rayleung.javaeye.com/blog/435147
Call the handler. Post (runnable R) method. runnable runs in the thread where the UI is located, so you can directly call view. invalidate ()
1 Package Com. Test. androidtest;
2
3 Import Android. App. activity;
4 Import Android. content. context;
5 Import Android. Graphics. Canvas;
6 Import Android. Graphics. color;
7 Import Android. Graphics. paint;
8 Import Android. OS. Bundle;
9 Import Android. OS. Handler;
10 Import Android. View. view;
11
12 Public Class Testhandler Extends Activity {
13 Private Myview;
14 Private Handler mhandler;
15 Public Void Oncreate (bundle savedinstancestate ){
16 Super . Oncreate (savedinstancestate );
17 Myview = New Myview ( This );
18 Mhandler = New Handler ();
19 Mhandler. Post ( New Runnable (){
20 @ Override
21 Public Void Run (){
22 Myview. invalidate ();
23 Mhandler. postdelayed ( This , 5 );
24 }
25 });
26 Setcontentview (myview );
27 }
28
29 Class Myview Extends View {
30 Private Float X = 0f;
31 Public Myview (context ){
32 Super (Context );
33
34 }
35 Protected Void Ondraw (canvas ){
36 Super . Ondraw (canvas );
37 X + = 1 ;
38 Paint mpaint = New Paint ();
39 Mpaint. setcolor (color. Blue );
40 Canvas. drawrect (X, 40 , X + 40 , 80 , Mpaint );
41 }
42
43 }
44 }
45
Update the UI in the new thread. You can directly post invalidate ()
1 Public Void Oncreate (bundle savedinstancestate ){
2 Super . Oncreate (savedinstancestate );
3 This . Requestwindowfeature (window. feature_no_title );
4
5 Myview = New Myview ( This );
6 This . Setcontentview ( This . Myview );
7 New Thread ( New Mythread (). Start ();
8 }
9
10 Class Mythread Implements Runnable {
11 Public Void Run (){
12 While ( ! Thread. currentthread (). isinterrupted ()){
13 Try {
14 Myview. postinvalidate ();
15 Thread. Sleep ( 100 );
16 } Catch (Interruptedexception e ){
17 Thread. currentthread (). Interrupt ();
18 }
19 }
20 }
21 }
22