Original post link: http://rayleung.javaeye.com/blog/411860
When I first came into contact with Android Thread Programming, I used to be like Java and tried to solve the problem using the following code.
Java code
- New thread (New runnable (){
- Public void run (){
- Myview. invalidate ();
- }
- }). Start ();
However, this is not possible because it violates the single-threaded model: Android UI operations are not thread-safe and must be executed in the UI thread. After reading the document and apidemo, I found that the commonly used method is to use handler to update the UI thread.
The function of the following code is very simple: Draw a circle, every 0.1 seconds, the circle moves 10 pixels to 10. However, the process of updating the UI using handler is clearly displayed.
First, create a simple view. The Code is as follows:
Java code
- Package com. Ray. Handler;
- Import Android. content. context;
- Import Android. Graphics. Canvas;
- Import Android. Graphics. color;
- Import Android. Graphics. paint;
- Import Android. Graphics. Point;
- Import Android. Graphics. drawable. drawable;
- Import Android. View. view;
- Public class bounceview extends view {
- Float x = 40;
- Public bounceview (context ){
- Super (context );
- }
- @ Override
- Protected void ondraw (canvas ){
- X + = 10;
- Paint mpaint = new paint ();
- Mpaint. setantialias (true );
- Mpaint. setcolor (color. Green );
- Canvas. drawcircle (x, 40, 40, mpaint );
- }
- }
The code for creating an activity is as follows:
Java code
- Package com. Ray. Handler;
- Import Android. App. activity;
- Import Android. content. context;
- Import Android. Graphics. Canvas;
- Import Android. Graphics. color;
- Import Android. Graphics. paint;
- Import Android. OS. Bundle;
- Import Android. OS. Handler;
- Import Android. OS. message;
- Import Android. View. view;
- Import Android. View. window;
- Public class testhandler extends activity {
- Protected static final int guiupdateidentifier = 0x101;
- Thread myrefreshthread = NULL;
- Bounceview mybounceview = NULL;
- Handler myhandler = new handler (){
- Public void handlemessage (Message MSG ){
- Switch (msg. What ){
- Case testhandler. guiupdateidentifier:
- Mybounceview. invalidate ();
- Break;
- }
- Super. handlemessage (MSG );
- }
- };
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- This. requestwindowfeature (window. feature_no_title );
- This. mybounceview = new bounceview (this );
- This. setcontentview (this. mybounceview );
- New thread (New mythread (). Start ();
- }
- Class mythread implements runnable {
- Public void run (){
- While (! Thread. currentthread (). isinterrupted ()){
- Message message = new message ();
- Message. What = testhandler. guiupdateidentifier;
- Testhandler. This. myhandler. sendmessage (Message );
- Try {
- Thread. Sleep (100 );
- } Catch (interruptedexception e ){
- Thread. currentthread (). Interrupt ();
- }
- }
- }
- }
- }