java.lang.RuntimeException的:内螺纹尚未调用无法建立处理活套prepare(); [英] java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();
问题描述
我有一个Android应用程序正在运行的线程。我想敬酒消息有消息显示。
I have an Android app running a thread. I want a Toast message to show with a message.
当我这样做,我得到了以下异常:
When I do this, I get the below exception:
的logcat 跟踪:
FATAL EXCEPTION: Timer-0
java.lang.RuntimeException: Can't create handler inside thread that has not
called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast$TN.<init>(Toast.java:322)
at android.widget.Toast.<init>(Toast.java:91)
at android.widget.Toast.makeText(Toast.java:238)
有没有变通的推动敬酒的消息从线程的用户界面?
Is there a work around for pushing Toast messages from threads to the User Interface?
推荐答案
我得到这个例外,因为我试图让从后台线程举杯弹出。
吐司需要一个活动推向用户界面和线程不必说。照片
所以,一个解决办法就是给线程一个链接到一个父活动,并举杯说。
I got this exception because I was trying to make a Toast popup from a background thread.
Toast needs an Activity to push to the user interface and threads don't have that.
So one workaround is to give the thread a link to a parent Activity and Toast to that.
将这个code在线程要发送一个吐司消息:
Put this code in the thread where you want to send a Toast message:
parent.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(parent.getBaseContext(), "Hello", Toast.LENGTH_LONG).show();
}
});
请创建此线程后台线程链接到父活动。将这个变量在你的线程类:
Keep a link to the parent Activity in the background thread that created this thread. Put this variable in your thread class:
private static YourActivity parent;
在创建线程,通过父活动作为参数,通过这样的构造:
When you create the thread, pass the parent Activity as a parameter through the constructor like this:
public YourBackgroundThread(YourActivity parent){
this.parent = parent;
}
现在的后台线程可以把吐司消息到屏幕。
Now the background thread can push Toast messages to the screen.
这篇关于java.lang.RuntimeException的:内螺纹尚未调用无法建立处理活套prepare();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!