如何从线程传递的进步价值的活动? [英] How to pass progress value from thread to activity?

查看:127
本文介绍了如何从线程传递的进步价值的活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从类调用从一个线程在活动类更新GUI设计问题发送进度条的值,如下面的

I am having a design issue sending progress bar value from class called from a Thread in Activity class to update the GUI, as the following

[在code段不编译它的解释只有]:

[The code snippet don't compile it's for explaining only]:

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
       }

    }

}

任何帮助或指导将大大pciated AP $ P $

Any help or guide would be greatly appreciated

推荐答案

您可以做出A级的updateProgressBar方法,然后通过B类的引用,B级A级便可以调用一个回调函数(可能会通过int或东西来表示多远的进展)。从一个不同的线程更新UI然后UI线程趋向于引起问题。幸运的是,活动类有方法runOnUiThread(Runnable的行动)。因此,要设置,你可以做这样的事情的进展情况:

You could make an updateProgressBar method in class A and then pass class B a reference to class A. Class B could then call the callback function in A (probably pass an int or something to indicate how far the progress is). Updating the UI from a different thread then the UI thread tends to cause problems. Luckily the Activity class has the method "runOnUiThread(Runnable action)". So to set the progress you could do something like:

while(response.read()){
  //do stuff here
int progress = getProgress(); //set the progress to something
  a.runOnUiThread(new Runnable(){
    a.updateProgress(progress);
  });
}

这篇关于如何从线程传递的进步价值的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆