问题
I have a syncing service that I want a progress bar for, because it takes >1 minute to sync all the data and I don't want to use indeterminate progress. I have a Handler for the syncing functions and am referencing and correctly updating the progressBar's progress but the UI does not update.
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//Sync calls
updateProgress(getContext());
}
};
public static void updateProgress(Context c){
layout = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
progress_view = layout.inflate(R.layout.sync_dialog, null);
mProgressStatus += mProgressStep;
mProgress = (ProgressBar) progress_view.findViewById(R.id.progress);
mProgress.setProgress(mProgressStatus);
}
I have tried using an ASynchTask class with no success. Any help is appreciated.
回答1:
Let this my example of right use of Handler
.
Handler handler = new Handler() {
@Override
public void handleMessage(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)
@Override
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(300);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
}
}
});
isRunning = true;
backgroundThread.start();
}
public void onStop() {
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
回答2:
you should use Thread
or AsyncTask for that,And only handler update progressBar meanwhile you sync all the data.
See this Example and put your sync code in doInBackground method
来源:https://stackoverflow.com/questions/10919508/progressbar-update-from-within-handler