从Handler中更新ProgressBar [英] ProgressBar update from within Handler
问题描述
我有一个同步服务,我想要一个进度条,因为它需要> 1分钟的时间来同步所有数据,并且我不想使用不确定的进度.我有一个用于同步功能的处理程序,正在引用并正确更新progressBar的进度,但UI无法更新.
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);
}
我尝试使用ASynchTask类没有成功.感谢您的帮助.
I have tried using an ASynchTask class with no success. Any help is appreciated.
推荐答案
下面是正确使用Handler
的示例.
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();
}
}
};
然后您必须创建Thread
(现在它仅进行一些模拟或工作)
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;
}
还必须在onCreate
方法中声明并初始化progressBar
Also in onCreate
method you have to declare and initialise progressBar
bar = (ProgressBar) findViewById(R.id.progBar)
所以这很好,但并非总是如此.更复杂的方法提供了AsyncTask
.这是一个非常复杂而强大的工具,当我向您推荐如此清晰的东西时,它是AnyncTask
.它是通用类型,有一个名为doInBackground()
的方法,用于长时间任务,并将您的任务转移到后台.有一个规则,您不能从后台线程更新UI
.您只能AsyncTask
提供用于更新UI
的onProgressUpdate()
方法.但是只要您愿意,就可以看看 AsyncTask .
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.
致谢
这篇关于从Handler中更新ProgressBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!