[英]Run thread from another thread
I test the following code and the Toast message did not appear and the "TestMethod" did not call "Catch" method , please help me ? 我测试下面的代码并没有出现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();
}
May be runOnUiThread helpful to you. 可能runOnUiThread对你有帮助。
Try this: 尝试这个:
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
});
You can make a toast only from the UI Thread . 您只能从UI线程进行干杯。 If you have access to the activity, you can change your code like 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)
{
}
}
});
}
This is the complete solution and it should work perfectly Some methods will only run on the uithread, (runOnUiThread is a method on the activity, so if you can't reach it, than just put a variable 这是完整的解决方案,它应该可以正常工作有些方法只能在uithread上运行,(runOnUiThread是一个关于活动的方法,所以如果你不能达到它,那么只需要放一个变量
private final Activity activity = this;
and call the runOnUiThread from there 并从那里调用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();
} }
The thread you are using does not allows toast to show. 您正在使用的线程不允许toast显示。 You must do UI related stuff on a UI thread.
您必须在UI线程上执行与UI相关的内容。 If you are not on Main Thread, then you need to use runOnUiThread.
如果您不在主线程上,则需要使用runOnUiThread。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.