调用主线程从子线程的方法

时间:2012-03-06 05:48:21

标签: android multithreading user-interface thread-safety

在我的应用程序中我使用soap webservice调用,基于webservice调用回复我必须显示一些消息。,

但是在回复后我无法从衍生的子线程中执行此操作

那么如何回到主线程并在我得到的回复后显示

希望这很清楚..帮助我如何实现我的要求

{
Thread t1 = new Thread() {
public void run() {

    String threadName = Thread.currentThread().getName();
    // There will be delay in this statement while fetching a data from webservice
    String  returnfromWebservice =   webservice(xmlDetails, "generateid");
    Log.v("returnfromWebservice",returnfromWebservice);
    if(  ! returnfromWebservice.equalsIgnoreCase("nil")){ 
        gotid = returnfromWebservice;
        gotReply=true;
    //  dothis();// I could able to do this because this method contains widgets
    //  I am gettin the error : Only the original thread that created a view hierarchy can touch its views.
    //I understand this is because childthread has no controls on widget 
    /**Suggest me how to get back to main thread*/
    }
    }};
t1.start();
dothis();// so i am doin here after the completion of it 


}

public void dothis{
if(gotReply){
    idtext.setText(gotid);
    genId.setEnabled(false);
    Toast.makeText(WelcomeScorer.this, "Generated ", 500).show();
}
else{
    Toast.makeText(WelcomeScorer.this, "Try Once More ", 500).show();
    idtext.setText(gotid);
}
}

我是android的新手,在android api中有没有最好的方法来处理这种情况?

2 个答案:

答案 0 :(得分:2)

您应该使用以下代码来触摸其他线程中的ui元素

youractivityname.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

            }
        });

如果你的线程处于相同的活动中,你可以使用它。否则,您应该使用您的活动类对象来运行上述方法。
从您的代码中,您应该调用dothis();在线程完成其工作之后。从它开始,它将在线程启动后立即调用dothis方法,它不关心线程是否完成了它的工作。

答案 1 :(得分:1)

this article中记录了各种方法。使用runOnUiThread可能是最简单的。

相关问题