Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

android - 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. 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? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. But since Handler's default constructor attaches itself to current thread, and current thread does not have Looper running, you're getting this exception.

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. And I wouldn't recommend it.

You should stick with creating WebViews in main thread. All controls are usually optimized for fast construction, as they are almost always created in UI thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...