0

我想Toast在线程内显示消息..但我得到

RunTimeException:Can't create handler inside thread that has not called Looper.prepare()

请帮我。提前致谢。

4

2 回答 2

11

在您的线程中尝试以下代码

runOnUiThread(new Runnable() 
        {                
            @Override
            public void run() 
            {
                //Your toast code here
            }
        });

线程是非 GUI 线程并且您无法从非 GUI 线程访问 GUI 元素会发生什么情况

于 2011-02-23T06:21:56.280 回答
4

使用android.os.Handler实例从另一个线程访问 UI 线程:

例如:

class YourUI exends Activity {

    private Handler hm;

    @override
    public void onCreate(Bundle b) {
        // do stuff, and instantiate the handler
        hm = new Handler() {
            public void handleMessage(Message m) {
                // toast code
            }
        };
    }


    public Handler returnHandler(){
        return hm;
    }
}

在非 UI 线程中,使用以下命令:

YourUI.getHandler().sendEmptyMeassage(0);
于 2011-02-23T06:43:13.223 回答