I have a very simple question:
Is or is it not possible to inflate a view (not add it to layout) in a background thread (ex: in the doInBackground of an AsyncTask)?
I know that it is possible, because I have implemented most Activities in my application this way and never had a problem, until I had this problem on a Galaxy S: Android: android.view.InflateException: Binary XML file line #13: Error inflating class <unknown> in SAMSUNG Galaxy S
I’ve been told that I should not inflate Views in background threads, but what are the specific reasons and why does my aproach work in most devices but not in Galaxy S?
The
LayoutInflaterdoes not make any assumptions about what thread it runs on. And nothing is mentioned about this in its documentation. Also its code seams to be thread-agnostic.On the other hand, Views that are created by
LayoutInflatermight instantiateHandlers in their constructors. Well, they probably shouldn’t do that, but there is no requirement for them to not create/useHandlers in their constructors.My guess is that Samsung Galaxy S had some modifications in its
EditTextthat somehow triggers creation ofHandler(according to crash log from your other question instance ofGestureDetectorwas instantiated which in turn created newHandler). While default implementation doesn’t do this.Overall, I’d say that because there is no explicit requirement for
Views to not useHandlers andLoopers in their constructors you can’t assume inflating Views from non-UI thread is safe.You can actually create
HandlerThreadand try inflatingViews inside it. But I’d say this is very risky, as in Samsung Galaxy S example the view assumes that this thread will be alive duringViewlifetime and will process all messages using itsLooper. Which might result in crash later on.