Progressbar Update From Within Handler
Solution 1:
Let this my example of right use of Handler
.
Handlerhandler=newHandler() {
@OverridepublicvoidhandleMessage(Message msg) {
bar.incrementProgressBy(5);
if (bar.getProgress() == 100) {
bar.setProgress(0);
Toast.makeText(ThreadsDemoActivity.this, "Progress is finished.", Toast.LENGTH_SHORT).show();
}
}
};
Then you have to create Thread
(now it do only some simulation or work)
@OverridepublicvoidonStart() {
super.onStart();
bar.setProgress(0);
Thread backgroundThread = newThread(newRunnable() {
publicvoidrun() {
try {
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(300);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
}
}
});
isRunning = true;
backgroundThread.start();
}
publicvoidonStop() {
super.onStop();
isRunning = false;
}
Also in onCreate
method you have to declare and initialise progressBar
bar = (ProgressBar) findViewById(R.id.progBar)
So this is good but not always. More complex approach offers AsyncTask
. It's very complex and strong tool and when i would recommend to you something so clearly it's AnyncTask
. It's generic type and has one method named doInBackground()
that are using for long-time tasks and trasfers your task to background. There is one rule that you cannot update UI
from background thread. You cannot but AsyncTask
offers onProgressUpdate()
method that are using for updating UI
. But enough, if you want, have look at AsyncTask.
Regards
Solution 2:
you should use Thread
orAsyncTask for that,And only handler update progressBar meanwhile you sync all the data.
See this Example and put your sync code in doInBackground method
Post a Comment for "Progressbar Update From Within Handler"