UI (View) refresh in Android
There are many ways to update the view in Android, so you need to distinguish between different application scenarios. I think the most important thing is to clarify the usage of multithreading and double buffering.
1. multithreading and double buffering are not used.
This is the simplest case. Generally, you only want to re-paint the UI when the view changes. You only need to explicitly call the invalidate () method in the view object in the activity. The system automatically calls the ondraw () method of view.
2. multithreading and no dual Buffering
In this case, a new thread needs to be enabled, and the newly opened thread cannot access the view object. Android. View. viewroot $ calledfromwrongthreadexception: only
The original thread that created a view hierarchy can touch its views.
In this case, you need to create a subclass that inherits Android. OS. handler and overwrite handlemessage (Message
MSG) method. Android. OS. handler can send and process messages. You need to send a message to update the UI in the activity, and then your handler (you can use an anonymous internal class) (because the anonymous internal class can access the parent class variable, you can directly call the invalidate () method in the view object ). That is, a message is created and sent in a new thread, and then captured and processed in the main thread.
3. multithreading and dual Buffering
In Android, surfaceview is a subclass of view. It also implements dual buffering. You can define a subclass and implement the surfaceholder. Callback interface. Because the surfaceholder. Callback interface is implemented, the new thread does not need the help of Android. OS. Handler. The lockcanvas () method in surfaceholder can lock the canvas. It is more convenient to draw a new image and call unlockcanvasandpost (canvas) to unlock (Display.