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();
T开发者_StackOverflow中文版hread.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
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.
See runOnUiThread
精彩评论