我有一个设计问题,从活动类中的Thread调用的类中发送进度条值以更新GUI,如下所示
[代码片段不编译它仅用于解释]:
Class A : Extend Activity {
new Thread(new Runnable()
{
public void run()
{
B objB = new B();
objB.DownloadFile();
}
}).start();
}
Class B {
public void DownloadFile()
{
... some work [preparing SOAP request]
while(response.read())
{
//send calculated progress to Class A to update the progress value
}
}
}
任何帮助或指南将不胜感激
解决方法
您可以在类A中创建一个updateProgressBar方法,然后向类B传递对类A的引用.然后,类B可以调用A中的回调函数(可能传递一个int或其他东西来指示进度有多远).从不同的线程更新UI然后UI线程往往会导致问题.幸运的是,Activity类的方法是“runOnUiThread(Runnable action)”.因此,要设置进度,您可以执行以下操作:
while(response.read()){
//do stuff here
int progress = getProgress(); //set the progress to something
a.runOnUiThread(new Runnable(){
a.updateProgress(progress);
});
}