Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Offscreen Drawing from non-UI thread

Short verson

Is it allowed, or do I need to use the UI thread?

EDIT: A reference to a place in the official android docs would be ideal.

Long version

Android docs make it clear that it's not allowed to "access the Android UI toolkit from outside the UI thread".

On the other hand, creating Bitmap objects from worker threads seems to be allowed, at least it's being done in sample code: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html Apparently, the Bitmap class is not considered part of the "UI toolkit" as far as threading is concerned.

I've got a piece of code that seems to work when invoked from a non-ui thread. It involves using Bitmap.createBitmap(int,int,Bitmap.Config), new Canvas(bitmap), Typeface.create() and text drawing. My code does not refer to any View object.

Can someone point me to a piece of documentation that says that I may do these things from a background thread? Or will doing this lead to random crashes?

like image 719
wolfgang Avatar asked Oct 10 '22 09:10

wolfgang


1 Answers

UI toolkit means UIs such as buttons, labels, listview, and so on provided by Google. You can't access them from non-ui thread mainly because they are not thread-safe.

What you are doing is not on UI toolkit but on low-level Canvas which is allowed (actually should be allowed) to access from non-ui threads. This mechanism is used in game development all the time. So I believe you are safe.

like image 81
Tae-Sung Shin Avatar answered Oct 13 '22 11:10

Tae-Sung Shin