Starting a thread from another thread

I am testing the following code and the Toast message did not appear and the “TestMethod” did not call the “Catch” method, please help me?

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
source share
5 answers

You can only make a toast from the user interface thread . If you have access to this activity, you can change your code, for example, 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) { } } }); } 
+4
source

Maybe runOnUiThread is useful for you.

  • runOnUiThread allows you to cycle through the user interface thread and allow you to perform actions in the user interface thread.

Try the following:

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

You must call Toast.makeText in the user interface thread. Read this for more details.

+5
source

This is a complete solution, and it should work fine. Some methods will only run on uithread, (runOnUiThread is an activity method, so if you cannot reach it, just put a variable

 private final Activity activity = this; 

and call runOnUiThread from there

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

}

+3
source

The thread you use does not allow toast. You must do the UI related stuff in the UI thread. If you are not in the main topic, you need to use runOnUiThread.

+2
source

Source: https://habr.com/ru/post/1382682/


All Articles