Ahm*_*ali 6 java multithreading android handlers progressdialog
我有一个设计问题,从活动类中的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
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助或指南将不胜感激
小智 2
您可以在 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);
});
}
Run Code Online (Sandbox Code Playgroud)