Package
Import
Import
Import
Import
Import
Public class extends
New Handler
Public handleMessage
IncrementProgressBy
False
Public onCreate
Super onCreate
SetContentView
FindViewById
Public onStart
Super onStart
SetProgress
New Thread new Runnable
Public run
Try
For
Sleep
SendMessage obtainMessage
Catch
// just end the background thread
True
Start
Public onStop
Super onStop
False
As part of constructing the , we create an instance of , with our implementation of . Basically, for any message received, we update the by 5 points, then exit the message handler.
In , we set up a background thread. In a real system, this thread would do something meaningful. Here, we just sleep one second, post a to the , and repeat for a total of 20 passes. This, combined with the 5‑point increase in the position, will march the bar clear across the screen, as the default maximum value for is 100. You can adjust that maximum via , such as setting the maximum to be the number of database rows you are processing, and updating once per row.
Note that we then leave . This is crucial. The method is invoked on the activity UI thread, so it can update widgets and anything else that affects the UI, such as the title bar. However, that means we need to get out of , both to let the get its work done, and also so Android does not think our activity is stuck.
The resulting activity is simply a horizontal progress bar (see Figure 15‑1).
Figure 15‑1. The HandlerDemo sample application
Дата добавления: 2015-05-16; просмотров: 750;