2011-11-23 183 views
4

我测试下面的代码,Toast消息没有出现,并且“TestMethod”没有调用“Catch”方法,请帮助我?从另一个线程运行线程

public void TestMethod() 
{ 
    Test= new Thread(new Runnable() { 
     public void run() { 
      try{ 
       Catch(); 
      } 
      catch (Exception ioe) 
      { 

      } 

     } 
    }); 
    Test.start(); 
} 
public void Catch() 
{ 
    Test2= new Thread(new Runnable() { 
     public void run() { 
      try{ 
       Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show(); 
      } 
      catch (Exception ioe) 
      { 

      } 

     } 
    }); 
    Test2.start(); 
} 

回答

4

只能从UI线程敬酒。如果你有机会到活动中,你可以改变你的代码像THI

public void TestMethod() 
{ 
    Test= new Thread(new Runnable() { 
     public void run() { 
      try{ 
       Catch(); 
      } 
      catch (Exception ioe) 
      { 

      } 

     } 
    }); 
    Test.start(); 
} 
public void Catch() 
{ 
    activity.runOnUiThread(new Runnable() { 
     public void run() { 
      try{ 
       Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show(); 
      } 
      catch (Exception ioe) 
      { 

      } 

     } 
    }); 

} 
6

可能是runOnUiThread对您有帮助。

  • runOnUiThread让你骑在UI线程上,让你在UI线程上执行动作。

试试这个:

runOnUiThread(new Runnable() 
{ 
     public void run() 
     { 
     Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show(); 
     } 
}); 
5

您应该在UI线程中调用Toast.makeText。阅读this了解更多详情。

2

您正在使用的线程不允许吐司显示。你必须在UI线程上做与UI相关的东西。如果你不在主线程上,那么你需要使用runOnUiThread。

3

这是完整的解决方案,它应该很好地工作 一些方法将只在uithread运行,(runOnUiThread是活性的方法,因此,如果您不能达到它,不​​仅仅是把一个变量

private final Activity activity = this; 

,并呼吁从那里

public void TestMethod() { 
Test= new Thread(new Runnable() { 
    public void run() { 
     try{ 
      Catch(); 
     } 
     catch (Exception ioe) { 
      //always log your exceptions 
      Log.e("simpleclassname", ioe.getMessage(), ioe); 
     } 
    } 
}); 
Test.start(); 
} 
public void Catch() { 
    Test2= new Thread(new Runnable() { 
    public void run() { 
     try{ 
      runOnUiThread(new Runnable() { 
       public void run() { 
        Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show(); 
       }); 
     catch (Exception ioe) { 
      //always log your exceptions 
      Log.e("simpleclassname", ioe.getMessage(), ioe); 
     } 

    } 
}); 
Test2.start(); 

}

的runOnUiThread
相关问题