从另一个线程运行线程

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();
 }
5个回答

6

也许runOnUiThread对你有帮助。

  • runOnUiThread可以让你在UI线程上执行操作并对UI线程进行控制。

可以试试这个:

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

5

您应该在UI线程上调用 Toast.makeText 。阅读此文章以获取更多详细信息。


4

你只能在UI线程中制作Toast。如果你可以访问activity,你可以像这样更改你的代码:

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) 
             {

             }

         }
     });

 }

3
这是完整的解决方案,应该可以完美地运行。 有些方法只能在主线程上运行(runOnUiThread是activity上的一个方法,如果您无法访问它,那么只需放置一个变量即可。
private final Activity activity = this;

并从那里调用runOnUiThread

 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();

}


2

您正在使用的线程不允许显示toast。您必须在UI线程上执行与UI相关的操作。如果您不在主线程上,那么您需要使用runOnUiThread。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接