简体   繁体   English

无法创建线程中的WebView

[英]A WebView in a thread can't be created

i have some threads in which i create some views and prepare them to be displayed. 我有一些线程,我在其中创建一些视图并准备它们显示。 Among them i also have a WebView. 其中我也有一个WebView。 This code is executed in thread: 此代码在线程中执行:

WebView lGraphWebView = null;
        try{
            lGraphWebView = new WebView(AppController.getAppController());
        }catch (Exception e) {
            Log.d("info", "error: " +e );
        }

and it throws the following exception: 并抛出以下异常:

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

This is a bit strange, because when i create a simple button all is OK. 这有点奇怪,因为当我创建一个简单的按钮时,一切都还可以。 So, can anyone explane to me why on creation of a WebView i get this exception and if Looper.prepare() can help here? 所以,任何人都可以解释为什么在创建WebView时我会得到这个异常,如果Looper.prepare()可以帮到这里吗? Thanks in advance! 提前致谢!

In general, its not safe to create view outside of main thread. 通常,在主线程之外创建视图是不安全的。

In your particular case, this is not allowed, because WebView creates Handler() in its constructor for communication with UI thread. 在您的特定情况下,这是不允许的,因为WebView在其构造函数中创建Handler()以与UI线程进行通信。 But since Handler 's default constructor attaches itself to current thread, and current thread does not have Looper running, you're getting this exception. 但是由于Handler的默认构造函数将其自身附加到当前线程,并且当前线程没有运行Looper ,因此您将获得此异常。

You might think that creating a looper thread (that must be alive at least as long as WebView ) might help you, but this actually a risky way to go. 您可能认为创建一个looper线程(必须至少与WebView一样长)可能会对您有所帮助,但这实际上是一种冒险的方法。 And I wouldn't recommend it. 我不推荐它。

You should stick with creating WebView s in main thread. 你应该坚持在主线程中创建WebView All controls are usually optimized for fast construction, as they are almost always created in UI thread. 所有控件通常都针对快速构造进行了优化,因为它们几乎总是在UI线程中创建。

You should not create or manipulate views in threads other than the main UI thread. 您不应该在主UI线程以外的线程中创建或操作视图。 For instance, you can use the Handler to post to the UI thread: 例如,您可以使用Handler发布到UI线程:

private Handler handler = new Handler();

handler.post(new Runnable() {
   public void run() {
       lGraphWebView = new WebView(AppController.getAppController());
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM