[英]Toast can't be used in new runnable?
as the title,i was used toast in runnable but there is an error my code: 作为标题,我曾经在可运行的烤面包机上使用过,但是我的代码有一个错误:
public Runnable backgroud=new Runnable(){
public void run() {
// TODO Auto-generated method stub
try
{
while(!Thread.interrupted())
{
String msg="this is a test";
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Thread.sleep(1000);
}
}
catch(InterruptedException c)
{
c.printStackTrace();
}
}
};
you can not use toast directly in other thread but there is a solution you create your msgHandler 您不能在其他线程中直接使用Toast,但是有一种解决方案可以创建msgHandler
mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
String mString=(String)msg.obj;
Toast.makeText(this, mString, Toast.LENGTH_SHORT).show();
}
};
after that you pass message from your thread 之后,您通过线程传递消息
new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.interrupted())
{
Message msg=new Message();
msg.obj="your text";
mHandler.sendMessage(msg);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
You cannot use Toasts ( or anything that shows something on the UI ) from other threads. 您不能从其他线程使用Toasts(或在UI上显示内容的任何东西)。
See runOnUiThread 参见runOnUiThread
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.